Skip to content

Commit 31145e0

Browse files
samzongsteipete
andauthored
[Fix] Preflight runtime SecretRefs before config writes (#84454)
* fix(config): preflight runtime secret refs before writes * fix(config): restore include rollback env * docs(changelog): note SecretRef config preflight --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 81dee15 commit 31145e0

11 files changed

Lines changed: 1187 additions & 95 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ Docs: https://docs.openclaw.ai
6565
### Fixes
6666

6767
- Discord/voice: keep realtime playback running when meeting notes attaches to an existing voice session or a realtime consult starts, and route realtime user transcripts into meeting notes.
68+
- Config/secrets: preflight active runtime SecretRefs before root and include config writes persist, and roll back unchanged file/env state when post-write refresh fails. Fixes #46531. (#84454) Thanks @samzong.
6869
- WebChat: keep the run-complete indicator in progress until deferred history replay renders the assistant reply, so Done no longer appears before response text. (#85374) Thanks @neeravmakwana.
6970
- Agents/tools: give timed-out or cancelled process trees a bounded SIGTERM cleanup window before SIGKILL while preserving tree-aware cancellation. Fixes #66399. (#85865) Thanks @IWhatsskill.
7071
- Agents/compaction: skip agent-harness preflight for provider-owned CLI runtime sessions so over-threshold Claude CLI sessions continue through normal compaction instead of failing on a missing harness. Fixes #84857. (#84878) Thanks @zhangguiping-xydt.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
0516394dbae9a5a497ad1c8eb568a10b88db9026be537e6b5671a198c71ea459 plugin-sdk-api-baseline.json
2-
635c4205b8ce8d84f67fe7183536d5c0a65eeec087eae75245e7e936cebca9c3 plugin-sdk-api-baseline.jsonl
1+
8882e41620deeed05be9526981c32a034444abc232903b946c48d416f46f06c3 plugin-sdk-api-baseline.json
2+
40b22ddad62692447717a2b4f0ecdbd9f6209fa86eaf4e66f85d37c48e26d394 plugin-sdk-api-baseline.jsonl

‎src/config/io.ts‎

Lines changed: 192 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ import {
9292
getRuntimeConfigSourceSnapshot as getRuntimeConfigSourceSnapshotState,
9393
loadPinnedRuntimeConfig,
9494
notifyRuntimeConfigWriteListeners,
95+
preflightRuntimeSnapshotWrite,
9596
registerRuntimeConfigWriteListener,
9697
resetConfigRuntimeState as resetConfigRuntimeStateState,
9798
resolveRuntimeConfigCacheKey,
@@ -135,6 +136,7 @@ type ShippedPluginInstallConfigWriteMigration =
135136
| {
136137
migrated: true;
137138
filePath: string;
139+
writtenHash: string;
138140
previousFile:
139141
| {
140142
existed: false;
@@ -184,6 +186,10 @@ type ConfigHealthState = {
184186

185187
export type ParseConfigJson5Result = { ok: true; parsed: unknown } | { ok: false; error: string };
186188
export type ConfigWriteResult = { persistedHash: string; persistedConfig: OpenClawConfig };
189+
const configWritePostCommitRollback = Symbol("configWritePostCommitRollback");
190+
type InternalConfigWriteResult = ConfigWriteResult & {
191+
[configWritePostCommitRollback]?: () => void;
192+
};
187193
export type ConfigWriteOptions = {
188194
/**
189195
* Read-time env snapshot used to validate `${VAR}` restoration decisions.
@@ -261,6 +267,11 @@ export type ConfigWriteOptions = {
261267
* readable by the parent process after a candidate doctor repair.
262268
*/
263269
lastTouchedVersionOverride?: string;
270+
/**
271+
* Internal hook used by the exported runtime-aware writer after validation
272+
* has produced the exact source config that will be committed.
273+
*/
274+
preCommitRuntimePreflight?: (sourceConfig: OpenClawConfig) => Promise<unknown>;
264275
};
265276

266277
export type ReadConfigFileSnapshotForWriteResult = {
@@ -327,6 +338,46 @@ export function resolveConfigSnapshotHash(snapshot: {
327338
return hashConfigRaw(snapshot.raw);
328339
}
329340

341+
async function rollbackConfigFileWriteIfUnchanged(params: {
342+
configPath: string;
343+
previousSnapshot: ConfigFileSnapshot;
344+
committedHash: string;
345+
}): Promise<boolean> {
346+
let currentRaw: string | null = null;
347+
try {
348+
currentRaw = await fs.promises.readFile(params.configPath, "utf-8");
349+
} catch (error) {
350+
if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
351+
throw error;
352+
}
353+
}
354+
if (hashConfigRaw(currentRaw) !== params.committedHash) {
355+
return false;
356+
}
357+
if (params.previousSnapshot.exists && typeof params.previousSnapshot.raw === "string") {
358+
await replaceFileAtomic({
359+
filePath: params.configPath,
360+
content: params.previousSnapshot.raw,
361+
dirMode: 0o700,
362+
mode: 0o600,
363+
tempPrefix: path.basename(params.configPath),
364+
copyFallbackOnPermissionError: true,
365+
});
366+
return true;
367+
}
368+
if (params.previousSnapshot.exists) {
369+
return false;
370+
}
371+
try {
372+
await fs.promises.unlink(params.configPath);
373+
} catch (error) {
374+
if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
375+
throw error;
376+
}
377+
}
378+
return true;
379+
}
380+
330381
function coerceConfig(value: unknown): OpenClawConfig {
331382
if (!value || typeof value !== "object" || Array.isArray(value)) {
332383
return {};
@@ -1190,6 +1241,29 @@ function resolveConfigForRead(
11901241
};
11911242
}
11921243

1244+
function snapshotEnv(env: NodeJS.ProcessEnv): Record<string, string | undefined> {
1245+
return { ...env };
1246+
}
1247+
1248+
export function restoreEnvChangesIfUnchanged(params: {
1249+
env: NodeJS.ProcessEnv;
1250+
before: Record<string, string | undefined>;
1251+
after: Record<string, string | undefined>;
1252+
}): void {
1253+
const keys = new Set([...Object.keys(params.before), ...Object.keys(params.after)]);
1254+
for (const key of keys) {
1255+
if (params.before[key] === params.after[key] || params.env[key] !== params.after[key]) {
1256+
continue;
1257+
}
1258+
const previous = params.before[key];
1259+
if (previous === undefined) {
1260+
delete params.env[key];
1261+
} else {
1262+
params.env[key] = previous;
1263+
}
1264+
}
1265+
}
1266+
11931267
type ReadConfigFileSnapshotInternalResult = {
11941268
snapshot: ConfigFileSnapshot;
11951269
envSnapshotForRestore?: Record<string, string | undefined>;
@@ -1444,6 +1518,21 @@ export function createConfigIO(
14441518
};
14451519
}
14461520

1521+
function resolveRuntimePreflightSourceConfig(candidate: OpenClawConfig): OpenClawConfig {
1522+
const env = { ...deps.env } as NodeJS.ProcessEnv;
1523+
const resolvedIncludes = resolveConfigIncludesForRead(candidate, configPath, {
1524+
...deps,
1525+
env,
1526+
});
1527+
const readResolution = resolveConfigForRead(resolvedIncludes, env);
1528+
return coerceConfig(
1529+
migrateAndStripShippedPluginInstallConfigRecords(readResolution.resolvedConfigRaw, {
1530+
persist: false,
1531+
rootConfigRaw: candidate,
1532+
}).config,
1533+
);
1534+
}
1535+
14471536
function ensureShippedPluginInstallConfigRecordsMigratedForWrite(
14481537
snapshot: ConfigFileSnapshot,
14491538
): ShippedPluginInstallConfigWriteMigration {
@@ -1475,7 +1564,7 @@ export function createConfigIO(
14751564
} as const)
14761565
: ({ existed: false } as const);
14771566
try {
1478-
writePersistedInstalledPluginIndexInstallRecordsSync(
1567+
const writtenPath = writePersistedInstalledPluginIndexInstallRecordsSync(
14791568
{
14801569
...installRecords,
14811570
...existingRecords,
@@ -1486,9 +1575,13 @@ export function createConfigIO(
14861575
stateDir,
14871576
},
14881577
);
1578+
const writtenRaw = deps.fs.existsSync(writtenPath)
1579+
? deps.fs.readFileSync(writtenPath, "utf-8")
1580+
: null;
14891581
return {
14901582
migrated: true,
1491-
filePath,
1583+
filePath: writtenPath,
1584+
writtenHash: hashConfigRaw(writtenRaw),
14921585
previousFile,
14931586
};
14941587
} catch (err) {
@@ -1503,16 +1596,22 @@ export function createConfigIO(
15031596

15041597
function rollbackShippedPluginInstallConfigWriteMigration(
15051598
migration: ShippedPluginInstallConfigWriteMigration,
1506-
): void {
1599+
): boolean {
15071600
if (!migration.migrated) {
1508-
return;
1601+
return false;
1602+
}
1603+
const currentRaw = deps.fs.existsSync(migration.filePath)
1604+
? deps.fs.readFileSync(migration.filePath, "utf-8")
1605+
: null;
1606+
if (hashConfigRaw(currentRaw) !== migration.writtenHash) {
1607+
return false;
15091608
}
15101609
if (migration.previousFile.existed) {
15111610
deps.fs.writeFileSync(migration.filePath, migration.previousFile.raw, {
15121611
encoding: "utf-8",
15131612
mode: 0o600,
15141613
});
1515-
return;
1614+
return true;
15161615
}
15171616
try {
15181617
deps.fs.unlinkSync(migration.filePath);
@@ -1521,6 +1620,7 @@ export function createConfigIO(
15211620
throw err;
15221621
}
15231622
}
1623+
return true;
15241624
}
15251625

15261626
function loadConfig(): OpenClawConfig {
@@ -2025,7 +2125,7 @@ export function createConfigIO(
20252125
async function writeConfigFile(
20262126
cfg: OpenClawConfig,
20272127
options: ConfigWriteOptions = {},
2028-
): Promise<{ persistedHash: string; persistedConfig: OpenClawConfig }> {
2128+
): Promise<InternalConfigWriteResult> {
20292129
assertConfigWriteAllowedInCurrentMode({ configPath, env: deps.env });
20302130
clearConfigCache();
20312131
const unsetPaths = resolveManagedUnsetPathsForWrite(options.unsetPaths);
@@ -2267,6 +2367,22 @@ export function createConfigIO(
22672367
throw err;
22682368
}
22692369

2370+
const preCommitRuntimePreflight =
2371+
options.preCommitRuntimePreflight ??
2372+
(async (sourceConfig: OpenClawConfig) => {
2373+
await preflightRuntimeSnapshotWrite({
2374+
nextSourceConfig: sourceConfig,
2375+
refreshOptions: options.runtimeRefresh,
2376+
formatRefreshError: (error) => formatErrorMessage(error),
2377+
createRefreshError: (detail, cause) =>
2378+
new ConfigRuntimeRefreshError(
2379+
`Config write blocked before committing ${configPath}: active SecretRef resolution failed: ${detail}`,
2380+
{ cause },
2381+
),
2382+
});
2383+
});
2384+
await preCommitRuntimePreflight(resolveRuntimePreflightSourceConfig(stampedOutputConfig));
2385+
22702386
const pluginInstallConfigMigration =
22712387
ensureShippedPluginInstallConfigRecordsMigratedForWrite(snapshot);
22722388
let configCommitted = false;
@@ -2293,7 +2409,17 @@ export function createConfigIO(
22932409
undefined,
22942410
await deps.fs.promises.stat(configPath).catch(() => null),
22952411
);
2296-
return { persistedHash: nextHash, persistedConfig: stampedOutputConfig };
2412+
return {
2413+
persistedHash: nextHash,
2414+
persistedConfig: stampedOutputConfig,
2415+
...(pluginInstallConfigMigration.migrated
2416+
? {
2417+
[configWritePostCommitRollback]: () => {
2418+
rollbackShippedPluginInstallConfigWriteMigration(pluginInstallConfigMigration);
2419+
},
2420+
}
2421+
: {}),
2422+
};
22972423
} catch (err) {
22982424
if (!configCommitted) {
22992425
rollbackShippedPluginInstallConfigWriteMigration(pluginInstallConfigMigration);
@@ -2305,6 +2431,7 @@ export function createConfigIO(
23052431

23062432
return {
23072433
configPath,
2434+
env: deps.env,
23082435
loadConfig,
23092436
readBestEffortConfig,
23102437
readSourceConfigBestEffort,
@@ -2486,8 +2613,10 @@ export async function writeConfigFile(
24862613
const runtimePatch = createMergePatch(runtimeConfigSnapshot!, cfg);
24872614
nextCfg = coerceConfig(applyMergePatch(runtimeConfigSourceSnapshot!, runtimePatch));
24882615
}
2616+
const baseSnapshot = options.baseSnapshot ?? (await io.readConfigFileSnapshot());
2617+
let runtimePreflightResult: unknown;
24892618
const writeResult = await io.writeConfigFile(nextCfg, {
2490-
baseSnapshot: options.baseSnapshot,
2619+
baseSnapshot,
24912620
envSnapshotForRestore: resolveWriteEnvSnapshotForPath({
24922621
actualConfigPath: io.configPath,
24932622
expectedConfigPath: options.expectedConfigPath,
@@ -2506,6 +2635,18 @@ export async function writeConfigFile(
25062635
skipPluginValidation: options.skipPluginValidation,
25072636
preservedLegacyRootKeys: options.preservedLegacyRootKeys,
25082637
lastTouchedVersionOverride: options.lastTouchedVersionOverride,
2638+
preCommitRuntimePreflight: async (sourceConfig) => {
2639+
runtimePreflightResult = await preflightRuntimeSnapshotWrite({
2640+
nextSourceConfig: sourceConfig,
2641+
refreshOptions: options.runtimeRefresh,
2642+
formatRefreshError: (error) => formatErrorMessage(error),
2643+
createRefreshError: (detail, cause) =>
2644+
new ConfigRuntimeRefreshError(
2645+
`Config write blocked before committing ${io.configPath}: active SecretRef resolution failed: ${detail}`,
2646+
{ cause },
2647+
),
2648+
});
2649+
},
25092650
});
25102651
if (
25112652
options.skipRuntimeSnapshotRefresh &&
@@ -2527,6 +2668,8 @@ export async function writeConfigFile(
25272668
// triggering a `plugins`-scoped restart of the gateway for changes that
25282669
// never touched any plugin entry.
25292670
let canonicalSourceConfig: OpenClawConfig = nextCfg;
2671+
const envBeforeCanonicalRead = snapshotEnv(process.env);
2672+
let envAfterCanonicalRead = envBeforeCanonicalRead;
25302673
try {
25312674
const freshSnapshot = await io.readConfigFileSnapshot();
25322675
if (freshSnapshot.exists && freshSnapshot.valid) {
@@ -2535,6 +2678,8 @@ export async function writeConfigFile(
25352678
} catch {
25362679
// Best-effort; fall back to nextCfg so a transient read failure does not
25372680
// block the write notification.
2681+
} finally {
2682+
envAfterCanonicalRead = snapshotEnv(process.env);
25382683
}
25392684
const notifyCommittedWrite = () => {
25402685
const currentRuntimeConfig = getRuntimeConfigSnapshotState();
@@ -2553,19 +2698,44 @@ export async function writeConfigFile(
25532698
};
25542699
// Keep the last-known-good runtime snapshot active until the specialized refresh path
25552700
// succeeds, so concurrent readers do not observe unresolved SecretRefs mid-refresh.
2556-
await finalizeRuntimeSnapshotWrite({
2557-
nextSourceConfig: canonicalSourceConfig,
2558-
refreshOptions: options.runtimeRefresh,
2559-
hadRuntimeSnapshot,
2560-
hadBothSnapshots,
2561-
loadFreshConfig: () => io.loadConfig(),
2562-
notifyCommittedWrite,
2563-
formatRefreshError: (error) => formatErrorMessage(error),
2564-
createRefreshError: (detail, cause) =>
2565-
new ConfigRuntimeRefreshError(
2566-
`Config was written to ${io.configPath}, but runtime snapshot refresh failed: ${detail}`,
2567-
{ cause },
2568-
),
2569-
});
2701+
try {
2702+
await finalizeRuntimeSnapshotWrite({
2703+
nextSourceConfig: canonicalSourceConfig,
2704+
refreshOptions: options.runtimeRefresh,
2705+
hadRuntimeSnapshot,
2706+
hadBothSnapshots,
2707+
loadFreshConfig: () => io.loadConfig(),
2708+
notifyCommittedWrite,
2709+
formatRefreshError: (error) => formatErrorMessage(error),
2710+
preflightResult: runtimePreflightResult,
2711+
createRefreshError: (detail, cause) =>
2712+
new ConfigRuntimeRefreshError(
2713+
`Config was written to ${io.configPath}, but runtime snapshot refresh failed: ${detail}`,
2714+
{ cause },
2715+
),
2716+
});
2717+
} catch (error) {
2718+
try {
2719+
const rolledBackConfig = await rollbackConfigFileWriteIfUnchanged({
2720+
configPath: io.configPath,
2721+
previousSnapshot: baseSnapshot,
2722+
committedHash: writeResult.persistedHash,
2723+
});
2724+
if (rolledBackConfig) {
2725+
restoreEnvChangesIfUnchanged({
2726+
env: process.env,
2727+
before: envBeforeCanonicalRead,
2728+
after: envAfterCanonicalRead,
2729+
});
2730+
writeResult[configWritePostCommitRollback]?.();
2731+
}
2732+
} catch (rollbackError) {
2733+
throw new ConfigRuntimeRefreshError(
2734+
`${formatErrorMessage(error)} Rollback failed: ${formatErrorMessage(rollbackError)}`,
2735+
{ cause: error },
2736+
);
2737+
}
2738+
throw error;
2739+
}
25702740
return { ...writeResult, persistedConfig: canonicalSourceConfig };
25712741
}

0 commit comments

Comments
 (0)