Skip to content

Commit a47722d

Browse files
authored
Integrations: tighten inbound callback and allowlist checks (#46787)
* Integrations: harden inbound callback and allowlist handling * Integrations: address review follow-ups * Update CHANGELOG.md * Mattermost: avoid command-gating open button callbacks
1 parent 67b2d1b commit a47722d

14 files changed

Lines changed: 323 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,14 @@ Docs: https://docs.openclaw.ai
2929
- Zalo Personal/group gating: stop reapplying `dmPolicy.allowFrom` as a sender gate for already-allowlisted groups when `groupAllowFrom` is unset, so any member of an allowed group can trigger replies while DMs stay restricted. (#40146)
3030
- Browser/remote CDP: honor strict browser SSRF policy during remote CDP reachability and `/json/version` discovery checks, redact sensitive `cdpUrl` tokens from status output, and warn when remote CDP targets private/internal hosts.
3131
- Plugins/install precedence: keep bundled plugins ahead of auto-discovered globals by default, but let an explicitly installed plugin record win its own duplicate-id tie so installed channel plugins load from `~/.openclaw/extensions` after `openclaw plugins install`.
32+
- Inbound policy hardening: tighten callback and webhook sender checks across Mattermost and Google Chat, match Nextcloud Talk rooms by stable room token, and treat explicit empty Twitch allowlists as deny-all. Thanks @vincentkoc.
3233
- macOS/canvas actions: keep unattended local agent actions on trusted in-app canvas surfaces only, and stop exposing the deep-link fallback key to arbitrary page scripts. Thanks @vincentkoc.
3334
- Agents/compaction: extend the enclosing run deadline once while compaction is actively in flight, and abort the underlying SDK compaction on timeout/cancel so large-session compactions stop freezing mid-run. (#46889) Thanks @asyncjason.
3435
- Models/openai-completions: default non-native OpenAI-compatible providers to omit tool-definition `strict` fields unless users explicitly opt back in, so tool calling keeps working on providers that reject that option. (#45497) Thanks @sahancava.
3536
- WhatsApp/reconnect: restore the append recency filter in the extension inbox monitor and handle protobuf `Long` timestamps correctly, so fresh post-reconnect append messages are processed while stale history sync stays suppressed. (#42588) thanks @MonkeyLeeT.
3637
- WhatsApp/login: wait for pending creds writes before reopening after Baileys `515` pairing restarts in both QR login and `channels login` flows, and keep the restart coverage pinned to the real wrapped error shape plus per-account creds queues. (#27910) Thanks @asyncjason.
3738
- Agents/openai-compatible tool calls: deduplicate repeated tool call ids across live assistant messages and replayed history so OpenAI-compatible backends no longer reject duplicate `tool_call_id` values with HTTP 400. (#40996) Thanks @xaeon2026.
3839
- Security/device pairing: harden `device.token.rotate` deny handling by keeping public failures generic while logging internal deny reasons and preserving approved-baseline enforcement. (`GHSA-7jrw-x62h-64p8`)
39-
40-
### Fixes
41-
4240
- Slack/interactive replies: preserve `channelData.slack.blocks` through live DM delivery and preview-finalized edits so Block Kit button and select directives render instead of falling back to raw text. Thanks @vincentkoc.
4341
- Zalo/plugin runtime: export `resolveClientIp` from `openclaw/plugin-sdk/zalo` so installed builds no longer crash on startup when the webhook monitor loads from the packaged extension instead of the monorepo source tree. (#46549) Thanks @No898.
4442
- CI/channel test routing: move the built-in channel suites into `test:channels` and keep them out of `test:extensions`, so extension CI no longer fails after the channel migration while targeted test routing still sends Slack, Signal, and iMessage suites to the right lane. (#46066) Thanks @scoootscooob.
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+
const mocks = vi.hoisted(() => ({
4+
verifyIdToken: vi.fn(),
5+
}));
6+
7+
vi.mock("google-auth-library", () => ({
8+
GoogleAuth: class {},
9+
OAuth2Client: class {
10+
verifyIdToken = mocks.verifyIdToken;
11+
},
12+
}));
13+
14+
const { verifyGoogleChatRequest } = await import("./auth.js");
15+
16+
function mockTicket(payload: Record<string, unknown>) {
17+
mocks.verifyIdToken.mockResolvedValue({
18+
getPayload: () => payload,
19+
});
20+
}
21+
22+
describe("verifyGoogleChatRequest", () => {
23+
beforeEach(() => {
24+
mocks.verifyIdToken.mockReset();
25+
});
26+
27+
it("accepts Google Chat app-url tokens from the Chat issuer", async () => {
28+
mockTicket({
29+
30+
email_verified: true,
31+
});
32+
33+
await expect(
34+
verifyGoogleChatRequest({
35+
bearer: "token",
36+
audienceType: "app-url",
37+
audience: "https://example.com/googlechat",
38+
}),
39+
).resolves.toEqual({ ok: true });
40+
});
41+
42+
it("rejects add-on tokens when no principal binding is configured", async () => {
43+
mockTicket({
44+
45+
email_verified: true,
46+
sub: "principal-1",
47+
});
48+
49+
await expect(
50+
verifyGoogleChatRequest({
51+
bearer: "token",
52+
audienceType: "app-url",
53+
audience: "https://example.com/googlechat",
54+
}),
55+
).resolves.toEqual({
56+
ok: false,
57+
reason: "missing add-on principal binding",
58+
});
59+
});
60+
61+
it("accepts add-on tokens only when the bound principal matches", async () => {
62+
mockTicket({
63+
64+
email_verified: true,
65+
sub: "principal-1",
66+
});
67+
68+
await expect(
69+
verifyGoogleChatRequest({
70+
bearer: "token",
71+
audienceType: "app-url",
72+
audience: "https://example.com/googlechat",
73+
expectedAddOnPrincipal: "principal-1",
74+
}),
75+
).resolves.toEqual({ ok: true });
76+
});
77+
78+
it("rejects add-on tokens when the bound principal does not match", async () => {
79+
mockTicket({
80+
81+
email_verified: true,
82+
sub: "principal-2",
83+
});
84+
85+
await expect(
86+
verifyGoogleChatRequest({
87+
bearer: "token",
88+
audienceType: "app-url",
89+
audience: "https://example.com/googlechat",
90+
expectedAddOnPrincipal: "principal-1",
91+
}),
92+
).resolves.toEqual({
93+
ok: false,
94+
reason: "unexpected add-on principal: principal-2",
95+
});
96+
});
97+
});

‎extensions/googlechat/src/auth.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ export async function verifyGoogleChatRequest(params: {
9494
bearer?: string | null;
9595
audienceType?: GoogleChatAudienceType | null;
9696
audience?: string | null;
97+
expectedAddOnPrincipal?: string | null;
9798
}): Promise<{ ok: boolean; reason?: string }> {
9899
const bearer = params.bearer?.trim();
99100
if (!bearer) {
@@ -112,10 +113,32 @@ export async function verifyGoogleChatRequest(params: {
112113
audience,
113114
});
114115
const payload = ticket.getPayload();
115-
const email = payload?.email ?? "";
116-
const ok =
117-
payload?.email_verified && (email === CHAT_ISSUER || ADDON_ISSUER_PATTERN.test(email));
118-
return ok ? { ok: true } : { ok: false, reason: `invalid issuer: ${email}` };
116+
const email = String(payload?.email ?? "")
117+
.trim()
118+
.toLowerCase();
119+
if (!payload?.email_verified) {
120+
return { ok: false, reason: "email not verified" };
121+
}
122+
if (email === CHAT_ISSUER) {
123+
return { ok: true };
124+
}
125+
if (!ADDON_ISSUER_PATTERN.test(email)) {
126+
return { ok: false, reason: `invalid issuer: ${email}` };
127+
}
128+
const expectedAddOnPrincipal = params.expectedAddOnPrincipal?.trim().toLowerCase();
129+
if (!expectedAddOnPrincipal) {
130+
return { ok: false, reason: "missing add-on principal binding" };
131+
}
132+
const tokenPrincipal = String(payload?.sub ?? "")
133+
.trim()
134+
.toLowerCase();
135+
if (!tokenPrincipal || tokenPrincipal !== expectedAddOnPrincipal) {
136+
return {
137+
ok: false,
138+
reason: `unexpected add-on principal: ${tokenPrincipal || "<missing>"}`,
139+
};
140+
}
141+
return { ok: true };
119142
} catch (err) {
120143
return { ok: false, reason: err instanceof Error ? err.message : "invalid token" };
121144
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ export function createGoogleChatWebhookRequestHandler(params: {
132132
bearer: headerBearer,
133133
audienceType: target.audienceType,
134134
audience: target.audience,
135+
expectedAddOnPrincipal: target.account.config.appPrincipal,
135136
});
136137
return verification.ok;
137138
},
@@ -166,6 +167,7 @@ export function createGoogleChatWebhookRequestHandler(params: {
166167
bearer: parsed.addOnBearerToken,
167168
audienceType: target.audienceType,
168169
audience: target.audience,
170+
expectedAddOnPrincipal: target.account.config.appPrincipal,
169171
});
170172
return verification.ok;
171173
},

‎extensions/mattermost/src/mattermost/interactions.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,37 @@ describe("createMattermostInteractionHandler", () => {
738738
expectSuccessfulApprovalUpdate(res, requestLog);
739739
});
740740

741+
it("blocks button dispatch when the sender is not allowed for the action", async () => {
742+
const { context, token } = createActionContext();
743+
const dispatchButtonClick = vi.fn();
744+
const handleInteraction = vi.fn();
745+
const handler = createMattermostInteractionHandler({
746+
client: {
747+
request: async (_path: string, init?: { method?: string }) =>
748+
init?.method === "PUT" ? { id: "post-1" } : createActionPost(),
749+
} as unknown as MattermostClient,
750+
botUserId: "bot",
751+
accountId: "acct",
752+
authorizeButtonClick: async () => ({
753+
ok: false,
754+
response: {
755+
ephemeral_text: "blocked",
756+
},
757+
}),
758+
handleInteraction,
759+
dispatchButtonClick,
760+
});
761+
762+
const res = await runHandler(handler, {
763+
body: createInteractionBody({ context, token }),
764+
});
765+
766+
expect(res.statusCode).toBe(200);
767+
expect(res.body).toContain("blocked");
768+
expect(handleInteraction).not.toHaveBeenCalled();
769+
expect(dispatchButtonClick).not.toHaveBeenCalled();
770+
});
771+
741772
it("forwards fetched post threading metadata to session and button callbacks", async () => {
742773
const enqueueSystemEvent = vi.fn();
743774
setMattermostRuntime({

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ export type MattermostInteractionResponse = {
3737
ephemeral_text?: string;
3838
};
3939

40+
export type MattermostInteractionAuthorizationResult =
41+
| { ok: true }
42+
| { ok: false; statusCode?: number; response?: MattermostInteractionResponse };
43+
4044
export type MattermostInteractiveButtonInput = {
4145
id?: string;
4246
callback_data?: string;
@@ -404,6 +408,10 @@ export function createMattermostInteractionHandler(params: {
404408
context: Record<string, unknown>;
405409
post: MattermostPost;
406410
}) => Promise<MattermostInteractionResponse | null>;
411+
authorizeButtonClick?: (opts: {
412+
payload: MattermostInteractionPayload;
413+
post: MattermostPost;
414+
}) => Promise<MattermostInteractionAuthorizationResult>;
407415
dispatchButtonClick?: (opts: {
408416
channelId: string;
409417
userId: string;
@@ -566,6 +574,33 @@ export function createMattermostInteractionHandler(params: {
566574
`post=${payload.post_id} channel=${payload.channel_id}`,
567575
);
568576

577+
if (params.authorizeButtonClick) {
578+
try {
579+
const authorization = await params.authorizeButtonClick({
580+
payload,
581+
post: originalPost,
582+
});
583+
if (!authorization.ok) {
584+
res.statusCode = authorization.statusCode ?? 200;
585+
res.setHeader("Content-Type", "application/json");
586+
res.end(
587+
JSON.stringify(
588+
authorization.response ?? {
589+
ephemeral_text: "You are not allowed to use this action here.",
590+
},
591+
),
592+
);
593+
return;
594+
}
595+
} catch (err) {
596+
log?.(`mattermost interaction: authorization failed: ${String(err)}`);
597+
res.statusCode = 500;
598+
res.setHeader("Content-Type", "application/json");
599+
res.end(JSON.stringify({ error: "Interaction authorization failed" }));
600+
return;
601+
}
602+
}
603+
569604
if (params.handleInteraction) {
570605
try {
571606
const response = await params.handleInteraction({

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,45 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
567567
trustedProxies: cfg.gateway?.trustedProxies,
568568
allowRealIpFallback: cfg.gateway?.allowRealIpFallback === true,
569569
handleInteraction: handleModelPickerInteraction,
570+
authorizeButtonClick: async ({ payload, post }) => {
571+
const channelInfo = await resolveChannelInfo(payload.channel_id);
572+
const isDirect = channelInfo?.type?.trim().toUpperCase() === "D";
573+
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
574+
cfg,
575+
surface: "mattermost",
576+
});
577+
const decision = authorizeMattermostCommandInvocation({
578+
account,
579+
cfg,
580+
senderId: payload.user_id,
581+
senderName: payload.user_name ?? "",
582+
channelId: payload.channel_id,
583+
channelInfo,
584+
storeAllowFrom: isDirect
585+
? await readStoreAllowFromForDmPolicy({
586+
provider: "mattermost",
587+
accountId: account.accountId,
588+
dmPolicy: account.config.dmPolicy ?? "pairing",
589+
readStore: pairing.readStoreForDmPolicy,
590+
})
591+
: undefined,
592+
allowTextCommands,
593+
hasControlCommand: false,
594+
});
595+
if (decision.ok) {
596+
return { ok: true };
597+
}
598+
return {
599+
ok: false,
600+
response: {
601+
update: {
602+
message: post.message ?? "",
603+
props: post.props as Record<string, unknown> | undefined,
604+
},
605+
ephemeral_text: `OpenClaw ignored this action for ${decision.roomLabel}.`,
606+
},
607+
};
608+
},
570609
resolveSessionKey: async ({ channelId, userId, post }) => {
571610
const channelInfo = await resolveChannelInfo(channelId);
572611
const kind = mapMattermostChannelTypeToChatType(channelInfo?.type);

‎extensions/nextcloud-talk/src/inbound.authz.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,77 @@ describe("nextcloud-talk inbound authz", () => {
8181
});
8282
expect(buildMentionRegexes).not.toHaveBeenCalled();
8383
});
84+
85+
it("matches group rooms by token instead of colliding room names", async () => {
86+
const readAllowFromStore = vi.fn(async () => []);
87+
const buildMentionRegexes = vi.fn(() => [/@openclaw/i]);
88+
89+
setNextcloudTalkRuntime({
90+
channel: {
91+
pairing: {
92+
readAllowFromStore,
93+
},
94+
commands: {
95+
shouldHandleTextCommands: () => false,
96+
},
97+
text: {
98+
hasControlCommand: () => false,
99+
},
100+
mentions: {
101+
buildMentionRegexes,
102+
matchesMentionPatterns: () => false,
103+
},
104+
},
105+
} as unknown as PluginRuntime);
106+
107+
const message: NextcloudTalkInboundMessage = {
108+
messageId: "m-2",
109+
roomToken: "room-attacker",
110+
roomName: "Room Trusted",
111+
senderId: "trusted-user",
112+
senderName: "Trusted User",
113+
text: "hello",
114+
mediaType: "text/plain",
115+
timestamp: Date.now(),
116+
isGroupChat: true,
117+
};
118+
119+
const account: ResolvedNextcloudTalkAccount = {
120+
accountId: "default",
121+
enabled: true,
122+
baseUrl: "",
123+
secret: "",
124+
secretSource: "none",
125+
config: {
126+
dmPolicy: "pairing",
127+
allowFrom: [],
128+
groupPolicy: "allowlist",
129+
groupAllowFrom: ["trusted-user"],
130+
rooms: {
131+
"room-trusted": {
132+
enabled: true,
133+
},
134+
},
135+
},
136+
};
137+
138+
await handleNextcloudTalkInbound({
139+
message,
140+
account,
141+
config: {
142+
channels: {
143+
"nextcloud-talk": {
144+
groupPolicy: "allowlist",
145+
groupAllowFrom: ["trusted-user"],
146+
},
147+
},
148+
},
149+
runtime: {
150+
log: vi.fn(),
151+
error: vi.fn(),
152+
} as unknown as RuntimeEnv,
153+
});
154+
155+
expect(buildMentionRegexes).not.toHaveBeenCalled();
156+
});
84157
});

0 commit comments

Comments
 (0)