Skip to content

Commit 2bd3590

Browse files
committed
fix(secrets): bind env-ref .env retention to the validated source
Retention selects each dotenv file's runtime-effective assignment for a planned env SecretRef and drops the other assignments of that name in that file, so a same-file duplicate cannot leave a fresh process authenticating with a credential apply never validated.
1 parent 9386ac0 commit 2bd3590

4 files changed

Lines changed: 250 additions & 13 deletions

File tree

‎docs/gateway/secrets-plan-contract.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ No writes are committed for an invalid plan: target resolution and path validati
127127
## Runtime and audit scope notes
128128

129129
- Ref-only `auth-profiles.json` entries (`keyRef`/`tokenRef`) are included in runtime credential resolution and audit coverage.
130-
- `secrets apply` writes supported `openclaw.json` targets, supported `auth-profiles.json` targets, and three optional scrub passes, each on by default: `scrubEnv` (removes migrated plaintext values from `.env` files in the effective state and active-config directories), `scrubAuthProfilesForProviderTargets` (clears plaintext/unused-ref residue in `auth-profiles.json` for providers a plan just migrated), and `scrubLegacyAuthJson` (drops migrated `api_key` entries from legacy `auth.json` stores). Set any of `options.scrubEnv`, `options.scrubAuthProfilesForProviderTargets`, `options.scrubLegacyAuthJson` to `false` in the plan to skip that pass.
130+
- `secrets apply` writes supported `openclaw.json` targets, supported `auth-profiles.json` targets, and three optional scrub passes, each on by default: `scrubEnv` (removes migrated plaintext values from `.env` files in the effective state and active-config directories, except one retained assignment per `env` SecretRef the same plan writes: the first of those files, in the order the gateway loads them, whose effective value for the ref's name is the value the plan validated the ref against. That assignment is the ref's durable source, so removing it would leave the ref unresolvable after restart; the other assignments of that name in the same file are removed so the durable source is also the effective one, and non-matching values under the same name in other files are still removed), `scrubAuthProfilesForProviderTargets` (clears plaintext/unused-ref residue in `auth-profiles.json` for providers a plan just migrated), and `scrubLegacyAuthJson` (drops migrated `api_key` entries from legacy `auth.json` stores). Set any of `options.scrubEnv`, `options.scrubAuthProfilesForProviderTargets`, `options.scrubLegacyAuthJson` to `false` in the plan to skip that pass.
131131

132132
## Operator checks
133133

‎docs/gateway/secrets.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ For production deployments where agent-accessible files are in scope, treat migr
5858
- `openclaw secrets audit --check` is clean after migration.
5959
- Any remaining unsupported or rotating credentials are protected by OS isolation, container isolation, or an external credential proxy.
6060

