Skip to content

Commit 347ee45

Browse files
authored
fix(secrets): surface degradation in logs and doctor (#109792)
* fix(secrets): surface degraded owners safely * fix(secrets): preserve degradation ownership across reloads * fix(secrets): require cold ownership for source recovery * refactor(secrets): keep assignment provenance internal * test(secrets): use provider error contract * fix(secrets): attribute provider failures to active co-owners * test(secrets): clarify provider failure fixture * fix(secrets): redact doctor degradation reasons * test(secrets): align reload harness with runtime state * test(secrets): cover atomic source publication * fix(secrets): preserve web owner degradation context * fix(secrets): retain active web degradation co-owners * fix(secrets): keep web provider error internal * refactor(secrets): unify reload degradation state * refactor(config): remove obsolete source snapshot setter
1 parent 4a96c9d commit 347ee45

34 files changed

Lines changed: 3395 additions & 429 deletions

‎docs/cli/doctor.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ title: "Doctor"
1010

1111
Health checks and quick fixes for the gateway, channels, plugins, skills, model routing, local state, and config migrations. Use it whenever something is not behaving as expected and you want one command to explain what is wrong.
1212

13-
When Gateway status reports SecretRef owners isolated during cold startup, doctor prints a **Secret owners unavailable** warning with every owner and affected config path.
13+
When Gateway status reports SecretRef owners isolated during cold startup, doctor prints a **Secret runtime degradation** warning with every cold owner, affected config path, redacted reason, and the `openclaw secrets reload` retry command.
1414

1515
Related:
1616

‎docs/gateway/secrets.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,15 @@ Plaintext credentials remain agent-readable if they sit in files the agent can i
2121
## Runtime model
2222

2323
- Secrets resolve into an in-memory runtime snapshot, eagerly during activation, not lazily on request paths.
24-
- Cold Gateway startup isolates unavailable SecretRefs to a known non-Gateway owner when that owner supports isolation. Today this covers model providers and the built-in TTS capability. The Gateway starts, records that owner as configured-unavailable, and emits a redacted `SECRETS_OWNER_UNAVAILABLE` warning. Gateway ingress auth, structurally invalid refs or resolved values, and refs whose runtime owner is not yet mapped still fail startup.
24+
- Cold Gateway startup isolates unavailable SecretRefs to a known non-Gateway owner when that owner supports isolation. Today this covers model providers, the built-in TTS capability, web search and fetch providers, and webhook routes. The Gateway starts, records that owner as configured-unavailable, and emits a redacted `SECRETS_OWNER_UNAVAILABLE` warning. Gateway ingress auth, structurally invalid refs or resolved values, and refs whose runtime owner is not yet mapped still fail startup.
2525
- Reload is an atomic swap: full success, or keep the last-known-good snapshot.
2626
- Policy violations (for example an OAuth-mode auth profile combined with SecretRef input) fail activation before the runtime swap.
2727
- Runtime requests read only the active in-memory snapshot. Model-provider SecretRef credentials pass through auth storage and stream options as process-local sentinels until egress. Outbound delivery paths (Discord reply/thread delivery, Telegram action sends) also read that snapshot and do not re-resolve refs per send.
2828

2929
This keeps secret-provider outages off hot request paths.
3030

3131
<Note>
32-
Target policy for the SecretRef ownership-isolation migration: failures isolate to the smallest known owner. Only unavailable Gateway ingress protection, structurally invalid config, or unknown ownership will block startup; other affected capabilities, accounts, or routes will become configured-unavailable with typed redacted diagnostics and no implicit credential fallback. Reload will retain last-known-good only for an unchanged ref and provider, while a changed unresolved ref will make that owner cold. Doctor and status will list every degraded owner. This migration is not fully implemented; the current activation rules on this page remain in effect.
32+
Target policy for the SecretRef ownership-isolation migration: failures isolate to the smallest known owner. Only unavailable Gateway ingress protection, structurally invalid config, or unknown ownership will block startup; other affected capabilities, accounts, or routes will become configured-unavailable with typed redacted diagnostics and no implicit credential fallback. Reload will retain last-known-good only for an unchanged ref and provider, while a changed unresolved ref will make that owner cold. Doctor and structured Gateway warnings will identify degraded owners. This migration is not fully implemented; the current activation rules on this page remain in effect.
3333
</Note>
3434

3535
## Egress-time injection (sentinels)
@@ -617,6 +617,8 @@ Behavior:
617617
- Recovered: emitted once after the next successful activation.
618618
- Repeated failures while already degraded log warnings but do not re-emit the event.
619619
- Startup fail-fast never emits a degraded event, because runtime never became active.
620+
- Startup and reload failures emit a structured `SECRETS_DEGRADED` warning for each affected owner. The warning includes the owner kind and id, a redacted reason, `cold` or `stale` state, and the `openclaw secrets reload` retry hint. It never includes resolved values or SecretRef ids.
621+
- `openclaw doctor` lists owners isolated during cold startup with their affected config paths, redacted reason, and retry guidance.
620622

621623
## Command-path resolution
622624

‎src/commands/doctor-gateway-health.test.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,14 +120,21 @@ describe("checkGatewayHealth", () => {
120120
ownerId: "discord:ops",
121121
state: "unavailable",
122122
paths: ["channels.discord.accounts.ops.token"],
123-
reason: "secret reference was not found",
123+
reason: "secret reference was not found (env:default:PRIVATE_REF_ID)",
124124
},
125125
{
126126
ownerKind: "capability",
127127
ownerId: "tts",
128128
state: "unavailable",
129129
paths: ["messages.tts.providers.elevenlabs.apiKey"],
130-
reason: "secret provider failed",
130+
reason: "secret provider policy denied resolution",
131+
},
132+
{
133+
ownerKind: "capability",
134+
ownerId: "web-fetch:firecrawl",
135+
state: "unavailable",
136+
paths: ["plugins.entries.firecrawl.config.webFetch.apiKey"],
137+
reason: "resolved secret value was invalid",
131138
},
132139
],
133140
})
@@ -138,10 +145,14 @@ describe("checkGatewayHealth", () => {
138145

139146
expect(note).toHaveBeenCalledWith(
140147
[
141-
"- account:discord:ops (channels.discord.accounts.ops.token): secret reference was not found",
142-
"- capability:tts (messages.tts.providers.elevenlabs.apiKey): secret provider failed",
148+
"- cold account:discord:ops (channels.discord.accounts.ops.token): secret resolution failed",
149+
" Retry: openclaw secrets reload",
150+
"- cold capability:tts (messages.tts.providers.elevenlabs.apiKey): secret provider policy denied resolution",
151+
" Retry: openclaw secrets reload",
152+
"- cold capability:web-fetch:firecrawl (plugins.entries.firecrawl.config.webFetch.apiKey): resolved secret value was invalid",
153+
" Retry: openclaw secrets reload",
143154
].join("\n"),
144-
"Secret owners unavailable",
155+
"Secret runtime degradation",
145156
);
146157
});
147158

