Skip to content

Commit a2ab9e6

Browse files
tmimmanuelobviyus
andauthored
fix: avoid inline dotenv secrets in systemd unit during service repair (#66249) (thanks @tmimmanuel)
* fix(daemon): avoid inline dotenv secrets in systemd unit during service repair * fix(daemon): sanitize systemd envfile and dedupe state-dir resolution * fix(daemon): fail on multiline dotenv values for systemd envfile * test(daemon): cover systemd envfile staging * fix: keep systemd envfile overrides intact (#66249) (thanks @tmimmanuel) --------- Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 3c501d3 commit a2ab9e6

7 files changed

Lines changed: 222 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Docs: https://docs.openclaw.ai
1313
- Media-understanding/attachments: fail closed when a local attachment path cannot be canonically resolved via `realpath`, so a `realpath` error can no longer downgrade the canonical-roots allowlist check to a non-canonical comparison; attachments that also have a URL still fall back to the network fetch path. (#66022) Thanks @eleqtrizit.
1414
- Agents/gateway-tool: reject `config.patch` and `config.apply` calls from the model-facing gateway tool when they would newly enable any flag enumerated by `openclaw security audit` (for example `dangerouslyDisableDeviceAuth`, `allowInsecureAuth`, `dangerouslyAllowHostHeaderOriginFallback`, `hooks.gmail.allowUnsafeExternalContent`, `tools.exec.applyPatch.workspaceOnly: false`); already-enabled flags pass through unchanged so non-dangerous edits in the same patch still apply, and direct authenticated operator RPC behavior is unchanged. (#62006) Thanks @eleqtrizit.
1515
- Telegram/forum topics: persist learned topic names to the Telegram session sidecar store so agent context can keep using human topic names after a restart instead of relearning from future service metadata. (#66107) Thanks @obviyus.
16+
- Doctor/systemd: keep `openclaw doctor --repair` and service reinstall from re-embedding dotenv-backed secrets in user systemd units, while preserving newer inline overrides over stale state-dir `.env` values. (#66249) Thanks @tmimmanuel.
1617

1718
## 2026.4.14-beta.1
1819

‎src/config/state-dir-dotenv.ts‎

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,7 @@ function isBlockedServiceEnvVar(key: string): boolean {
1414
return isDangerousHostEnvVarName(key) || isDangerousHostEnvOverrideVarName(key);
1515
}
1616

17-
/**
18-
* Read and parse `~/.openclaw/.env` (or `$OPENCLAW_STATE_DIR/.env`), returning
19-
* a filtered record of key-value pairs suitable for embedding in a service
20-
* environment (LaunchAgent plist, systemd unit, Scheduled Task).
21-
*/
22-
export function readStateDirDotEnvVars(
23-
env: Record<string, string | undefined>,
24-
): Record<string, string> {
25-
const stateDir = resolveStateDir(env as NodeJS.ProcessEnv);
26-
const dotEnvPath = path.join(stateDir, ".env");
27-
28-
let content: string;
29-
try {
30-
content = fs.readFileSync(dotEnvPath, "utf8");
31-
} catch {
32-
return {};
33-
}
34-
17+
function parseStateDirDotEnvContent(content: string): Record<string, string> {
3518
const parsed = dotenv.parse(content);
3619
const entries: Record<string, string> = {};
3720
for (const [rawKey, value] of Object.entries(parsed)) {
@@ -50,6 +33,27 @@ export function readStateDirDotEnvVars(
5033
return entries;
5134
}
5235

36+
export function readStateDirDotEnvVarsFromStateDir(stateDir: string): Record<string, string> {
37+
const dotEnvPath = path.join(stateDir, ".env");
38+
try {
39+
return parseStateDirDotEnvContent(fs.readFileSync(dotEnvPath, "utf8"));
40+
} catch {
41+
return {};
42+
}
43+
}
44+
45+
/**
46+
* Read and parse `~/.openclaw/.env` (or `$OPENCLAW_STATE_DIR/.env`), returning
47+
* a filtered record of key-value pairs suitable for embedding in a service
48+
* environment (LaunchAgent plist, systemd unit, Scheduled Task).
49+
*/
50+
export function readStateDirDotEnvVars(
51+
env: Record<string, string | undefined>,
52+
): Record<string, string> {
53+
const stateDir = resolveStateDir(env as NodeJS.ProcessEnv);
54+
return readStateDirDotEnvVarsFromStateDir(stateDir);
55+
}
56+
5357
/**
5458
* Durable service env sources survive beyond the invoking shell and are safe to
5559
* persist into gateway install metadata.

‎src/daemon/service-types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,5 @@ export type GatewayServiceRenderArgs = {
5656
programArguments: string[];
5757
workingDirectory?: string;
5858
environment?: GatewayServiceEnv;
59+
environmentFiles?: string[];
5960
};

‎src/daemon/systemd-unit.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,20 @@ describe("buildSystemdUnit", () => {
3838
}),
3939
).toThrow(/CR or LF/);
4040
});
41+
42+
it("renders EnvironmentFile entries before inline Environment values", () => {
43+
const unit = buildSystemdUnit({
44+
description: "OpenClaw Gateway",
45+
programArguments: ["/usr/bin/openclaw", "gateway", "run"],
46+
environmentFiles: ["/home/test/.openclaw/.env"],
47+
environment: {
48+
OPENCLAW_GATEWAY_PORT: "18789",
49+
},
50+
});
51+
expect(unit).toContain("EnvironmentFile=-/home/test/.openclaw/.env");
52+
expect(unit).toContain("Environment=OPENCLAW_GATEWAY_PORT=18789");
53+
expect(unit.indexOf("EnvironmentFile=-/home/test/.openclaw/.env")).toBeLessThan(
54+
unit.indexOf("Environment=OPENCLAW_GATEWAY_PORT=18789"),
55+
);
56+
});
4157
});

‎src/daemon/systemd-unit.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,25 @@ function renderEnvLines(env: Record<string, string | undefined> | undefined): st
3535
});
3636
}
3737

38+
function renderEnvironmentFileLines(environmentFiles: string[] | undefined): string[] {
39+
if (!environmentFiles) {
40+
return [];
41+
}
42+
return environmentFiles
43+
.map((entry) => entry.trim())
44+
.filter(Boolean)
45+
.map((entry) => {
46+
assertNoSystemdLineBreaks(entry, "Systemd EnvironmentFile values");
47+
return `EnvironmentFile=-${systemdEscapeArg(entry)}`;
48+
});
49+
}
50+
3851
export function buildSystemdUnit({
3952
description,
4053
programArguments,
4154
workingDirectory,
4255
environment,
56+
environmentFiles,
4357
}: GatewayServiceRenderArgs): string {
4458
const execStart = programArguments.map(systemdEscapeArg).join(" ");
4559
const descriptionValue = description?.trim() || "OpenClaw Gateway";
@@ -49,6 +63,7 @@ export function buildSystemdUnit({
4963
? `WorkingDirectory=${systemdEscapeArg(workingDirectory)}`
5064
: null;
5165
const envLines = renderEnvLines(environment);
66+
const environmentFileLines = renderEnvironmentFileLines(environmentFiles);
5267
return [
5368
"[Unit]",
5469
descriptionLine,
@@ -69,6 +84,7 @@ export function buildSystemdUnit({
6984
// orphan ACP/runtime workers behind.
7085
"KillMode=control-group",
7186
workingDirLine,
87+
...environmentFileLines,
7288
...envLines,
7389
"",
7490
"[Install]",

‎src/daemon/systemd.test.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import fs from "node:fs/promises";
22
import os from "node:os";
3+
import path from "node:path";
34
import { beforeEach, describe, expect, it, vi } from "vitest";
45

56
const execFileMock = vi.hoisted(() => vi.fn());
@@ -26,6 +27,7 @@ import {
2627
readSystemdServiceExecStart,
2728
restartSystemdService,
2829
resolveSystemdUserUnitPath,
30+
stageSystemdService,
2931
stopSystemdService,
3032
} from "./systemd.js";
3133

@@ -640,6 +642,116 @@ describe("readSystemdServiceExecStart", () => {
640642
});
641643
});
642644

645+
describe("stageSystemdService", () => {
646+
beforeEach(() => {
647+
vi.restoreAllMocks();
648+
execFileMock.mockReset();
649+
});
650+
651+
it("writes dotenv-backed values to a separate env file and keeps inline env minimal", async () => {
652+
const tempHomeRoot = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-systemd-stage-"));
653+
const home = path.join(tempHomeRoot, "home");
654+
const stateDir = path.join(home, ".openclaw");
655+
const env = {
656+
HOME: home,
657+
OPENCLAW_STATE_DIR: stateDir,
658+
OPENCLAW_SYSTEMD_UNIT: "openclaw-gateway-stage-test",
659+
};
660+
const unitPath = resolveSystemdUserUnitPath(env);
661+
const envFilePath = path.join(stateDir, "gateway.systemd.env");
662+
663+
await fs.mkdir(stateDir, { recursive: true });
664+
await fs.writeFile(
665+
path.join(stateDir, ".env"),
666+
["OPENCLAW_GATEWAY_TOKEN=dotenv-token", "LLM_API_KEY=dotenv-key"].join("\n"),
667+
"utf8",
668+
);
669+
670+
execFileMock.mockImplementationOnce((_cmd, args, _opts, cb) => {
671+
assertUserSystemctlArgs(args, "status");
672+
cb(null, "", "");
673+
});
674+
675+
try {
676+
await stageSystemdService({
677+
env,
678+
stdout: { write: vi.fn() } as unknown as NodeJS.WritableStream,
679+
programArguments: ["/usr/bin/openclaw", "gateway", "run"],
680+
workingDirectory: "/tmp",
681+
environment: {
682+
OPENCLAW_GATEWAY_TOKEN: "dotenv-token",
683+
LLM_API_KEY: "dotenv-key",
684+
OPENCLAW_GATEWAY_PORT: "18789",
685+
},
686+
});
687+
688+
const [unit, envFile, envFileStat] = await Promise.all([
689+
fs.readFile(unitPath, "utf8"),
690+
fs.readFile(envFilePath, "utf8"),
691+
fs.stat(envFilePath),
692+
]);
693+
694+
expect(unit).toContain(`EnvironmentFile=-${envFilePath}`);
695+
expect(unit).toContain("Environment=OPENCLAW_GATEWAY_PORT=18789");
696+
expect(unit).not.toContain("Environment=OPENCLAW_GATEWAY_TOKEN=dotenv-token");
697+
expect(unit).not.toContain("Environment=LLM_API_KEY=dotenv-key");
698+
expect(envFile).toBe("OPENCLAW_GATEWAY_TOKEN=dotenv-token\nLLM_API_KEY=dotenv-key\n");
699+
expect(envFileStat.mode & 0o777).toBe(0o600);
700+
} finally {
701+
await fs.rm(tempHomeRoot, { recursive: true, force: true });
702+
}
703+
});
704+
705+
it("keeps inline overrides out of the generated env file", async () => {
706+
const tempHomeRoot = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-systemd-stage-"));
707+
const home = path.join(tempHomeRoot, "home");
708+
const stateDir = path.join(home, ".openclaw");
709+
const env = {
710+
HOME: home,
711+
OPENCLAW_STATE_DIR: stateDir,
712+
OPENCLAW_SYSTEMD_UNIT: "openclaw-gateway-stage-test",
713+
};
714+
const unitPath = resolveSystemdUserUnitPath(env);
715+
const envFilePath = path.join(stateDir, "gateway.systemd.env");
716+
717+
await fs.mkdir(stateDir, { recursive: true });
718+
await fs.writeFile(
719+
path.join(stateDir, ".env"),
720+
["OPENCLAW_GATEWAY_TOKEN=stale-token", "LLM_API_KEY=dotenv-key"].join("\n"),
721+
"utf8",
722+
);
723+
724+
execFileMock.mockImplementationOnce((_cmd, args, _opts, cb) => {
725+
assertUserSystemctlArgs(args, "status");
726+
cb(null, "", "");
727+
});
728+
729+
try {
730+
await stageSystemdService({
731+
env,
732+
stdout: { write: vi.fn() } as unknown as NodeJS.WritableStream,
733+
programArguments: ["/usr/bin/openclaw", "gateway", "run"],
734+
workingDirectory: "/tmp",
735+
environment: {
736+
OPENCLAW_GATEWAY_TOKEN: "fresh-token",
737+
LLM_API_KEY: "dotenv-key",
738+
},
739+
});
740+
741+
const [unit, envFile] = await Promise.all([
742+
fs.readFile(unitPath, "utf8"),
743+
fs.readFile(envFilePath, "utf8"),
744+
]);
745+
746+
expect(unit).toContain(`EnvironmentFile=-${envFilePath}`);
747+
expect(unit).toContain("Environment=OPENCLAW_GATEWAY_TOKEN=fresh-token");
748+
expect(envFile).toBe("LLM_API_KEY=dotenv-key\n");
749+
} finally {
750+
await fs.rm(tempHomeRoot, { recursive: true, force: true });
751+
}
752+
});
753+
});
754+
643755
describe("systemd service control", () => {
644756
const assertMachineRestartArgs = (args: string[]) => {
645757
assertMachineUserSystemctlArgs(args, "debian", "restart", GATEWAY_SERVICE);

‎src/daemon/systemd.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import fs from "node:fs/promises";
22
import os from "node:os";
33
import path from "node:path";
4+
import { resolveStateDir } from "../config/paths.js";
5+
import { readStateDirDotEnvVarsFromStateDir } from "../config/state-dir-dotenv.js";
46
import { formatErrorMessage } from "../infra/errors.js";
57
import { parseStrictInteger, parseStrictPositiveInteger } from "../infra/parse-finite-number.js";
68
import { normalizeLowercaseStringOrEmpty } from "../shared/string-coerce.js";
@@ -40,6 +42,8 @@ import {
4042
parseSystemdExecStart,
4143
} from "./systemd-unit.js";
4244

45+
const SYSTEMD_GATEWAY_DOTENV_FILENAME = "gateway.systemd.env";
46+
4347
function resolveSystemdUnitPathForName(env: GatewayServiceEnv, name: string): string {
4448
const home = toPosixPath(resolveHomeDir(env));
4549
return path.posix.join(home, ".config", "systemd", "user", `${name}.service`);
@@ -449,16 +453,65 @@ async function writeSystemdUnit({
449453
}
450454

451455
const serviceDescription = resolveGatewayServiceDescription({ env, environment, description });
456+
const stateDir = resolveStateDir(env as NodeJS.ProcessEnv);
457+
const stateDirDotEnvVars = Object.fromEntries(
458+
Object.entries(readStateDirDotEnvVarsFromStateDir(stateDir)).filter(([key, value]) => {
459+
const inlineValue = environment?.[key];
460+
if (typeof inlineValue !== "string") {
461+
return true;
462+
}
463+
return inlineValue.trim() === value.trim();
464+
}),
465+
);
466+
const environmentFiles = await writeSystemdGatewayEnvironmentFile({
467+
stateDir,
468+
dotenvVars: stateDirDotEnvVars,
469+
});
470+
const environmentSansDotEnvEntries = Object.fromEntries(
471+
Object.entries(environment ?? {}).filter(([key, value]) => {
472+
if (typeof value !== "string") {
473+
return false;
474+
}
475+
const stateDirValue = stateDirDotEnvVars[key];
476+
if (typeof stateDirValue !== "string") {
477+
return true;
478+
}
479+
return value.trim() !== stateDirValue.trim();
480+
}),
481+
);
452482
const unit = buildSystemdUnit({
453483
description: serviceDescription,
454484
programArguments,
455485
workingDirectory,
456-
environment,
486+
environment: environmentSansDotEnvEntries,
487+
environmentFiles,
457488
});
458489
await fs.writeFile(unitPath, unit, "utf8");
459490
return { unitPath, backedUp };
460491
}
461492

493+
async function writeSystemdGatewayEnvironmentFile(params: {
494+
stateDir: string;
495+
dotenvVars: Record<string, string>;
496+
}): Promise<string[]> {
497+
const entries = Object.entries(params.dotenvVars);
498+
if (entries.length === 0) {
499+
return [];
500+
}
501+
for (const [key, value] of entries) {
502+
if (/[\r\n]/.test(value)) {
503+
throw new Error(
504+
`state-dir .env contains a multiline value for ${key}; systemd EnvironmentFile values must be single-line`,
505+
);
506+
}
507+
}
508+
const envFilePath = path.join(params.stateDir, SYSTEMD_GATEWAY_DOTENV_FILENAME);
509+
const content = entries.map(([key, value]) => `${key}=${value}`).join("\n");
510+
await fs.writeFile(envFilePath, `${content}\n`, { encoding: "utf8", mode: 0o600 });
511+
await fs.chmod(envFilePath, 0o600);
512+
return [envFilePath];
513+
}
514+
462515
export async function stageSystemdService({
463516
stdout,
464517
...args

0 commit comments

Comments
 (0)