61+
An `env` SecretRef does not satisfy this boundary. It resolves by reading its variable from the process environment, which a fresh process hydrates from the dotenv files described in [Retained dotenv sources](#retained-dotenv-sources), so `secrets apply` keeps the backing line in whichever of those files supplies it and the re-audit keeps reporting it as `PLAINTEXT_FOUND`. Migrating to `env` removes the credential from `openclaw.json` and from generated `models.json` files, which is a real config-exposure reduction, but the value stays readable by any agent file or shell tool. Where agent-accessible files are in scope, use `file` or `exec` SecretRefs, or isolate the directories holding those dotenv files, before calling the migration complete.
62+
6163
This is why the audit/configure/apply workflow is a security migration gate, not just a convenience helper.
6264

6365
<Warning>
@@ -811,6 +813,23 @@ Default operator flow:
811813

812814
Do not treat the migration as complete until the re-audit is clean. If the audit still reports plaintext values at rest, the agent-access risk remains even when runtime APIs return redacted values.
813815

816+
### Retained dotenv sources
817+
818+
An `env` SecretRef leaves its backing value on disk by design, so the re-audit keeps reporting that `.env` key as `PLAINTEXT_FOUND`. `secrets apply` retains exactly one assignment per ref: in the first file it scrubs whose effective value for that name equals the value apply validated the ref against. Deleting that line leaves the ref unresolvable in a fresh process that has no other source for the name.
819+
820+
`secrets apply` scrubs two files, in the order the gateway loads them:
821+
822+
1. The state-directory `.env` (`OPENCLAW_STATE_DIR`, otherwise `~/.openclaw`).
823+
2. The active config directory's `.env`, when `OPENCLAW_CONFIG_PATH` points outside the state directory.
824+
825+
Only `openclaw gateway run` loads both. Normal CLI commands load the working-directory `.env` and the state-directory `.env`, and never the active config directory's `.env`, so a ref whose only retained source is the config-directory file resolves in the gateway but not in a fresh CLI such as the post-apply `openclaw secrets audit`. Move that assignment into the state-directory `.env` if you need both.
826+
827+
Across files the first assignment of a name wins, and an inherited process-environment value wins over every file. Within one file the last assignment of a name wins, so apply removes the other assignments of a retained name in that file; without that removal the ref could resolve after restart to a value apply never validated. A ref validated against a value exported only in the operator's shell has no retained file source at all, and that shell export has to keep supplying it. Working-directory `.env` files are never scrubbed and never retained.
828+
829+
Everything else is still scrubbed: a stale value under the same name, a duplicate of the same name, and any redundant copy in a lower-precedence source.
830+
831+
The retained line is unmigrated plaintext, not a completed migration, so both a clean re-audit and the agent-access boundary above still require `file` or `exec` SecretRefs, whose values live outside the agent-readable dotenv directories.
832+
814833
If you save a plan instead of applying during `configure`, apply that saved plan with `openclaw secrets apply --from <plan-path>` before the re-audit.
815834

816835
<AccordionGroup>

‎src/secrets/apply.test.ts‎

Lines changed: 182 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
} from "../agents/auth-profiles/store.js";
2626
import { testing as storeTesting } from "../agents/auth-profiles/store.test-support.js";
2727
import type { AuthProfileStore } from "../agents/auth-profiles/types.js";
28+
import { readDotEnvFile } from "../infra/dotenv-global.js";
2829
import {
2930
closeOpenClawAgentDatabasesForTest,
3031
openOpenClawAgentDatabase,
@@ -40,6 +41,7 @@ import {
4041
TALK_TEST_PROVIDER_ID,
4142
} from "../test-utils/talk-test-provider.js";
4243
import type { SecretsApplyPlan } from "./plan.js";
44+
import { resolveSecretRefValue } from "./resolve.js";
4345

4446
const { clearSecretsRuntimeSnapshotMock, prepareSecretsRuntimeSnapshotMock } = vi.hoisted(() => ({
4547
clearSecretsRuntimeSnapshotMock: vi.fn(),
@@ -216,6 +218,17 @@ function createOpenAiProviderTarget(params?: {
216218
};
217219
}
218220

221+
function readStateDotEnvAsProcessEnv(...envPaths: string[]): NodeJS.ProcessEnv {
222+
const processEnv: NodeJS.ProcessEnv = {};
223+
for (const envPath of envPaths) {
224+
const loaded = readDotEnvFile({ filePath: envPath, quiet: true });
225+
for (const { key, value } of loaded?.entries ?? []) {
226+
processEnv[key] ??= value;
227+
}
228+
}
229+
return processEnv;
230+
}
231+
219232
function createOpenAiExecProviderTarget(): SecretsApplyPlan["targets"][number] {
220233
return {
221234
type: "models.providers.apiKey",
@@ -360,6 +373,173 @@ describe("secrets apply", () => {
360373
expect(nextEnv).toContain("UNRELATED=value");
361374
});
362375

376+
it("keeps the state .env source backing a newly written env SecretRef", async () => {
377+
const plan = createPlan({
378+
targets: [createOpenAiProviderTarget()],
379+
options: createOneWayScrubOptions(),
380+
});
381+
382+
const applied = await runSecretsApply({
383+
plan,
384+
env: { ...fixture.env, OPENAI_API_KEY: "sk-openai-plaintext" },
385+
write: true,
386+
});
387+
expect(applied.changed).toBe(true);
388+
expect(applied.changedFiles).not.toContain(fixture.envPath);
389+
390+
const nextConfig = JSON.parse(await fs.readFile(fixture.configPath, "utf8")) as {
391+
models: { providers: { openai: { apiKey: unknown } } };
392+
};
393+
expect(nextConfig.models.providers.openai.apiKey).toEqual(OPENAI_API_KEY_ENV_REF);
394+
395+
const freshProcessEnv = readStateDotEnvAsProcessEnv(fixture.envPath);
396+
expect(freshProcessEnv.OPENAI_API_KEY).toBe("sk-openai-plaintext");
397+
await expect(
398+
resolveSecretRefValue(OPENAI_API_KEY_ENV_REF, {
399+
config: nextConfig as never,
400+
env: freshProcessEnv,
401+
}),
402+
).resolves.toBe("sk-openai-plaintext");
403+
});
404+
405+
it("scrubs a state .env value that does not back the validated env SecretRef", async () => {
406+
const plan = createPlan({
407+
targets: [createOpenAiProviderTarget()],
408+
options: createOneWayScrubOptions(),
409+
});
410+
411+
const applied = await runSecretsApply({ plan, env: fixture.env, write: true });
412+
expect(applied.changed).toBe(true);
413+
expect(applied.changedFiles).toContain(fixture.envPath);
414+
415+
const nextConfig = JSON.parse(await fs.readFile(fixture.configPath, "utf8")) as {
416+
models: { providers: { openai: { apiKey: unknown } } };
417+
};
418+
419+
const nextEnv = await fs.readFile(fixture.envPath, "utf8");
420+
expect(nextEnv).not.toContain("sk-openai-plaintext");
421+
expect(nextEnv).toContain("UNRELATED=value");
422+
423+
const freshProcessEnv = readStateDotEnvAsProcessEnv(fixture.envPath);
424+
expect(freshProcessEnv.OPENAI_API_KEY).toBeUndefined();
425+
await expect(
426+
resolveSecretRefValue(OPENAI_API_KEY_ENV_REF, {
427+
config: nextConfig as never,
428+
env: { ...freshProcessEnv, OPENAI_API_KEY: "sk-live-env" },
429+
}),
430+
).resolves.toBe("sk-live-env");
431+
});
432+
433+
it("scrubs a config-adjacent .env copy while keeping the state .env source", async () => {
434+
const configDir = path.join(fixture.rootDir, "config");
435+
const configPath = path.join(configDir, "openclaw.json");
436+
const configEnvPath = path.join(configDir, ".env");
437+
await fs.mkdir(configDir, { recursive: true });
438+
await fs.copyFile(fixture.configPath, configPath);
439+
await fs.copyFile(fixture.envPath, configEnvPath);
440+
441+
const applied = await runSecretsApply({
442+
plan: createPlan({
443+
targets: [createOpenAiProviderTarget()],
444+
options: createOneWayScrubOptions(),
445+
}),
446+
env: {
447+
...fixture.env,
448+
OPENCLAW_CONFIG_PATH: configPath,
449+
OPENAI_API_KEY: "sk-openai-plaintext", // pragma: allowlist secret
450+
},
451+
write: true,
452+
});
453+
454+
expect(applied.changedFiles).toContain(configEnvPath);
455+
expect(applied.changedFiles).not.toContain(fixture.envPath);
456+
await expect(fs.readFile(configEnvPath, "utf8")).resolves.toBe("UNRELATED=value\n");
457+
await expect(fs.readFile(fixture.envPath, "utf8")).resolves.toContain(
458+
"OPENAI_API_KEY=sk-openai-plaintext",
459+
);
460+
});
461+
462+
it("keeps the config-adjacent .env source when the state .env cannot back the env SecretRef", async () => {
463+
const configDir = path.join(fixture.rootDir, "config");
464+
const configPath = path.join(configDir, "openclaw.json");
465+
const configEnvPath = path.join(configDir, ".env");
466+
await fs.mkdir(configDir, { recursive: true });
467+
await fs.copyFile(fixture.configPath, configPath);
468+
await fs.copyFile(fixture.envPath, configEnvPath);
469+
await fs.writeFile(fixture.envPath, "UNRELATED=value\n", "utf8");
470+
471+
const applied = await runSecretsApply({
472+
plan: createPlan({
473+
targets: [createOpenAiProviderTarget()],
474+
options: createOneWayScrubOptions(),
475+
}),
476+
env: {
477+
...fixture.env,
478+
OPENCLAW_CONFIG_PATH: configPath,
479+
OPENAI_API_KEY: "sk-openai-plaintext", // pragma: allowlist secret
480+
},
481+
write: true,
482+
});
483+
484+
expect(applied.changedFiles).not.toContain(configEnvPath);
485+
await expect(fs.readFile(configEnvPath, "utf8")).resolves.toContain(
486+
"OPENAI_API_KEY=sk-openai-plaintext",
487+
);
488+
489+
const nextConfig = JSON.parse(await fs.readFile(configPath, "utf8")) as {
490+
models: { providers: { openai: { apiKey: unknown } } };
491+
};
492+
expect(nextConfig.models.providers.openai.apiKey).toEqual(OPENAI_API_KEY_ENV_REF);
493+
494+
const freshProcessEnv = readStateDotEnvAsProcessEnv(fixture.envPath, configEnvPath);
495+
await expect(
496+
resolveSecretRefValue(OPENAI_API_KEY_ENV_REF, {
497+
config: nextConfig as never,
498+
env: freshProcessEnv,
499+
}),
500+
).resolves.toBe("sk-openai-plaintext");
501+
});
502+
503+
for (const { order, raw } of [
504+
{
505+
order: "before",
506+
raw: "OPENAI_API_KEY=sk-openai-plaintext\nOPENAI_API_KEY=sk-openai-stale\nUNRELATED=value\n", // pragma: allowlist secret
507+
},
508+
{
509+
order: "after",
510+
raw: "OPENAI_API_KEY=sk-openai-stale\nOPENAI_API_KEY=sk-openai-plaintext\nUNRELATED=value\n", // pragma: allowlist secret
511+
},
512+
]) {
513+
it(`removes a same-file duplicate declared ${order} the retained env SecretRef source`, async () => {
514+
await fs.writeFile(fixture.envPath, raw, "utf8");
515+
516+
const applied = await runSecretsApply({
517+
plan: createPlan({
518+
targets: [createOpenAiProviderTarget()],
519+
options: createOneWayScrubOptions(),
520+
}),
521+
env: { ...fixture.env, OPENAI_API_KEY: "sk-openai-plaintext" },
522+
write: true,
523+
});
524+
expect(applied.changedFiles).toContain(fixture.envPath);
525+
await expect(fs.readFile(fixture.envPath, "utf8")).resolves.toBe(
526+
"OPENAI_API_KEY=sk-openai-plaintext\nUNRELATED=value\n",
527+
);
528+
529+
const nextConfig = JSON.parse(await fs.readFile(fixture.configPath, "utf8")) as {
530+
models: { providers: { openai: { apiKey: unknown } } };
531+
};
532+
const freshProcessEnv = readStateDotEnvAsProcessEnv(fixture.envPath);
533+
expect(freshProcessEnv.OPENAI_API_KEY).toBe("sk-openai-plaintext");
534+
await expect(
535+
resolveSecretRefValue(OPENAI_API_KEY_ENV_REF, {
536+
config: nextConfig as never,
537+
env: freshProcessEnv,
538+
}),
539+
).resolves.toBe("sk-openai-plaintext");
540+
});
541+
}
542+
363543
it("preserves auth-profile tokenRef during provider scrub", async () => {
364544
await writeJsonFile(fixture.authStorePath, {
365545
version: 1,
@@ -1705,7 +1885,7 @@ describe("secrets apply", () => {
17051885

17061886
const env = {
17071887
HOME: homeDir,
1708-
OPENAI_API_KEY: "sk-openai-plaintext", // pragma: allowlist secret
1888+
OPENAI_API_KEY: "sk-live-env", // pragma: allowlist secret
17091889
};
17101890

17111891
await writeJsonFile(configPath, {
@@ -1771,7 +1951,7 @@ describe("secrets apply", () => {
17711951

17721952
const env = {
17731953
HOME: homeDir,
1774-
OPENAI_API_KEY: "sk-openai-plaintext", // pragma: allowlist secret
1954+
OPENAI_API_KEY: "sk-live-env", // pragma: allowlist secret
17751955
};
17761956

17771957
await writeJsonFile(configPath, {

‎src/secrets/apply.ts‎

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -153,29 +153,48 @@ function scrubEnvRaw(
153153
raw: string,
154154
migratedValues: Set<string>,
155155
allowedEnvKeys: Set<string>,
156+
retainableEnvValues: ReadonlyMap<string, string>,
156157
): {
157158
nextRaw: string;
158159
removed: number;
160+
retainedKeys: string[];
159161
} {
160162
if (migratedValues.size === 0 || allowedEnvKeys.size === 0) {
161-
return { nextRaw: raw, removed: 0 };
163+
return { nextRaw: raw, removed: 0, retainedKeys: [] };
162164
}
163165
const lines = raw.split(/\r?\n/);
166+
const assignments = lines.map((line) =>
167+
line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/),
168+
);
169+
const durableLineByKey = new Map<string, number>();
170+
assignments.forEach((match, index) => {
171+
const envKey = match?.[1] ?? "";
172+
if (
173+
allowedEnvKeys.has(envKey) &&
174+
retainableEnvValues.get(envKey) === parseEnvAssignmentValue(match?.[2] ?? "")
175+
) {
176+
durableLineByKey.set(envKey, index);
177+
}
178+
});
164179
const nextLines: string[] = [];
165180
let removed = 0;
166-
for (const line of lines) {
167-
const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
168-
if (!match) {
181+
for (const [index, line] of lines.entries()) {
182+
const match = assignments[index];
183+
const envKey = match?.[1] ?? "";
184+
if (!match || !allowedEnvKeys.has(envKey)) {
169185
nextLines.push(line);
170186
continue;
171187
}
172-
const envKey = match[1] ?? "";
173-
if (!allowedEnvKeys.has(envKey)) {
174-
nextLines.push(line);
188+
const durableLine = durableLineByKey.get(envKey);
189+
if (durableLine !== undefined) {
190+
if (durableLine === index) {
191+
nextLines.push(line);
192+
} else {
193+
removed += 1;
194+
}
175195
continue;
176196
}
177-
const parsedValue = parseEnvAssignmentValue(match[2] ?? "");
178-
if (migratedValues.has(parsedValue)) {
197+
if (migratedValues.has(parseEnvAssignmentValue(match[2] ?? ""))) {
179198
removed += 1;
180199
continue;
181200
}
@@ -189,6 +208,7 @@ function scrubEnvRaw(
189208
? `${joined}${joined.endsWith("\n") ? "" : "\n"}`
190209
: joined,
191210
removed,
211+
retainedKeys: [...durableLineByKey.keys()],
192212
};
193213
}
194214

@@ -336,6 +356,8 @@ async function projectPlanState(params: {
336356
configPath,
337357
stateDir,
338358
scrubbedValues: targetMutations.scrubbedValues,
359+
plannedTargets: params.plan.targets,
360+
env: params.env,
339361
changedFiles,
340362
enabled: options.scrubEnv,
341363
});
@@ -700,6 +722,8 @@ function scrubEnvFiles(params: {
700722
configPath: string;
701723
stateDir: string;
702724
scrubbedValues: Set<string>;
725+
plannedTargets: readonly SecretsPlanTarget[];
726+
env: NodeJS.ProcessEnv;
703727
changedFiles: Set<string>;
704728
enabled: boolean;
705729
}): Map<string, string> {
@@ -708,6 +732,12 @@ function scrubEnvFiles(params: {
708732
return envRawByPath;
709733
}
710734
const knownSecretEnvVars = new Set(listKnownSecretEnvVarNames());
735+
const envRefValuesAwaitingSource = new Map(
736+
params.plannedTargets.flatMap((target) => {
737+
const value = target.ref.source === "env" ? params.env[target.ref.id] : undefined;
738+
return isNonEmptyString(value) ? [[target.ref.id, value] as [string, string]] : [];
739+
}),
740+
);
711741
for (const envPath of listSecretsDotEnvPaths({
712742
configPath: params.configPath,
713743
stateDir: params.stateDir,
@@ -716,7 +746,15 @@ function scrubEnvFiles(params: {
716746
continue;
717747
}
718748
const current = fs.readFileSync(envPath, "utf8");
719-
const scrubbed = scrubEnvRaw(current, params.scrubbedValues, knownSecretEnvVars);
749+
const scrubbed = scrubEnvRaw(
750+
current,
751+
params.scrubbedValues,
752+
knownSecretEnvVars,
753+
envRefValuesAwaitingSource,
754+
);
755+
for (const retainedKey of scrubbed.retainedKeys) {
756+
envRefValuesAwaitingSource.delete(retainedKey);
757+
}
720758
if (scrubbed.removed > 0 && scrubbed.nextRaw !== current) {
721759
envRawByPath.set(envPath, scrubbed.nextRaw);
722760
params.changedFiles.add(envPath);

0 commit comments

Comments
 (0)