Skip to content

Commit 680001b

Browse files
authored
fix(gateway): fix plugin metadata lifecycle staleness in auth-bypass cache and config reload (#127664)
The gateway HTTP auth-bypass path cache was keyed only by config object identity, so replacing a channel plugin's declared bypass contract while config identity stayed stable preserved obsolete unauthenticated HTTP routes. It now clears on plugin metadata lifecycle resets alongside every other plugin-derived process memo. notifyPluginMetadataChanged cleared the process plugin metadata snapshot slot, but when config bytes were unchanged the config-reload diff took its early no-op return and skipped both plugin reload and republishing, leaving the snapshot slot empty so configless readers cold-scanned repeatedly. An unchanged-bytes metadata signal now forces a plugin-reload plan so the runtime generation republishes.
1 parent 6d47044 commit 680001b

4 files changed

Lines changed: 184 additions & 9 deletions

File tree

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4507,6 +4507,54 @@ describe("startGatewayConfigReloader", () => {
45074507
await harness.reloader.stop();
45084508
});
45094509

4510+
it("forces a plugin reload when signaled metadata leaves config and install records identical", async () => {
4511+
const activeConfig: OpenClawConfig = {
4512+
gateway: { reload: {} },
4513+
};
4514+
const installRecords = {
4515+
brave: {
4516+
source: "npm",
4517+
spec: "@openclaw/brave",
4518+
installPath: "/tmp/openclaw/plugins/brave",
4519+
},
4520+
} satisfies Record<string, PluginInstallRecord>;
4521+
const readSnapshot = vi.fn(async () =>
4522+
makeSnapshot({
4523+
sourceConfig: activeConfig,
4524+
runtimeConfig: activeConfig,
4525+
config: activeConfig,
4526+
hash: "unchanged-config",
4527+
}),
4528+
);
4529+
const readPluginInstallRecords = vi.fn(async () => ({ ...installRecords }));
4530+
const harness = createReloaderHarness(readSnapshot, {
4531+
initialConfig: activeConfig,
4532+
initialCompareConfig: activeConfig,
4533+
initialPluginInstallRecords: installRecords,
4534+
readPluginInstallRecords,
4535+
});
4536+
4537+
harness.reloader.notifyPluginMetadataChanged();
4538+
await vi.runOnlyPendingTimersAsync();
4539+
4540+
expect(harness.onRestart).not.toHaveBeenCalled();
4541+
const [plan, nextConfig] = getOnlyHotReloadCall(harness);
4542+
expect(plan.changedPaths).toEqual([]);
4543+
expect(plan.restartGateway).toBe(false);
4544+
expect(plan.reloadPlugins).toBe(true);
4545+
expect(plan.disposeMcpRuntimes).toBe(true);
4546+
expect(nextConfig).toBe(activeConfig);
4547+
4548+
// The refresh is consumed by the committed reload: a later watcher echo of
4549+
// identical bytes must not replace the plugin runtime generation again.
4550+
harness.watcher.emit("change");
4551+
await vi.runOnlyPendingTimersAsync();
4552+
expect(harness.onHotReload).toHaveBeenCalledTimes(1);
4553+
expect(harness.onRestart).not.toHaveBeenCalled();
4554+
4555+
await harness.reloader.stop();
4556+
});
4557+
45104558
it("keeps external plugin policy-only writes on the hot reload path", async () => {
45114559
const previousConfig: OpenClawConfig = {
45124560
gateway: { reload: {} },

‎src/gateway/config-reload.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,11 @@ export function startGatewayConfigReloader(opts: {
265265
const activeReloads = new Set<Promise<void>>();
266266
let missingConfigRetries = 0;
267267
let configWriteEpoch = 0;
268+
// Signaled metadata changes clear the process snapshot slot before the diff
269+
// pass runs; the counters keep that pass honest when config bytes are
270+
// unchanged, and stay pending until a plugin reload or restart commits.
271+
let pluginMetadataRefreshRequests = 0;
272+
let pluginMetadataRefreshApplied = 0;
268273
let pendingInProcessConfig: InProcessConfigCandidate | null = null;
269274
let activeInProcessConfig: InProcessConfigCandidate | null = null;
270275
let watcherIntentCandidate: InProcessConfigCandidate | null = null;
@@ -644,7 +649,16 @@ export function startGatewayConfigReloader(opts: {
644649
}
645650
notifyCommitted();
646651
};
647-
if (changedPaths.length === 0) {
652+
// A signaled metadata change emptied the process snapshot slot. An
653+
// unchanged config diff must still replace the plugin runtime generation so
654+
// the slot republishes instead of leaving configless readers cold-scanning
655+
// against a registry that diverged from the live runtime owners.
656+
const pluginMetadataRefreshToken = pluginMetadataRefreshRequests;
657+
const forcePluginMetadataReload = pluginMetadataRefreshToken !== pluginMetadataRefreshApplied;
658+
const markPluginMetadataRefreshApplied = () => {
659+
pluginMetadataRefreshApplied = pluginMetadataRefreshToken;
660+
};
661+
if (changedPaths.length === 0 && !forcePluginMetadataReload) {
648662
let publishedSource: { rollback: () => Promise<void>; commit?: () => void } | undefined;
649663
let publishedSourceRollback: (() => Promise<void>) | undefined;
650664
let publishedSourceRolledBack = false;
@@ -681,7 +695,11 @@ export function startGatewayConfigReloader(opts: {
681695
}
682696

683697
const followUp = resolveConfigWriteFollowUp(afterWrite);
684-
opts.log.info(`config change detected; evaluating reload (${changedPaths.join(", ")})`);
698+
opts.log.info(
699+
changedPaths.length > 0
700+
? `config change detected; evaluating reload (${changedPaths.join(", ")})`
701+
: "plugin metadata changed with identical config; replacing plugin runtime generation",
702+
);
685703
if (followUp.mode === "none") {
686704
opts.log.info(`config reload skipped by writer intent (${followUp.reason})`);
687705
await commitReloadBaseline({ runtimeApplied: false });
@@ -692,6 +710,12 @@ export function startGatewayConfigReloader(opts: {
692710
forceChangedPaths: pluginInstallWholeRecordPaths,
693711
candidateConfig: nextConfig,
694712
});
713+
if (forcePluginMetadataReload && !plan.restartGateway && !plan.reloadPlugins) {
714+
// Mirror the `plugins.*` hot rule pairing: a replaced plugin registry
715+
// also invalidates MCP runtimes assembled from the previous generation.
716+
plan.reloadPlugins = true;
717+
plan.disposeMcpRuntimes = true;
718+
}
695719
if (nextSettings.mode === "off") {
696720
opts.log.info("config reload disabled (gateway.reload.mode=off)");
697721
await commitReloadBaseline({ runtimeApplied: false });
@@ -716,12 +740,15 @@ export function startGatewayConfigReloader(opts: {
716740
await opts.onConfigChange?.(restartPlan, nextConfig);
717741
await prepareRestart(restartPlan, nextConfig, ownership, nextSourceConfig);
718742
await commitReloadBaseline();
743+
// The accepted restart owns snapshot republication at next startup.
744+
markPluginMetadataRefreshApplied();
719745
return;
720746
}
721747
if (plan.restartGateway) {
722748
await opts.onConfigChange?.(plan, nextConfig);
723749
await prepareRestart(plan, nextConfig, ownership, nextSourceConfig);
724750
await commitReloadBaseline();
751+
markPluginMetadataRefreshApplied();
725752
return;
726753
}
727754

@@ -735,6 +762,10 @@ export function startGatewayConfigReloader(opts: {
735762
assertCurrent();
736763
await appliedRevision.apply(plan, nextConfig, nextConfigRevisionHash);
737764
await commitReloadBaseline();
765+
if (plan.reloadPlugins) {
766+
// The committed reload republished the metadata snapshot generation.
767+
markPluginMetadataRefreshApplied();
768+
}
738769
};
739770

740771
const promoteAcceptedSnapshot = async (snapshot: ConfigFileSnapshot, reason: string) => {
@@ -1271,6 +1302,7 @@ export function startGatewayConfigReloader(opts: {
12711302
notifyPluginMetadataChanged: () => {
12721303
// The signal carries a metadata change while config bytes stay identical.
12731304
// Clear both metadata and config-echo caches before scheduling the shared diff path.
1305+
pluginMetadataRefreshRequests += 1;
12741306
clearLoadInstalledPluginIndexInstallRecordsCache();
12751307
clearPluginMetadataLifecycleCaches();
12761308
startupInternalWriteHash = null;
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Covers plugin gateway auth bypass caching across metadata lifecycle resets.
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { OpenClawConfig } from "../config/types.openclaw.js";
4+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
5+
import { getCachedPluginGatewayAuthBypassPaths } from "./server-http-plugin-auth.js";
6+
7+
const resolveBypassPaths = vi.hoisted(() =>
8+
vi.fn<(params: { channelId: string; cfg: OpenClawConfig }) => Promise<string[]>>(),
9+
);
10+
11+
vi.mock("../channels/plugins/gateway-auth-bypass.js", () => ({
12+
resolveBundledChannelGatewayAuthBypassPaths: resolveBypassPaths,
13+
}));
14+
15+
describe("getCachedPluginGatewayAuthBypassPaths", () => {
16+
beforeEach(() => {
17+
resolveBypassPaths.mockReset();
18+
clearPluginMetadataLifecycleCaches();
19+
});
20+
21+
it("caches resolved bypass paths per config identity", async () => {
22+
const config: OpenClawConfig = { channels: { telegram: {} } };
23+
resolveBypassPaths.mockResolvedValue(["/telegram/webhook"]);
24+
25+
await expect(getCachedPluginGatewayAuthBypassPaths(config)).resolves.toEqual(
26+
new Set(["/telegram/webhook"]),
27+
);
28+
await getCachedPluginGatewayAuthBypassPaths(config);
29+
expect(resolveBypassPaths).toHaveBeenCalledTimes(1);
30+
});
31+
32+
it("drops cached bypass paths on a metadata lifecycle reset despite stable config identity", async () => {
33+
const config: OpenClawConfig = { channels: { telegram: {} } };
34+
resolveBypassPaths.mockResolvedValueOnce(["/telegram/old-bypass"]);
35+
await expect(getCachedPluginGatewayAuthBypassPaths(config)).resolves.toEqual(
36+
new Set(["/telegram/old-bypass"]),
37+
);
38+
39+
// Same config object, replaced plugin contract: the reset must invalidate,
40+
// or the predecessor's unauthenticated paths keep bypassing gateway auth.
41+
clearPluginMetadataLifecycleCaches();
42+
resolveBypassPaths.mockResolvedValueOnce(["/telegram/new-bypass"]);
43+
44+
await expect(getCachedPluginGatewayAuthBypassPaths(config)).resolves.toEqual(
45+
new Set(["/telegram/new-bypass"]),
46+
);
47+
});
48+
49+
it("retries after a failed resolution instead of caching the rejection", async () => {
50+
const config: OpenClawConfig = { channels: { telegram: {} } };
51+
resolveBypassPaths.mockRejectedValueOnce(new Error("resolution failed"));
52+
await expect(getCachedPluginGatewayAuthBypassPaths(config)).rejects.toThrow(
53+
"resolution failed",
54+
);
55+
56+
resolveBypassPaths.mockResolvedValueOnce(["/telegram/webhook"]);
57+
await expect(getCachedPluginGatewayAuthBypassPaths(config)).resolves.toEqual(
58+
new Set(["/telegram/webhook"]),
59+
);
60+
});
61+
62+
it("keeps the fresh generation cached when a stale failed resolution settles late", async () => {
63+
const config: OpenClawConfig = { channels: { telegram: {} } };
64+
let rejectStale: (error: Error) => void = () => {};
65+
resolveBypassPaths.mockReturnValueOnce(
66+
new Promise<string[]>((_resolve, reject) => {
67+
rejectStale = reject;
68+
}),
69+
);
70+
const stale = getCachedPluginGatewayAuthBypassPaths(config);
71+
72+
clearPluginMetadataLifecycleCaches();
73+
resolveBypassPaths.mockResolvedValue(["/telegram/webhook"]);
74+
await expect(getCachedPluginGatewayAuthBypassPaths(config)).resolves.toEqual(
75+
new Set(["/telegram/webhook"]),
76+
);
77+
78+
rejectStale(new Error("stale plugin generation failed"));
79+
await expect(stale).rejects.toThrow("stale plugin generation failed");
80+
81+
// The stale rejection evicts from its own generation only; the fresh entry
82+
// must stay cached instead of being re-resolved.
83+
await getCachedPluginGatewayAuthBypassPaths(config);
84+
expect(resolveBypassPaths).toHaveBeenCalledTimes(2);
85+
});
86+
});

‎src/gateway/server-http-plugin-auth.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { resolveBundledChannelGatewayAuthBypassPaths } from "../channels/plugins/gateway-auth-bypass.js";
22
import type { OpenClawConfig } from "../config/types.openclaw.js";
3+
import { registerPluginMetadataProcessMemoLifecycleClear } from "../plugins/plugin-metadata-lifecycle.js";
34
import type { AuthorizedGatewayHttpRequest } from "./http-auth-utils.js";
45
import type { PluginNodeCapabilitySurface } from "./plugin-node-capability.js";
56
import {
@@ -18,10 +19,15 @@ export type ResolvePluginNodeCapabilityRoute = (
1819
pathContext: PluginRoutePathContext,
1920
) => PluginNodeCapabilitySurface | undefined;
2021

21-
const pluginGatewayAuthBypassPathsCache = new WeakMap<
22-
OpenClawConfig,
23-
Promise<ReadonlySet<string>>
24-
>();
22+
// Bypass paths come from plugin-declared artifacts, not config bytes alone. A
23+
// metadata lifecycle reset can replace that contract while the config object
24+
// identity stays stable, so the cache must roll to a fresh generation on reset
25+
// or a replaced channel plugin keeps its predecessor's HTTP auth exceptions.
26+
let pluginGatewayAuthBypassPathsCache = new WeakMap<OpenClawConfig, Promise<ReadonlySet<string>>>();
27+
28+
registerPluginMetadataProcessMemoLifecycleClear(() => {
29+
pluginGatewayAuthBypassPathsCache = new WeakMap();
30+
});
2531

2632
async function resolvePluginGatewayAuthBypassPaths(
2733
configSnapshot: OpenClawConfig,
@@ -45,15 +51,18 @@ async function resolvePluginGatewayAuthBypassPaths(
4551
export function getCachedPluginGatewayAuthBypassPaths(
4652
configSnapshot: OpenClawConfig,
4753
): Promise<ReadonlySet<string>> {
48-
const cached = pluginGatewayAuthBypassPathsCache.get(configSnapshot);
54+
const cache = pluginGatewayAuthBypassPathsCache;
55+
const cached = cache.get(configSnapshot);
4956
if (cached) {
5057
return cached;
5158
}
5259
const resolved = resolvePluginGatewayAuthBypassPaths(configSnapshot).catch((error: unknown) => {
53-
pluginGatewayAuthBypassPathsCache.delete(configSnapshot);
60+
// Evict from the owning generation only; a stale failure settling after a
61+
// lifecycle reset must not drop a freshly cached entry.
62+
cache.delete(configSnapshot);
5463
throw error;
5564
});
56-
pluginGatewayAuthBypassPathsCache.set(configSnapshot, resolved);
65+
cache.set(configSnapshot, resolved);
5766
return resolved;
5867
}
5968

0 commit comments

Comments
 (0)