‎src/commands/doctor-gateway-health.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type {
1616
import { collectChannelStatusIssues } from "../infra/channels-status-issues.js";
1717
import { formatErrorMessage } from "../infra/errors.js";
1818
import type { RuntimeEnv } from "../runtime.js";
19+
import { redactSecretDegradationReason } from "../secrets/runtime-degraded-state.js";
1920
import { VERSION } from "../version.js";
2021
import {
2122
GATEWAY_HEALTH_CREDENTIALS_REQUIRED_MESSAGE,
@@ -91,10 +92,11 @@ export async function checkGatewayHealth(params: {
9192
status.degradedSecretOwners
9293
.map(
9394
(owner) =>
94-
`- ${owner.ownerKind}:${owner.ownerId} (${owner.paths.join(", ")}): ${owner.reason}`,
95+
`- cold ${owner.ownerKind}:${owner.ownerId} (${owner.paths.join(", ")}): ${redactSecretDegradationReason(owner.reason)}` +
96+
"\n Retry: openclaw secrets reload",
9597
)
9698
.join("\n"),
97-
"Secret owners unavailable",
99+
"Secret runtime degradation",
98100
);
99101
}
100102
if (status.degradedPlugins && status.degradedPlugins.length > 0) {

‎src/commands/status.summary.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ describe("getStatusSummary", () => {
286286
state: "unavailable",
287287
paths: ["channels.discord.accounts.ops.token"],
288288
refKeys: ["env:default:PRIVATE_REF_ID"],
289-
reason: "secret reference was not found",
289+
reason: "provider SecretRef is unresolved (env:default:PRIVATE_REF_ID)",
290290
},
291291
]);
292292

@@ -298,7 +298,7 @@ describe("getStatusSummary", () => {
298298
ownerId: "discord:ops",
299299
state: "unavailable",
300300
paths: ["channels.discord.accounts.ops.token"],
301-
reason: "secret reference was not found",
301+
reason: "secret resolution failed",
302302
},
303303
]);
304304
expect(JSON.stringify(summary.degradedSecretOwners)).not.toContain("PRIVATE_REF_ID");

‎src/commands/status.summary.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ import {
2121
toPublicPluginVerificationDiagnostic,
2222
} from "../plugins/runtime-degraded-state.js";
2323
import { parseAgentSessionKey } from "../routing/session-key.js";
24-
import { listActiveDegradedSecretOwners } from "../secrets/runtime-degraded-state.js";
24+
import {
25+
listActiveDegradedSecretOwners,
26+
redactSecretDegradationReason,
27+
} from "../secrets/runtime-degraded-state.js";
2528
import { createLazyImportLoader } from "../shared/lazy-promise.js";
2629
import { createLazyRuntimeSurface } from "../shared/lazy-runtime.js";
2730
import {
@@ -570,13 +573,16 @@ export async function getStatusSummary(
570573
channelSummary,
571574
queuedSystemEvents,
572575
degradedSecretOwners: listActiveDegradedSecretOwners().map(
573-
({ ownerKind, ownerId, state, paths: ownerPaths, reason }) => ({
574-
ownerKind,
575-
ownerId,
576-
state,
577-
paths: ownerPaths,
578-
reason,
579-
}),
576+
({ ownerKind, ownerId, state, paths: ownerPaths, reason }) => {
577+
const redactedReason: string = redactSecretDegradationReason(reason);
578+
return {
579+
ownerKind,
580+
ownerId,
581+
state,
582+
paths: ownerPaths,
583+
reason: redactedReason,
584+
};
585+
},
580586
),
581587
degradedPlugins: listActiveDegradedPlugins().map(({ pluginId, state, diagnostic }) => ({
582588
pluginId,

‎src/config/runtime-snapshot.ts‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -178,22 +178,6 @@ export function setAppliedRuntimeConfigSnapshot(
178178
runtimeConfigAppliedHash = hashRuntimeConfigValue(sourceConfig);
179179
}
180180

181-
/** Publish a newer canonical source without changing the active runtime object. */
182-
export function setRuntimeConfigSourceSnapshotIfCurrent(params: {
183-
expectedRevision: number;
184-
sourceConfig: OpenClawConfig;
185-
}): boolean {
186-
if (
187-
!runtimeConfigSnapshot ||
188-
!runtimeConfigSnapshotMetadata ||
189-
runtimeConfigSnapshotMetadata.revision !== params.expectedRevision
190-
) {
191-
return false;
192-
}
193-
setRuntimeConfigSnapshot(runtimeConfigSnapshot, params.sourceConfig);
194-
return true;
195-
}
196-
197181
export function resetConfigRuntimeState(): void {
198182
runtimeConfigSnapshot = null;
199183
runtimeConfigSourceSnapshot = null;

‎src/gateway/config-reload.test.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -667,7 +667,7 @@ function createReloaderHarness(
667667
nextConfig: OpenClawConfig,
668668
ownership: GatewayConfigReloadTransactionOwnership,
669669
sourceConfig: OpenClawConfig,
670-
) => Promise<() => Promise<void>>;
670+
) => Promise<{ rollback: () => Promise<void>; commit?: () => void }>;
671671
onConfigApplied?: (plan: GatewayReloadPlan, nextConfig: OpenClawConfig) => void | Promise<void>;
672672
onConfigRevisionApplied?: (hash: string) => void;
673673
onConfigChange?: (plan: GatewayReloadPlan, nextConfig: OpenClawConfig) => void | Promise<void>;
@@ -703,7 +703,7 @@ function createReloaderHarness(
703703
const onConfigAccepted = vi.fn(options.onConfigAccepted ?? (async () => {}));
704704
const onConfigRevisionApplied = vi.fn(options.onConfigRevisionApplied ?? (() => {}));
705705
const onEffectiveConfigUnchanged = vi.fn(
706-
options.onEffectiveConfigUnchanged ?? (async () => async () => {}),
706+
options.onEffectiveConfigUnchanged ?? (async () => ({ rollback: async () => {} })),
707707
);
708708
const onNoopConfigCommit = vi.fn(
709709
options.onNoopConfigCommit ??
@@ -3021,6 +3021,8 @@ describe("startGatewayConfigReloader", () => {
30213021
...initialConfig,
30223022
logging: { level: "debug" as const },
30233023
} satisfies OpenClawConfig;
3024+
const publicationEvents: string[] = [];
3025+
let publicationId = 0;
30243026
const rollbackSource = vi.fn(async () => {});
30253027
let emitSupersedingChange = () => {};
30263028
const harness = createReloaderHarness(
@@ -3032,7 +3034,18 @@ describe("startGatewayConfigReloader", () => {
30323034
queueMicrotask(emitSupersedingChange);
30333035
return rollback;
30343036
},
3035-
onEffectiveConfigUnchanged: async () => rollbackSource,
3037+
onEffectiveConfigUnchanged: async () => {
3038+
const id = publicationId++;
3039+
return {
3040+
rollback: async () => {
3041+
publicationEvents.push(`rollback:${id}`);
3042+
await rollbackSource();
3043+
},
3044+
commit: () => {
3045+
publicationEvents.push(`commit:${id}`);
3046+
},
3047+
};
3048+
},
30363049
},
30373050
);
30383051
emitSupersedingChange = () => {
@@ -3063,6 +3076,7 @@ describe("startGatewayConfigReloader", () => {
30633076
initialConfig,
30643077
]);
30653078
expect(rollbackSource).toHaveBeenCalledOnce();
3079+
expect(publicationEvents).toEqual(["rollback:0", "commit:1"]);
30663080

30673081
await harness.reloader.stop();
30683082
});

‎src/gateway/config-reload.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,11 @@ export function startGatewayConfigReloader(opts: {
175175
nextConfig: OpenClawConfig,
176176
ownership: GatewayConfigReloadTransactionOwnership,
177177
sourceConfig: OpenClawConfig,
178-
) => Promise<() => Promise<void>>;
178+
) => Promise<{
179+
rollback: () => Promise<void>;
180+
/** Runs only when this exact source publication can no longer roll back. */
181+
commit?: () => void;
182+
}>;
179183
onNoopConfigCommit: (
180184
plan: GatewayReloadPlan,
181185
nextConfig: OpenClawConfig,
@@ -497,16 +501,27 @@ export function startGatewayConfigReloader(opts: {
497501
}
498502
};
499503
if (changedPaths.length === 0) {
504+
let publishedSource: { rollback: () => Promise<void>; commit?: () => void } | undefined;
500505
let publishedSourceRollback: (() => Promise<void>) | undefined;
506+
let publishedSourceRolledBack = false;
501507
const publishSource = opts.onEffectiveConfigUnchanged
502-
? async () =>
503-
(publishedSourceRollback ??= await opts.onEffectiveConfigUnchanged!(
508+
? async () => {
509+
publishedSource ??= await opts.onEffectiveConfigUnchanged!(
504510
nextConfig,
505511
ownership,
506512
nextSourceConfig,
507-
))
513+
);
514+
publishedSourceRollback ??= async () => {
515+
publishedSourceRolledBack = true;
516+
await publishedSource?.rollback();
517+
};
518+
return publishedSourceRollback;
519+
}
508520
: undefined;
509521
await commitReloadBaseline(publishSource ? { publishSource } : {});
522+
if (!publishedSourceRolledBack) {
523+
publishedSource?.commit?.();
524+
}
510525
opts.onConfigRevisionApplied?.(nextConfigRevisionHash);
511526
return;
512527
}

‎src/gateway/server-aux-handlers.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -413,8 +413,18 @@ describe("gateway aux handlers", () => {
413413
canonicalConfig,
414414
]);
415415
expect(activateRuntimeSecrets.mock.calls.map(([, activation]) => activation)).toEqual([
416-
{ reason: "reload", activate: false },
417-
{ reason: "reload", activate: false },
416+
{
417+
reason: "reload",
418+
activate: false,
419+
publishFailureAsDegraded: true,
420+
canPublishFailureAsDegraded: expect.any(Function),
421+
},
422+
{
423+
reason: "reload",
424+
activate: false,
425+
publishFailureAsDegraded: true,
426+
canPublishFailureAsDegraded: expect.any(Function),
427+
},
418428
]);
419429
expect(activatePreparedSnapshotIfCurrent).toHaveBeenCalledTimes(2);
420430
expect(getActiveSecretsRuntimeSnapshot()?.sourceConfig).toEqual(canonicalConfig);

0 commit comments

Comments
 (0)