Skip to content

Commit 21a7676

Browse files
authored
fix(plugins): unify HTTP route conflict handling (#118203)
* fix(plugins): unify HTTP route conflict handling * fix(plugins): preserve source-less route replacement * test(line): type webhook route source
1 parent f7fbe9a commit 21a7676

29 files changed

Lines changed: 1078 additions & 239 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ a94c9ff59cc361b04f8731a47d722c4bc88cfabf942221369a8cb67bdcda7249 module/tool-pl
143143
89846974257b7551d46a514902998d0592fc67b1d8ce036c6514d7b9cd1bc159 module/tool-results
144144
9d6ab352913a573b226e054e1dc8c6d088493aea9954950c65585923b5b6895a module/tool-send
145145
541df9dea799f25e83ea483d481ecebc5b91c016effab593c54d3efe3ee6517b module/web-media
146-
2d9a53e49d9092804945248efa6d03ce0099cfa7a1c9d7836782754b5e99ebb3 module/webhook-ingress
146+
0d5ae2f16bb33c0fe4f85eea3da80283e89e2995a7406b98d24805feeee4f7ca module/webhook-ingress
147147
af8c5e1c84ec9d365a7aa0d15eb63f0dd9e7b50526023e6212bba020c229f224 module/webhook-request-guards
148148
1cc469eacda2818a116ab7b63847b9ddf86225e8d02e62fac48e618ba41a9852 module/widget-html
149149
9161b36ec0ab062ea41b363c894fcd672a7727f21cb726739f99f9c184fce69d module/zod

‎docs/plugins/architecture-internals.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -652,15 +652,18 @@ Route fields:
652652
- `auth`: required, `"gateway"` or `"plugin"`. Use `"gateway"` to require normal gateway auth, or `"plugin"` for plugin-managed auth/webhook verification.
653653
- `match`: optional. `"exact"` (default) or `"prefix"`.
654654
- `handleUpgrade`: optional handler for WebSocket upgrade requests on the same route.
655-
- `replaceExisting`: optional. Allows the same plugin to replace its own existing route registration.
655+
- `replaceExisting`: optional. Required only for dynamic lifecycle registration to replace its own existing route.
656656
- `handler`: return `true` when the route handled the request.
657657

658658
Notes:
659659

660660
- `api.registerHttpHandler(...)` was removed and will cause a plugin-load error. Use `api.registerHttpRoute(...)` instead.
661661
- Plugin routes must declare `auth` explicitly.
662-
- Exact `path + match` conflicts are rejected unless `replaceExisting: true`, and one plugin cannot replace another plugin's route.
662+
- Canonically equivalent paths with the same `match` mode occupy one route. Static `api.registerHttpRoute(...)` calls from the same plugin replace that route; another plugin cannot replace it.
663663
- Overlapping routes with different `auth` levels are rejected. Keep `exact`/`prefix` fallthrough chains on the same auth level only.
664+
- Dynamic lifecycle code using `registerPluginHttpRoute(...)` from `openclaw/plugin-sdk/webhook-ingress` must set `replaceExisting: true` to refresh its own canonical route. Named registrations can replace only the same nonempty `pluginId`; when either side sets a route `source`, both must set the same nonempty source. Same-plugin source-less-to-source-less refresh and anonymous-to-anonymous refresh remain supported for shipped SDK callers, but named and anonymous routes cannot replace each other.
665+
- Treat route `source` as a stable same-plugin sub-owner, not a diagnostic label. Existing source-less callers may keep omitting it; source-aware callers must keep it unchanged across refreshes.
666+
- Dynamic lifecycle registration logs and returns a no-op unregister callback on rejection by default. Set `throwOnFailure: true` when readiness depends on that route; required bundled webhook transports use strict registration so they cannot report ready without live ingress.
664667
- `auth: "plugin"` routes do **not** receive operator runtime scopes automatically. They are for plugin-managed webhooks/signature verification, not privileged Gateway helper calls.
665668
- `auth: "gateway"` routes run inside a Gateway request runtime scope. The default surface (`gatewayRuntimeScopeSurface: "write-default"`) is intentionally conservative:
666669
- shared-secret bearer auth (`gateway.auth.mode = "token"` / `"password"`) and any non-trusted-proxy auth method get a single `operator.write` scope, even if the caller sends `x-openclaw-scopes`

‎extensions/googlechat/src/monitor-routing.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export function registerGoogleChatWebhookTarget(target: WebhookTarget): () => vo
4646
source: "googlechat-webhook",
4747
accountId: target.account.accountId,
4848
log: target.runtime.log,
49+
throwOnFailure: true,
4950
handler: async (req, res) => {
5051
const handled = await handleGoogleChatWebhookRequest(req, res);
5152
if (!handled && !res.headersSent) {

‎extensions/googlechat/src/monitor-webhook.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ vi.mock("openclaw/plugin-sdk/webhook-request-guards", () => ({
1818
}));
1919

2020
vi.mock("openclaw/plugin-sdk/webhook-targets", () => ({
21+
canonicalizeWebhookRouteKey: (raw: string) =>
22+
raw
23+
.replace(/\/{2,}/g, "/")
24+
.replace(/\/+$/, "")
25+
.toLowerCase(),
2126
normalizeWebhookPath: (raw: string) => raw,
2227
resolveWebhookTargetWithAuthOrReject,
2328
withResolvedWebhookRequestPipeline,
@@ -169,7 +174,7 @@ describe("googlechat monitor webhook", () => {
169174
processEvent,
170175
});
171176
const req = createRequest({
172-
url: "/googlechat?ignored=1",
177+
url: "/GoogleChat//?ignored=1",
173178
headers: {
174179
"x-forwarded-for": "198.51.100.7, 10.0.0.1",
175180
},

‎extensions/googlechat/src/monitor-webhook.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
33
import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
44
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
55
import {
6-
normalizeWebhookPath,
6+
canonicalizeWebhookRouteKey,
77
resolveRequestClientIp,
88
type FixedWindowRateLimiter,
99
} from "openclaw/plugin-sdk/webhook-ingress";
@@ -154,7 +154,7 @@ export function createGoogleChatWebhookRequestHandler(params: {
154154
processEvent: (event: GoogleChatEvent, target: WebhookTarget) => Promise<void>;
155155
}): (req: IncomingMessage, res: ServerResponse) => Promise<boolean> {
156156
return async (req: IncomingMessage, res: ServerResponse): Promise<boolean> => {
157-
const path = normalizeWebhookPath(new URL(req.url ?? "/", "http://localhost").pathname);
157+
const path = canonicalizeWebhookRouteKey(new URL(req.url ?? "/", "http://localhost").pathname);
158158
// Shared-path registrations use the same gateway proxy settings in normal runtime setup.
159159
const config = params.webhookTargets.get(path)?.[0]?.config;
160160
const clientIp =

‎extensions/googlechat/src/monitor.lifecycle.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,26 @@ describe("Google Chat monitor lifecycle", () => {
5555
});
5656
await stop();
5757
});
58+
59+
it("stops ingress and rejects startup when the webhook route cannot bind", async () => {
60+
const statusSink = vi.fn();
61+
mocks.registerTarget.mockImplementationOnce(() => {
62+
throw new Error("Google Chat route conflict");
63+
});
64+
65+
await expect(
66+
startGoogleChatMonitor({
67+
account: { accountId: "default", enabled: true, credentialSource: "config", config: {} },
68+
config: {},
69+
runtime: {},
70+
abortSignal: new AbortController().signal,
71+
webhookPath: "/googlechat",
72+
statusSink,
73+
} as never),
74+
).rejects.toThrow("Google Chat route conflict");
75+
76+
expect(mocks.ingressStart).toHaveBeenCalledOnce();
77+
expect(mocks.ingressStop).toHaveBeenCalledOnce();
78+
expect(statusSink).not.toHaveBeenCalledWith(expect.objectContaining({ lifecycle: "ready" }));
79+
});
5880
});

‎extensions/googlechat/src/monitor.webhook-routing.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,35 @@ describe("Google Chat webhook routing", () => {
174174
vi.resetModules();
175175
});
176176

177+
it("rejects a foreign route collision instead of storing an unreachable target", () => {
178+
const registry = createEmptyPluginRegistry();
179+
const existingRoute = {
180+
path: "/googlechat",
181+
match: "exact" as const,
182+
auth: "plugin" as const,
183+
handler: () => {},
184+
pluginId: "other-plugin",
185+
source: "other-webhook",
186+
};
187+
registry.httpRoutes.push(existingRoute);
188+
setActivePluginRegistry(registry);
189+
190+
expect(() =>
191+
registerGoogleChatWebhookTarget({
192+
account: baseAccount("A"),
193+
config: {},
194+
runtime: { log: vi.fn() },
195+
core: {} as PluginRuntime,
196+
path: "/googlechat",
197+
statusSink: vi.fn(),
198+
mediaMaxMb: 5,
199+
ingress: { receive: vi.fn(async () => ({ kind: "ignored" as const })) },
200+
}),
201+
).toThrow("route replacement denied");
202+
203+
expect(registry.httpRoutes).toEqual([existingRoute]);
204+
});
205+
177206
it("rejects ambiguous routing when multiple targets on the same path verify successfully", async () => {
178207
vi.mocked(verifyGoogleChatRequest).mockResolvedValue({ ok: true });
179208

‎extensions/line/src/monitor.lifecycle.test.ts‎

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ type RegisteredRoute = {
4141
path?: string;
4242
pluginId?: string;
4343
replaceExisting?: boolean;
44+
source?: string;
45+
throwOnFailure?: boolean;
4446
};
4547

4648
type RegisteredTarget = {
@@ -88,7 +90,6 @@ vi.mock("openclaw/plugin-sdk/runtime-env", async () => {
8890
...actual,
8991
danger: (value: unknown) => String(value),
9092
logVerbose: vi.fn(),
91-
waitForAbortSignal: vi.fn(),
9293
};
9394
});
9495

@@ -184,9 +185,10 @@ describe("monitorLineProvider lifecycle", () => {
184185
? params.target.path
185186
: `/${params.target.path}`;
186187
const key =
187-
withLeadingSlash.length > 1 && withLeadingSlash.endsWith("/")
188-
? withLeadingSlash.slice(0, -1)
189-
: withLeadingSlash;
188+
withLeadingSlash
189+
.replace(/\/{2,}/g, "/")
190+
.replace(/\/+$/, "")
191+
.toLowerCase() || "/";
190192
const normalizedTarget = { ...params.target, path: key };
191193
const existing = params.targetsByPath.get(key) ?? [];
192194
params.targetsByPath.set(key, [...existing, normalizedTarget]);
@@ -238,8 +240,10 @@ describe("monitorLineProvider lifecycle", () => {
238240

239241
expect(registerWebhookTargetWithPluginRouteMock).toHaveBeenCalledTimes(1);
240242
expect(requireWebhookRegistration().route.auth).toBe("plugin");
241-
expect(statusSink).toHaveBeenCalledWith(
242-
expect.objectContaining({ lifecycle: "ready", connected: true }),
243+
await vi.waitFor(() =>
244+
expect(statusSink).toHaveBeenCalledWith(
245+
expect.objectContaining({ lifecycle: "ready", connected: true }),
246+
),
243247
);
244248
expect(resolved).toBe(false);
245249

@@ -266,6 +270,8 @@ describe("monitorLineProvider lifecycle", () => {
266270
expect(registration.route.accountId).toBe("work");
267271
expect(registration.route.auth).toBe("plugin");
268272
expect(registration.route.pluginId).toBe("line");
273+
expect(registration.route.source).toBe("line-webhook");
274+
expect(registration.route.throwOnFailure).toBe(true);
269275
expect(registration.route).not.toHaveProperty("path");
270276
expect(registration.route).not.toHaveProperty("replaceExisting");
271277
await monitor.stop();
@@ -344,6 +350,29 @@ describe("monitorLineProvider lifecycle", () => {
344350
expect(registerWebhookTargetWithPluginRouteMock).not.toHaveBeenCalled();
345351
});
346352

353+
it("stops the bot and rejects startup when the webhook route cannot bind", async () => {
354+
const statusSink = vi.fn();
355+
registerWebhookTargetWithPluginRouteMock.mockImplementationOnce(() => {
356+
throw new Error("LINE route conflict");
357+
});
358+
359+
await expect(
360+
monitorLineProvider({
361+
channelAccessToken: "token",
362+
channelSecret: "secret", // pragma: allowlist secret
363+
config: {} as OpenClawConfig,
364+
runtime: {} as RuntimeEnv,
365+
statusSink,
366+
}),
367+
).rejects.toThrow("LINE route conflict");
368+
369+
const bot = createLineBotMock.mock.results[0]?.value as
370+
| { stop: ReturnType<typeof vi.fn> }
371+
| undefined;
372+
expect(bot?.stop).toHaveBeenCalledOnce();
373+
expect(statusSink).not.toHaveBeenCalledWith(expect.objectContaining({ lifecycle: "ready" }));
374+
});
375+
347376
it("dispatches shared-path webhook posts to the account matching the signature", async () => {
348377
const firstMonitor = await monitorLineProvider({
349378
channelAccessToken: "first-token",
@@ -534,18 +563,18 @@ describe("monitorLineProvider lifecycle", () => {
534563
}
535564
});
536565

537-
it("dispatches a signed POST to a configured trailing-slash webhook path", async () => {
566+
it("dispatches a signed POST through the canonical configured webhook route", async () => {
538567
const monitor = await monitorLineProvider({
539568
channelAccessToken: "token",
540569
channelSecret: "secret", // pragma: allowlist secret
541-
webhookPath: "/line/webhook/",
570+
webhookPath: "/Line//Webhook/",
542571
accountId: "default",
543572
config: {} as OpenClawConfig,
544573
runtime: {} as RuntimeEnv,
545574
});
546575

547576
const registration = requireWebhookRegistration();
548-
expect(registration.target.path).toBe("/line/webhook");
577+
expect(registration.target.path).toBe("/Line//Webhook");
549578

550579
const route = requireRegisteredRoute();
551580
const payload = JSON.stringify({ events: [{ type: "message" }] });

‎extensions/line/src/monitor.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type RuntimeEnv,
1313
} from "openclaw/plugin-sdk/runtime-env";
1414
import {
15+
canonicalizeWebhookRouteKey,
1516
isRequestBodyLimitError,
1617
normalizePluginHttpPath,
1718
normalizeWebhookPath,
@@ -75,6 +76,18 @@ type LineWebhookTarget = {
7576
runtime: RuntimeEnv;
7677
};
7778

79+
async function registerLineWebhookTarget(
80+
params: Parameters<typeof registerWebhookTargetWithPluginRoute<LineWebhookTarget>>[0],
81+
bot: ReturnType<typeof createLineBot>,
82+
) {
83+
try {
84+
return registerWebhookTargetWithPluginRoute(params);
85+
} catch (error) {
86+
await Promise.allSettled([bot.stop()]);
87+
throw error;
88+
}
89+
}
90+
7891
const lineWebhookTargets = new Map<string, LineWebhookTarget[]>();
7992

8093
function startLineLoadingKeepalive(params: {
@@ -285,13 +298,16 @@ export async function monitorLineProvider(
285298
const normalizedPath = normalizeWebhookPath(
286299
normalizePluginHttpPath(webhookPath, "/line/webhook") ?? "/line/webhook",
287300
);
301+
const webhookRouteKey = canonicalizeWebhookRouteKey(normalizedPath);
288302
const createScopedLineWebhookHandler = (target: LineWebhookTarget) =>
289303
createLineNodeWebhookHandler({
290304
channelSecret: target.channelSecret,
291305
bot: target.bot,
292306
runtime: target.runtime,
293307
});
294-
const { unregister: unregisterHttp } = registerWebhookTargetWithPluginRoute({
308+
const registrationParams: Parameters<
309+
typeof registerWebhookTargetWithPluginRoute<LineWebhookTarget>
310+
>[0] = {
295311
targetsByPath: lineWebhookTargets,
296312
target: {
297313
accountId: resolvedAccountId,
@@ -303,10 +319,12 @@ export async function monitorLineProvider(
303319
route: {
304320
auth: "plugin",
305321
pluginId: "line",
322+
source: "line-webhook",
306323
accountId: resolvedAccountId,
307324
log: (msg) => logVerbose(msg),
325+
throwOnFailure: true,
308326
handler: async (req, res) => {
309-
const targets = lineWebhookTargets.get(normalizedPath) ?? [];
327+
const targets = lineWebhookTargets.get(webhookRouteKey) ?? [];
310328
const firstTarget = targets[0];
311329
if (req.method !== "POST") {
312330
if (!firstTarget) {
@@ -322,7 +340,7 @@ export async function monitorLineProvider(
322340
req,
323341
res,
324342
inFlightLimiter: lineWebhookInFlightLimiter,
325-
inFlightKey: `line:${normalizedPath}`,
343+
inFlightKey: `line:${webhookRouteKey}`,
326344
});
327345
if (!requestLifecycle.ok) {
328346
return;
@@ -409,7 +427,8 @@ export async function monitorLineProvider(
409427
}
410428
},
411429
},
412-
});
430+
};
431+
const { unregister: unregisterHttp } = await registerLineWebhookTarget(registrationParams, bot);
413432

414433
logVerbose(`line: registered webhook handler at ${normalizedPath}`);
415434
statusSink?.({

‎extensions/mattermost/src/mattermost/monitor-interactions.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export function registerMattermostInteractions(params: {
1919
interactionPath: string;
2020
allowedSourceIps: string[];
2121
handleModelPickerInteraction: MattermostModelPickerInteractionHandler;
22-
}): (() => void) | undefined {
22+
}): () => void {
2323
const { monitor } = params;
2424
const { account, botUserId, cfg, client, core, pairing, resources, runtime } = monitor;
2525
const { resolveChannelInfo } = resources;
@@ -167,5 +167,7 @@ export function registerMattermostInteractions(params: {
167167
source: "mattermost-interactions",
168168
accountId: account.accountId,
169169
log: (message: string) => runtime.log?.(message),
170+
replaceExisting: true,
171+
throwOnFailure: true,
170172
});
171173
}

0 commit comments

Comments
 (0)