Skip to content

Commit 9808269

Browse files
committed
fix(secrets): preserve providerless env refs
Signed-off-by: sallyom <[email protected]>
1 parent 2f64a4d commit 9808269

8 files changed

Lines changed: 96 additions & 38 deletions

File tree

‎docs/help/environment.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ read_when:
77
title: "Environment variables"
88
---
99

10-
OpenClaw pulls environment variables from multiple sources. The rule is **never override existing values**.
10+
OpenClaw pulls environment variables from multiple sources. The normal rule is **never override existing values**. For an OpenClaw-installed systemd service, the global `.env` may replace only service values that OpenClaw recorded as managed; operator-owned service values still take precedence.
1111
Workspace `.env` files are a lower-trust source: OpenClaw ignores provider credentials and protected runtime controls from workspace `.env` before applying precedence.
1212

1313
## Precedence (highest to lowest)
1414

1515
1. **Process environment** (what the Gateway process already has from the parent shell/daemon).
1616
2. **`.env` in the current working directory** (dotenv default; does not override; provider credentials and protected runtime controls are ignored).
17-
3. **Global `.env`** at `~/.openclaw/.env` (aka `$OPENCLAW_STATE_DIR/.env`; recommended for provider API keys; does not override).
17+
3. **Global `.env`** at `~/.openclaw/.env` (aka `$OPENCLAW_STATE_DIR/.env`; recommended for provider API keys; does not override except for recorded OpenClaw-managed systemd service values).
1818
4. **Config `env` block** in `~/.openclaw/openclaw.json` (applied only if missing).
1919
5. **Optional login-shell import** (`env.shellEnv.enabled` or `OPENCLAW_LOAD_SHELL_ENV=1`), applied only for missing expected keys.
2020

‎docs/help/faq.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -883,7 +883,7 @@ First-run Q&A - install, onboard, auth routes, subscriptions, initial failures -
883883
- `.env` from the current working directory.
884884
- a global fallback `.env` from `~/.openclaw/.env` (`$OPENCLAW_STATE_DIR/.env`).
885885

886-
Neither `.env` file overrides existing env vars. Provider credential and endpoint-routing keys are an exception for workspace `.env`: keys such as `GEMINI_API_KEY`, `XAI_API_KEY`, `MISTRAL_API_KEY`, or any key ending in `_ENDPOINT` (and other bundled-provider auth or endpoint env vars) are ignored from workspace `.env` and should live in the process environment, `~/.openclaw/.env`, or config `env`.
886+
Normally, neither `.env` file overrides existing env vars. For an OpenClaw-installed systemd service, the global `.env` may replace only service values that OpenClaw recorded as managed; operator-owned service values still take precedence. Provider credential and endpoint-routing keys are an exception for workspace `.env`: keys such as `GEMINI_API_KEY`, `XAI_API_KEY`, `MISTRAL_API_KEY`, or any key ending in `_ENDPOINT` (and other bundled-provider auth or endpoint env vars) are ignored from workspace `.env` and should live in the process environment, `~/.openclaw/.env`, or config `env`.
887887

888888
Inline env vars in config apply only if missing from the process env:
889889

