Skip to content

Commit 2ecd342

Browse files
authored
fix(gateway): recover credential-file accounts after secrets reload (#126999)
* fix(gateway): recover credential-file accounts on secrets reload Preserve independently discovered credential-file degradation across runtime snapshot refreshes, and re-inspect only the affected account when secrets are reloaded. Healthy sibling accounts remain running while status and doctor retain exact-owner diagnostics until recovery or teardown. * test(gateway): prove credential-file reload recovery * test(gateway): assert redacted reload error code
1 parent 9feb1db commit 2ecd342

14 files changed

Lines changed: 1093 additions & 454 deletions

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

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
33
import { SESSION_TOTAL_TOKENS_VERSION } from "../config/sessions/types.js";
44
import { setActiveDegradedPlugins } from "../plugins/runtime-degraded-state.js";
5-
import { setActiveDegradedSecretOwners } from "../secrets/runtime-degraded-state.js";
5+
import {
6+
clearActiveCredentialDegradedOwner,
7+
setActiveCredentialDegradedOwner,
8+
setActiveDegradedSecretOwners,
9+
} from "../secrets/runtime-degraded-state.js";
610
import type { TaskAuditFinding } from "../tasks/task-registry.audit.js";
711
import type { TaskRecord, TaskRegistrySummary } from "../tasks/task-registry.types.js";
812
import { normalizeSessionDeliveryState } from "../utils/delivery-context.shared.js";
@@ -219,6 +223,7 @@ describe("getStatusSummary", () => {
219223
beforeEach(() => {
220224
vi.clearAllMocks();
221225
setActiveDegradedPlugins([]);
226+
clearActiveCredentialDegradedOwner("account", "telegram:work");
222227
setActiveDegradedSecretOwners([]);
223228
statusSummaryMocks.taskRegistrySummary = {
224229
total: 0,
@@ -406,28 +411,44 @@ describe("getStatusSummary", () => {
406411
});
407412
});
408413

409-
it("reports degraded SecretRef owners without exposing ref identifiers", async () => {
414+
it("reports stale snapshot and cold credential owners without exposing ref identifiers", async () => {
410415
setActiveDegradedSecretOwners([
411416
{
412-
ownerKind: "account",
413-
ownerId: "discord:ops",
417+
ownerKind: "provider",
418+
ownerId: "openai",
414419
state: "unavailable",
415-
degradationState: "cold",
416-
paths: ["channels.discord.accounts.ops.token"],
420+
degradationState: "stale",
421+
paths: ["models.providers.openai.apiKey"],
417422
refKeys: ["env:default:PRIVATE_REF_ID"],
418423
reason: "provider SecretRef is unresolved (env:default:PRIVATE_REF_ID)",
419424
},
420425
]);
426+
setActiveCredentialDegradedOwner({
427+
ownerKind: "account",
428+
ownerId: "telegram:work",
429+
state: "unavailable",
430+
paths: ["channels.telegram.accounts.work.tokenFile"],
431+
refKeys: [],
432+
reason: "credential failure includes PRIVATE_REF_ID",
433+
});
421434

422435
const summary = await getStatusSummary();
423436

424437
expect(summary.degradedSecretOwners).toEqual([
438+
{
439+
ownerKind: "provider",
440+
ownerId: "openai",
441+
state: "unavailable",
442+
degradationState: "stale",
443+
paths: ["models.providers.openai.apiKey"],
444+
reason: "secret resolution failed",
445+
},
425446
{
426447
ownerKind: "account",
427-
ownerId: "discord:ops",
448+
ownerId: "telegram:work",
428449
state: "unavailable",
429450
degradationState: "cold",
430-
paths: ["channels.discord.accounts.ops.token"],
451+
paths: ["channels.telegram.accounts.work.tokenFile"],
431452
reason: "secret resolution failed",
432453
},
433454
]);

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

Lines changed: 113 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ import {
3333
claimAgentRunDelegatedAuthority,
3434
releaseAgentRunDelegatedAuthority,
3535
} from "../infra/agent-run-registry.js";
36+
import {
37+
setActiveCredentialDegradedOwner,
38+
type DegradedSecretOwner,
39+
} from "../secrets/runtime-degraded-state.js";
3640
import {
3741
activateSecretsRuntimeSnapshot,
3842
clearSecretsRuntimeSnapshot,
@@ -47,6 +51,10 @@ import {
4751
import { createAgentRuntimeApprovalAuthorityValidator } from "./agent-runtime-identity-token.js";
4852
import type { GatewayReloadPlan } from "./config-reload.js";
4953
import { createGatewayAuxHandlers } from "./server-aux-handlers.js";
54+
import {
55+
registerGatewaySecretCredentialReloadCases,
56+
type CredentialReloadHarnessOptions,
57+
} from "./server-secrets-reload.test-support.js";
5058
import { enforceSharedGatewaySessionGenerationForConfigWrite } from "./server-shared-auth-generation.js";
5159
import { createWorkerSessionPlacementStore } from "./worker-environments/placement-store.js";
5260

@@ -185,7 +193,8 @@ async function invokeSecretStoreSet(params: {
185193

186194
type RespondCall = [boolean, unknown, { message?: string } | undefined];
187195
type GatewayAuxHandlerParams = Parameters<typeof createGatewayAuxHandlers>[0];
188-
type ChannelName = Parameters<GatewayAuxHandlerParams["startChannel"]>[0];
196+
type GatewayChannelManager = GatewayAuxHandlerParams["channelManager"];
197+
type ChannelName = Parameters<GatewayChannelManager["startChannel"]>[0];
189198

190199
function firstRespondCall(respond: ReturnType<typeof vi.fn>): RespondCall {
191200
const call = respond.mock.calls[0];
@@ -208,8 +217,10 @@ type SecretsReloadHarnessParams = {
208217
sharedGatewaySessionGenerationState?: GatewayAuxHandlerParams["sharedGatewaySessionGenerationState"];
209218
resolveSharedGatewaySessionGenerationForConfig?: GatewayAuxHandlerParams["resolveSharedGatewaySessionGenerationForConfig"];
210219
clients?: GatewayAuxHandlerParams["clients"];
211-
startChannel?: GatewayAuxHandlerParams["startChannel"];
212-
stopChannel?: GatewayAuxHandlerParams["stopChannel"];
220+
startChannel?: GatewayChannelManager["startChannel"];
221+
stopChannel?: GatewayChannelManager["stopChannel"];
222+
isManuallyStopped?: (channel: ChannelName, accountId: string) => boolean;
223+
resolveRuntimeAccountId?: (channel: ChannelName, accountId: string) => string | undefined;
213224
getChannelAutostartSuppression?: GatewayAuxHandlerParams["getChannelAutostartSuppression"];
214225
logChannelsInfo?: GatewayAuxHandlerParams["logChannels"]["info"];
215226
respond?: ReturnType<typeof vi.fn>;
@@ -232,8 +243,13 @@ function createSecretsReloadHarness(params: SecretsReloadHarnessParams) {
232243
resolveSharedGatewaySessionGenerationForConfig:
233244
params.resolveSharedGatewaySessionGenerationForConfig ?? (() => undefined),
234245
clients: params.clients ?? [],
235-
startChannel: params.startChannel ?? (async () => {}),
236-
stopChannel: params.stopChannel ?? (async () => {}),
246+
channelManager: {
247+
startChannel: params.startChannel ?? (async () => {}),
248+
stopChannel: params.stopChannel ?? (async () => {}),
249+
isManuallyStopped: params.isManuallyStopped ?? (() => false),
250+
resolveRuntimeAccountId:
251+
params.resolveRuntimeAccountId ?? ((_channel, accountId) => accountId),
252+
},
237253
getChannelAutostartSuppression: params.getChannelAutostartSuppression,
238254
logChannels: { info: params.logChannelsInfo ?? vi.fn() },
239255
onApprovalLifecycle: params.onApprovalLifecycle,
@@ -267,6 +283,42 @@ function createSecretsReloadHarnessWithChannelMocks(
267283
};
268284
}
269285

286+
function createCredentialReloadHarness(options: CredentialReloadHarnessOptions = {}) {
287+
const ownerAccountId = options.ownerAccountId ?? "ops";
288+
const owner: DegradedSecretOwner = {
289+
ownerKind: "account",
290+
ownerId: `slack:${ownerAccountId}`,
291+
state: "unavailable",
292+
paths: ["env.SERVICE_ACCOUNT_FILE"],
293+
refKeys: [],
294+
reason: "credential file is unavailable",
295+
};
296+
const config = slackConfig("unchanged-secret");
297+
activateSnapshot(config);
298+
setActiveCredentialDegradedOwner(owner);
299+
const startChannel = vi.fn().mockImplementation(async () => {
300+
if (options.createFailure) {
301+
throw options.createFailure(owner);
302+
}
303+
});
304+
const stopChannel = vi.fn().mockResolvedValue(undefined);
305+
const isManuallyStopped = vi.fn(() => options.manualStop ?? false);
306+
return {
307+
...createSecretsReloadHarness({
308+
activateRuntimeSecrets: mockResolvedSecrets(config),
309+
buildReloadPlan: () => createReloadPlan(),
310+
startChannel,
311+
stopChannel,
312+
isManuallyStopped,
313+
resolveRuntimeAccountId: () => options.runtimeAccountId ?? ownerAccountId,
314+
}),
315+
owner,
316+
startChannel,
317+
stopChannel,
318+
isManuallyStopped,
319+
};
320+
}
321+
270322
// Other gateway test helpers (e.g. test-helpers.mocks.ts, test-helpers.server.ts)
271323
// set OPENCLAW_SKIP_CHANNELS / OPENCLAW_SKIP_PROVIDERS at module load. When a
272324
// shared vitest worker imports those helpers before this file's tests run,
@@ -551,18 +603,13 @@ describe("gateway aux handlers", () => {
551603
expect(respond).toHaveBeenCalledWith(true, { ok: true, warningCount: 0 });
552604
});
553605

554-
it("restarts the whole channel when a secret change is scoped to one account", async () => {
555-
// secrets.reload has no per-account restart path — account-scoped plan
556-
// entries must still produce a channel restart so rotated credentials
557-
// are applied.
606+
it("restarts only the changed account when a secret change is account-scoped", async () => {
558607
const buildReloadPlan = () =>
559608
createReloadPlan({
560-
restartChannels: new Set(),
561609
restartChannelAccounts: new Map([["slack", new Set(["ops"])]]),
562610
});
563611
activateSnapshot(slackConfig("old-slack-secret"));
564-
const prepared = createSnapshot(slackConfig("new-slack-secret"));
565-
const activateRuntimeSecrets = vi.fn().mockResolvedValue(prepared);
612+
const activateRuntimeSecrets = mockResolvedSecrets(slackConfig("new-slack-secret"));
566613
const { reload, respond, startChannel, stopChannel } =
567614
createSecretsReloadHarnessWithChannelMocks({
568615
activateRuntimeSecrets,
@@ -571,11 +618,30 @@ describe("gateway aux handlers", () => {
571618

572619
await reload();
573620

574-
expect(stopChannel.mock.calls.map(([ch]) => ch)).toEqual(["slack"]);
575-
expect(startChannel.mock.calls.map(([ch]) => ch)).toEqual(["slack"]);
621+
expect(stopChannel.mock.calls).toEqual([["slack", "ops", { manual: false }]]);
622+
expect(startChannel.mock.calls).toEqual([["slack", "ops", { preserveManualStop: true }]]);
576623
expect(respond).toHaveBeenCalledWith(true, { ok: true, warningCount: 0 });
577624
});
578625

626+
registerGatewaySecretCredentialReloadCases(createCredentialReloadHarness);
627+
628+
it("does not restart account targets already covered by a whole-channel target", async () => {
629+
activateSnapshot(slackConfig("old-secret"));
630+
const { reload, startChannel, stopChannel } = createSecretsReloadHarnessWithChannelMocks({
631+
activateRuntimeSecrets: mockResolvedSecrets(slackConfig("new-secret")),
632+
buildReloadPlan: () =>
633+
createReloadPlan({
634+
restartChannels: new Set(["slack"]),
635+
restartChannelAccounts: new Map([["slack", new Set(["ops"])]]),
636+
}),
637+
});
638+
639+
await reload();
640+
641+
expect(stopChannel.mock.calls).toEqual([["slack"]]);
642+
expect(startChannel.mock.calls).toEqual([["slack"]]);
643+
});
644+
579645
it("coalesces concurrent secrets.reload calls so channels are not restarted twice", async () => {
580646
const buildReloadPlan = buildRestartChannelsPlan("slack");
581647
activateSnapshot(slackConfig("old-slack-secret"));
@@ -731,9 +797,15 @@ describe("gateway aux handlers", () => {
731797
expect(firstRespondCall(respond)[0]).toBe(true);
732798
});
733799

734-
it("rolls back stopped channels when a later restart fails", async () => {
800+
it("rolls back only exact stopped accounts when a later account restart fails", async () => {
735801
const authAgentDir = "/tmp/openclaw-secrets-reload-concurrent-oauth";
736-
const buildReloadPlan = buildRestartChannelsPlan("slack", "zalo");
802+
const buildReloadPlan = () =>
803+
createReloadPlan({
804+
restartChannelAccounts: new Map([
805+
["slack", new Set(["ops"])],
806+
["zalo", new Set(["alerts"])],
807+
]),
808+
});
737809
activateSnapshot(slackZaloConfig("old-slack-secret", "old-zalo-secret"));
738810
const activateRuntimeSecrets = mockResolvedSecrets(
739811
slackZaloConfig("new-slack-secret", "new-zalo-secret"),
@@ -779,21 +851,30 @@ describe("gateway aux handlers", () => {
779851

780852
await reload();
781853

782-
expect(stopChannel.mock.calls).toEqual([["slack"], ["zalo"], ["slack"]]);
783-
expect(startChannel.mock.calls).toEqual([["slack"], ["zalo"], ["slack"], ["zalo"]]);
854+
expect(stopChannel.mock.calls).toEqual([
855+
["slack", "ops", { manual: false }],
856+
["zalo", "alerts", { manual: false }],
857+
["slack", "ops", { manual: false }],
858+
]);
859+
expect(startChannel.mock.calls).toEqual([
860+
["slack", "ops", { preserveManualStop: true }],
861+
["zalo", "alerts", { preserveManualStop: true }],
862+
["slack", "ops", { preserveManualStop: true }],
863+
["zalo", "alerts", { preserveManualStop: true }],
864+
]);
784865
expect(
785866
logChannelsInfo.mock.calls.some(([msg]) =>
786-
String(msg).startsWith("failed to restart zalo channel after secrets reload"),
867+
String(msg).startsWith("failed to restart zalo account alerts after secrets reload"),
787868
),
788869
).toBe(true);
789870
expect(
790871
logChannelsInfo.mock.calls.some(([msg]) =>
791-
String(msg).startsWith("rolling back slack channel after secrets reload failure"),
872+
String(msg).startsWith("rolling back slack account ops after secrets reload failure"),
792873
),
793874
).toBe(true);
794875
expect(
795876
logChannelsInfo.mock.calls.some(([msg]) =>
796-
String(msg).startsWith("rolling back zalo channel after secrets reload failure"),
877+
String(msg).startsWith("rolling back zalo account alerts after secrets reload failure"),
797878
),
798879
).toBe(true);
799880
// The handler surfaces the partial-failure so the caller can retry/alert
@@ -815,19 +896,13 @@ describe("gateway aux handlers", () => {
815896
).toMatchObject({ access: "access-new", refresh: "refresh-new" });
816897
});
817898

818-
it("does not roll back over a snapshot published after secrets.reload activation", async () => {
819-
const buildReloadPlan = buildRestartChannelsPlan("slack");
899+
it("fences account-scoped rollback when a newer snapshot and generation supersede reload", async () => {
900+
const buildReloadPlan = () =>
901+
createReloadPlan({ restartChannelAccounts: new Map([["slack", new Set(["ops"])]]) });
820902
activateSnapshot(slackConfig("old-slack-secret"));
821903
const prepared = createSnapshot(slackConfig("reload-secret"));
822904
const concurrent = createSnapshot(slackConfig("concurrent-secret"));
823-
const activateRuntimeSecrets = vi.fn(
824-
async (
825-
_config: OpenClawConfig,
826-
_activationParams: Parameters<GatewayAuxHandlerParams["activateRuntimeSecrets"]>[1],
827-
) => {
828-
return prepared;
829-
},
830-
);
905+
const activateRuntimeSecrets = vi.fn(async () => prepared);
831906
const sharedGatewaySessionGenerationState = {
832907
current: "gen-old" as string | undefined,
833908
required: "gen-old" as string | undefined | null,
@@ -841,19 +916,24 @@ describe("gateway aux handlers", () => {
841916
})
842917
.mockResolvedValue(undefined);
843918

919+
const stopChannel = vi.fn().mockResolvedValue(undefined);
844920
const { reload, respond } = createSecretsReloadHarness({
845921
activateRuntimeSecrets,
846922
buildReloadPlan,
847923
sharedGatewaySessionGenerationState,
848924
resolveSharedGatewaySessionGenerationForConfig: () => "gen-reload",
849925
startChannel,
850-
stopChannel: vi.fn().mockResolvedValue(undefined),
926+
stopChannel,
851927
});
852928

853929
await reload();
854930

855931
expect(firstRespondCall(respond)[0]).toBe(false);
856-
expect(startChannel).toHaveBeenCalledTimes(2);
932+
expect(stopChannel.mock.calls).toEqual([["slack", "ops", { manual: false }]]);
933+
expect(startChannel.mock.calls).toEqual([
934+
["slack", "ops", { preserveManualStop: true }],
935+
["slack", "ops", { preserveManualStop: true }],
936+
]);
857937
expect(getActiveSecretsRuntimeSnapshot()?.config).toEqual(slackConfig("concurrent-secret"));
858938
expect(sharedGatewaySessionGenerationState).toEqual({
859939
current: "gen-concurrent",

0 commit comments

Comments
 (0)