‎docs/security/network-proxy.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ openclaw gateway install --force
3939
openclaw gateway start
4040
```
4141

42-
The `OPENCLAW_PROXY_URL` env fallback is best for foreground runs. To use it with an installed service, put it in the service's durable environment (`$OPENCLAW_STATE_DIR/.env`, default `~/.openclaw/.env`), then reinstall so launchd/systemd/Scheduled Tasks picks it up.
42+
The `OPENCLAW_PROXY_URL` env fallback is best for foreground runs. To use it with an installed service, put it in the service's durable environment (`$OPENCLAW_STATE_DIR/.env`, default `~/.openclaw/.env`), then reinstall so launchd/systemd/Scheduled Tasks picks it up. This variable is copied into the generated service environment rather than tracked as a managed dotenv key, so systemd's restart-only managed dotenv refresh does not apply.
4343

4444
### HTTPS proxy endpoint with a private CA
4545

‎src/cli/gateway-cli/pre-bootstrap.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ async function guardGatewayRunSelectedConfig(
249249
{ normalizeStateDirEnv, resolveStateDir },
250250
{ resolveConfigDir },
251251
{ collectEnvSecretRefIds },
252-
{ clearMissingManagedServiceEnvKeys, readManagedServiceEnvKeysFromEnvironment },
252+
{ clearMissingManagedServiceEnvKeys, readManagedSystemdServiceEnvKeysFromEnvironment },
253253
] = await Promise.all([
254254
import("node:path"),
255255
import("../../config/config-env-vars.js"),
@@ -273,7 +273,7 @@ async function guardGatewayRunSelectedConfig(
273273
normalizeStateDirEnv(process.env);
274274
const loaded = loadGlobalRuntimeDotEnvFiles({
275275
...(gatewayRunTargetSelectedByConfig ? { entryFilter: isConfigRuntimeEnvVarAllowed } : {}),
276-
overrideKeys: readManagedServiceEnvKeysFromEnvironment(process.env),
276+
overrideKeys: readManagedSystemdServiceEnvKeysFromEnvironment(process.env),
277277
quiet: true,
278278
...resolveGatewayRunDotEnvPaths({
279279
env: process.env,
@@ -349,7 +349,7 @@ async function guardGatewayRunSelectedConfig(
349349
// config reference are stale; clearing the broad marker blindly would drop file-backed refs.
350350
clearMissingManagedServiceEnvKeys({
351351
environment: process.env,
352-
managedKeys: readManagedServiceEnvKeysFromEnvironment(process.env),
352+
managedKeys: readManagedSystemdServiceEnvKeysFromEnvironment(process.env),
353353
presentKeys: trustedEnvLoad.dotenvPresentKeys,
354354
preserveKeys: collectEnvSecretRefIds(snapshot.sourceConfig),
355355
});
@@ -560,7 +560,7 @@ export async function reloadTrustedGatewayRunEnvironment(params: {
560560
{ normalizeEnv },
561561
{ normalizeStateDirEnv, resolveStateDir },
562562
{ resolveConfigDir },
563-
{ readManagedServiceEnvKeysFromEnvironment },
563+
{ readManagedSystemdServiceEnvKeysFromEnvironment },
564564
] = await Promise.all([
565565
import("node:path"),
566566
import("../../config/env-vars.js"),
@@ -576,7 +576,7 @@ export async function reloadTrustedGatewayRunEnvironment(params: {
576576
normalizeStateDirEnv(process.env);
577577
loadGlobalRuntimeDotEnvFiles({
578578
...(gatewayRunTargetSelectedByConfig ? { entryFilter: isConfigRuntimeEnvVarAllowed } : {}),
579-
overrideKeys: readManagedServiceEnvKeysFromEnvironment(process.env),
579+
overrideKeys: readManagedSystemdServiceEnvKeysFromEnvironment(process.env),
580580
quiet: true,
581581
...resolveGatewayRunDotEnvPaths({
582582
env: process.env,

‎src/cli/gateway-cli/run.option-collisions.test.ts‎

Lines changed: 71 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from "../../test-utils/env.js";
1616
import { getFreePort } from "../../test-utils/ports.js";
1717
import { withTempSecretFiles } from "../../test-utils/secret-file-fixture.js";
18+
import { withMockedPlatform } from "../../test-utils/vitest-spies.js";
1819
import { createCliRuntimeCapture } from "../test-runtime-capture.js";
1920
import { installGatewayRunRuntimeHooks } from "./runtime-hooks.js";
2021

@@ -50,6 +51,7 @@ const runGatewayLoop = vi.fn(async ({ start }: GatewayLoopParams) => {
5051
const normalizeStateDirEnv = vi.fn((_env?: NodeJS.ProcessEnv) => undefined);
5152
const pinConfigDir = vi.fn((_env?: NodeJS.ProcessEnv) => undefined);
5253
const pinRuntimePaths = vi.fn((_env?: NodeJS.ProcessEnv) => undefined);
54+
const detectRespawnSupervisor = vi.fn(() => null as "systemd" | null);
5355
type RuntimeDotEnvLoadResult = {
5456
dotenvPresentKeys: string[];
5557
gatewayEnvAppliedKeys: string[];
@@ -301,7 +303,7 @@ vi.mock("../../infra/supervisor-markers.js", async (importOriginal) => {
301303
const actual = await importOriginal<typeof import("../../infra/supervisor-markers.js")>();
302304
return {
303305
...actual,
304-
detectRespawnSupervisor: () => null,
306+
detectRespawnSupervisor: () => detectRespawnSupervisor(),
305307
};
306308
});
307309

@@ -410,6 +412,7 @@ describe("gateway run option collisions", () => {
410412
});
411413
netState.autoBindHost = "127.0.0.1";
412414
netState.container = false;
415+
detectRespawnSupervisor.mockReset().mockReturnValue(null);
413416
readBestEffortConfig.mockClear();
414417
readConfigFileSnapshotWithPluginMetadata.mockClear();
415418
gatewayLogMessages.length = 0;
@@ -1576,14 +1579,20 @@ describe("gateway run option collisions", () => {
15761579
});
15771580

15781581
it("lets gateway bootstrap refresh inherited service-managed dotenv keys", async () => {
1579-
await withEnvAsync(
1580-
{ OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "OPENAI_API_KEY,ANTHROPIC_API_KEY" },
1581-
async () => {
1582-
const { prepareGatewayRunBootstrap, selectGatewayRunEnvironment } =
1583-
await import("./pre-bootstrap.js");
1584-
await selectGatewayRunEnvironment({ opts: {}, runtime: defaultRuntime });
1585-
await prepareGatewayRunBootstrap({ opts: {}, runtime: defaultRuntime });
1586-
},
1582+
detectRespawnSupervisor.mockReturnValue("systemd");
1583+
await withMockedPlatform("linux", () =>
1584+
withEnvAsync(
1585+
{
1586+
INVOCATION_ID: "systemd-invocation",
1587+
OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "OPENAI_API_KEY,ANTHROPIC_API_KEY",
1588+
},
1589+
async () => {
1590+
const { prepareGatewayRunBootstrap, selectGatewayRunEnvironment } =
1591+
await import("./pre-bootstrap.js");
1592+
await selectGatewayRunEnvironment({ opts: {}, runtime: defaultRuntime });
1593+
await prepareGatewayRunBootstrap({ opts: {}, runtime: defaultRuntime });
1594+
},
1595+
),
15871596
);
15881597

15891598
expect(loadGlobalRuntimeDotEnvFiles).toHaveBeenCalledWith(
@@ -1593,15 +1602,48 @@ describe("gateway run option collisions", () => {
15931602
);
15941603
});
15951604

1605+
it("limits inherited service-managed dotenv refresh to systemd launches", async () => {
1606+
const serviceManagedEnv = await import("../../daemon/service-managed-env.js");
1607+
detectRespawnSupervisor.mockReturnValueOnce("systemd");
1608+
expect(
1609+
serviceManagedEnv.readManagedSystemdServiceEnvKeysFromEnvironment(
1610+
{
1611+
INVOCATION_ID: "systemd-invocation",
1612+
OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "OPENAI_API_KEY",
1613+
},
1614+
"linux",
1615+
),
1616+
).toEqual(new Set(["OPENAI_API_KEY"]));
1617+
expect(
1618+
serviceManagedEnv.readManagedSystemdServiceEnvKeysFromEnvironment(
1619+
{ OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "OPENAI_API_KEY" },
1620+
"linux",
1621+
),
1622+
).toEqual(new Set());
1623+
expect(
1624+
serviceManagedEnv.readManagedSystemdServiceEnvKeysFromEnvironment(
1625+
{ OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "OPENAI_API_KEY" },
1626+
"darwin",
1627+
),
1628+
).toEqual(new Set());
1629+
expect(
1630+
serviceManagedEnv.readManagedSystemdServiceEnvKeysFromEnvironment(
1631+
{ OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "OPENAI_API_KEY" },
1632+
"win32",
1633+
),
1634+
).toEqual(new Set());
1635+
});
1636+
15961637
it("clears only missing managed keys after reading the selected config", async () => {
1638+
detectRespawnSupervisor.mockReturnValue("systemd");
15971639
configState.snapshot = {
15981640
config: {},
15991641
exists: true,
16001642
sourceConfig: {
16011643
models: {
16021644
providers: {
16031645
openai: {
1604-
apiKey: { source: "env", provider: "default", id: "SECRET_REF_KEY" },
1646+
apiKey: { source: "env", id: "SECRET_REF_KEY" },
16051647
},
16061648
},
16071649
},
@@ -1614,22 +1656,25 @@ describe("gateway run option collisions", () => {
16141656
stateEnvAppliedKeys: [],
16151657
});
16161658

1617-
await withEnvAsync(
1618-
{
1619-
OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "REMOVED_KEY,SECRET_REF_KEY",
1620-
REMOVED_KEY: "stale-service-value",
1621-
SECRET_REF_KEY: "file-backed-value",
1622-
OPERATOR_KEY: "operator-value",
1623-
},
1624-
async () => {
1625-
const { prepareGatewayRunBootstrap, selectGatewayRunEnvironment } =
1626-
await import("./pre-bootstrap.js");
1627-
await selectGatewayRunEnvironment({ opts: {}, runtime: defaultRuntime });
1628-
expect(process.env.REMOVED_KEY).toBeUndefined();
1629-
expect(process.env.SECRET_REF_KEY).toBe("file-backed-value");
1630-
expect(process.env.OPERATOR_KEY).toBe("operator-value");
1631-
await prepareGatewayRunBootstrap({ opts: {}, runtime: defaultRuntime });
1632-
},
1659+
await withMockedPlatform("linux", () =>
1660+
withEnvAsync(
1661+
{
1662+
INVOCATION_ID: "systemd-invocation",
1663+
OPENCLAW_SERVICE_MANAGED_ENV_KEYS: "REMOVED_KEY,SECRET_REF_KEY",
1664+
REMOVED_KEY: "stale-service-value",
1665+
SECRET_REF_KEY: "file-backed-value",
1666+
OPERATOR_KEY: "operator-value",
1667+
},
1668+
async () => {
1669+
const { prepareGatewayRunBootstrap, selectGatewayRunEnvironment } =
1670+
await import("./pre-bootstrap.js");
1671+
await selectGatewayRunEnvironment({ opts: {}, runtime: defaultRuntime });
1672+
expect(process.env.REMOVED_KEY).toBeUndefined();
1673+
expect(process.env.SECRET_REF_KEY).toBe("file-backed-value");
1674+
expect(process.env.OPERATOR_KEY).toBe("operator-value");
1675+
await prepareGatewayRunBootstrap({ opts: {}, runtime: defaultRuntime });
1676+
},
1677+
),
16331678
);
16341679
});
16351680

‎src/config/types.secrets.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,10 @@ describe("collectEnvSecretRefIds", () => {
4949
expect(
5050
collectEnvSecretRefIds({
5151
structured: { source: "env", provider: "default", id: "OPENAI_API_KEY" },
52+
providerless: { source: "env", id: "LEGACY_API_KEY" },
5253
nested: [{ token: "$DISCORD_BOT_TOKEN" }],
5354
ignored: { source: "file", provider: "default", id: "/run/secret" },
5455
}),
55-
).toEqual(new Set(["OPENAI_API_KEY", "DISCORD_BOT_TOKEN"]));
56+
).toEqual(new Set(["OPENAI_API_KEY", "LEGACY_API_KEY", "DISCORD_BOT_TOKEN"]));
5657
});
5758
});

‎src/config/types.secrets.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,12 @@ export function parseEnvTemplateSecretRef(
102102
};
103103
}
104104

105-
/** Collect env ids from canonical and shorthand SecretRefs anywhere in a config tree. */
105+
/** Collect env ids from supported SecretRef shapes anywhere in a config tree. */
106106
export function collectEnvSecretRefIds(value: unknown): Set<string> {
107107
const ids = new Set<string>();
108108
const seen = new WeakSet<object>();
109109
const visit = (candidate: unknown): void => {
110-
const ref = isSecretRef(candidate) ? candidate : parseEnvTemplateSecretRef(candidate);
110+
const ref = coerceSecretRef(candidate);
111111
if (ref?.source === "env" && isValidEnvSecretRefId(ref.id)) {
112112
ids.add(ref.id);
113113
return;

‎src/daemon/service-managed-env.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** Tracks managed service environment keys across reinstall and repair flows. */
22
import { sortUniqueStrings } from "@openclaw/normalization-core/string-normalization";
33
import { normalizeEnvVarKey } from "../infra/host-env-security.js";
4+
import { detectRespawnSupervisor } from "../infra/supervisor-markers.js";
45
import type { GatewayServiceEnvironmentValueSource } from "./service-types.js";
56

67
const MANAGED_SERVICE_ENV_KEYS_VAR = "OPENCLAW_SERVICE_MANAGED_ENV_KEYS";
@@ -72,6 +73,17 @@ export function readManagedServiceEnvKeysFromEnvironment(
7273
return new Set();
7374
}
7475

76+
export function readManagedSystemdServiceEnvKeysFromEnvironment(
77+
environment: Record<string, string | undefined> | undefined,
78+
platform: NodeJS.Platform = process.platform,
79+
): Set<string> {
80+
// Only systemd snapshots state dotenv values into its inherited service environment.
81+
// Other supervisors retain their existing reinstall-based precedence contract.
82+
return environment && detectRespawnSupervisor(environment, platform) === "systemd"
83+
? readManagedServiceEnvKeysFromEnvironment(environment)
84+
: new Set();
85+
}
86+
7587
export function clearMissingManagedServiceEnvKeys(params: {
7688
environment: Record<string, string | undefined>;
7789
managedKeys: Iterable<string>;

0 commit comments

Comments
 (0)