Skip to content

Commit ed31a4d

Browse files
steipetePeter Steinberger
andauthored
fix(slack): authorize reaction and message reads before applying limits (#118736)
* fix(slack): bound reaction users in message actions * test(slack): validate encoded reaction request bodies * fix(slack): keep reaction user limits in action owner * fix(slack): authorize message reads before validating limits --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 8f2850d commit ed31a4d

4 files changed

Lines changed: 247 additions & 21 deletions

File tree

‎extensions/slack/src/action-runtime.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const messagingActions = new Set([
4242

4343
const reactionsActions = new Set(["react", "reactions"]);
4444
const pinActions = new Set(["pinMessage", "unpinMessage", "listPins"]);
45+
const SLACK_REACTION_USER_LIMIT = 100;
4546

4647
type SlackActionsRuntimeModule = typeof import("./actions.runtime.js");
4748

@@ -548,10 +549,23 @@ export async function handleSlackAction(
548549
return jsonResult({ ok: true, added: emoji });
549550
}
550551
await assertReadTargetAllowed(channelId);
552+
const limit = Math.min(
553+
readPositiveIntegerParam(params, "limit", {
554+
message: "limit must be a positive integer.",
555+
}) ?? SLACK_REACTION_USER_LIMIT,
556+
SLACK_REACTION_USER_LIMIT,
557+
);
551558
const reactions = readOpts
552559
? await slackActionRuntime.listSlackReactions(channelId, messageId, readOpts)
553560
: await slackActionRuntime.listSlackReactions(channelId, messageId);
554-
return jsonResult({ ok: true, reactions });
561+
return jsonResult({
562+
ok: true,
563+
reactions: reactions?.map((reaction) =>
564+
reaction.users
565+
? Object.assign({}, reaction, { users: reaction.users.slice(0, limit) })
566+
: reaction,
567+
),
568+
});
555569
}
556570

557571
if (messagingActions.has(action)) {
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
import { WebClient } from "@slack/web-api";
2+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { slackActionRuntime } from "./action-runtime.js";
5+
import {
6+
listSlackReactions,
7+
removeOwnSlackReactions,
8+
type SlackMessageSummary,
9+
} from "./actions.js";
10+
import { createSlackActions } from "./channel-actions.js";
11+
12+
type SlackReaction = NonNullable<SlackMessageSummary["reactions"]>[number];
13+
14+
const slackConfig = {
15+
channels: { slack: { botToken: "xoxb-local-proof", groupPolicy: "open" } },
16+
} as OpenClawConfig;
17+
18+
function createSlackReactionClient(reactions: SlackReaction[]) {
19+
const calls: Array<{ method: string; body: URLSearchParams }> = [];
20+
const client = new WebClient("xoxb-local-proof", {
21+
retryConfig: { retries: 0 },
22+
fetch: async (input, init) => {
23+
const method = new URL(String(input)).pathname.split("/").at(-1) ?? "";
24+
const requestBody = init?.body;
25+
if (typeof requestBody !== "string") {
26+
throw new Error("Slack reaction requests must use URL-encoded request bodies.");
27+
}
28+
const body = new URLSearchParams(requestBody);
29+
calls.push({ method, body });
30+
const result =
31+
method === "reactions.get"
32+
? { ok: true, channel: "C1", message: { reactions } }
33+
: method === "auth.test"
34+
? { ok: true, user_id: "UBOT" }
35+
: method === "reactions.remove"
36+
? { ok: true }
37+
: null;
38+
if (!result) {
39+
throw new Error(`Unexpected Slack API method: ${method}`);
40+
}
41+
return new Response(JSON.stringify(result), {
42+
status: 200,
43+
headers: { "content-type": "application/json" },
44+
});
45+
},
46+
});
47+
return { client, calls };
48+
}
49+
50+
async function readSlackReactionsThroughPublicAction(params: {
51+
client: WebClient;
52+
limit?: number;
53+
}) {
54+
vi.spyOn(slackActionRuntime, "resolveSlackConversationInfo").mockResolvedValue({
55+
type: "channel",
56+
});
57+
vi.spyOn(slackActionRuntime, "listSlackReactions").mockImplementation(
58+
(channelId, messageId, options) =>
59+
listSlackReactions(channelId, messageId, { ...options, client: params.client }),
60+
);
61+
const result = await createSlackActions("slack").handleAction?.({
62+
action: "reactions",
63+
cfg: slackConfig,
64+
conversationReadOrigin: "direct-operator",
65+
params: {
66+
channelId: "C1",
67+
messageId: "123.456",
68+
...(params.limit === undefined ? {} : { limit: params.limit }),
69+
},
70+
} as never);
71+
const content = result?.content[0];
72+
if (!content || content.type !== "text") {
73+
throw new Error("Slack reactions did not return a text tool result.");
74+
}
75+
return JSON.parse(content.text) as { ok: boolean; reactions: SlackReaction[] };
76+
}
77+
78+
describe("Slack reaction user limits", () => {
79+
afterEach(() => {
80+
vi.restoreAllMocks();
81+
});
82+
83+
it("limits users per emoji through the public action without changing reaction facts", async () => {
84+
const { client, calls } = createSlackReactionClient([
85+
{ name: "eyes", count: 3, users: ["U1", "U2", "UBOT"] },
86+
{ name: "wave", count: 2, users: ["U3", "U4"] },
87+
{ name: "heart", count: 5 },
88+
{ name: "party", count: 0, users: [] },
89+
]);
90+
91+
const result = await readSlackReactionsThroughPublicAction({ client, limit: 1 });
92+
93+
expect(result).toEqual({
94+
ok: true,
95+
reactions: [
96+
{ name: "eyes", count: 3, users: ["U1"] },
97+
{ name: "wave", count: 2, users: ["U3"] },
98+
{ name: "heart", count: 5 },
99+
{ name: "party", count: 0, users: [] },
100+
],
101+
});
102+
expect(calls).toHaveLength(1);
103+
expect(calls[0]?.method).toBe("reactions.get");
104+
expect(calls[0]?.body.get("full")).toBe("true");
105+
expect(calls[0]?.body.has("limit")).toBe(false);
106+
});
107+
108+
it.each([
109+
{ name: "omitted", limit: undefined },
110+
{ name: "larger than the hard cap", limit: 500 },
111+
{ name: "the largest safe integer", limit: Number.MAX_SAFE_INTEGER },
112+
])("caps $name user limits at 100 users per emoji", async ({ limit }) => {
113+
const users = Array.from({ length: 101 }, (_, index) => `U${index + 1}`);
114+
const { client } = createSlackReactionClient([{ name: "eyes", count: 101, users }]);
115+
116+
const result = await readSlackReactionsThroughPublicAction({ client, limit });
117+
118+
expect(result.reactions).toEqual([{ name: "eyes", count: 101, users: users.slice(0, 100) }]);
119+
expect(users).toHaveLength(101);
120+
});
121+
122+
it.each(["reactions", "read"] as const)(
123+
"authorizes public %s targets before inspecting malformed limits",
124+
async (action) => {
125+
const restrictedConfig = {
126+
channels: {
127+
slack: {
128+
botToken: "xoxb-local-proof",
129+
groupPolicy: "allowlist",
130+
channels: { C_ALLOWED: { enabled: true } },
131+
},
132+
},
133+
} as OpenClawConfig;
134+
const { client, calls } = createSlackReactionClient([]);
135+
const reactionLookup = vi
136+
.spyOn(slackActionRuntime, "listSlackReactions")
137+
.mockImplementation((channelId, messageId, options) =>
138+
listSlackReactions(channelId, messageId, { ...options, client }),
139+
);
140+
const messageLookup = vi.spyOn(slackActionRuntime, "readSlackMessages");
141+
142+
await expect(
143+
createSlackActions("slack").handleAction?.({
144+
action,
145+
cfg: restrictedConfig,
146+
params: { channelId: "C_FORBIDDEN", messageId: "123.456", limit: 0 },
147+
} as never),
148+
).rejects.toThrow("Slack read target channel is not allowed.");
149+
expect(reactionLookup).not.toHaveBeenCalled();
150+
expect(messageLookup).not.toHaveBeenCalled();
151+
expect(calls).toEqual([]);
152+
},
153+
);
154+
155+
it.each([
156+
{ action: "reactions", limit: 0 },
157+
{ action: "reactions", limit: -1 },
158+
{ action: "reactions", limit: 1.5 },
159+
{ action: "reactions", limit: Number.NaN },
160+
{ action: "reactions", limit: Number.POSITIVE_INFINITY },
161+
{ action: "reactions", limit: Number.NEGATIVE_INFINITY },
162+
{ action: "reactions", limit: Number.MAX_SAFE_INTEGER + 1 },
163+
{ action: "read", limit: 0 },
164+
])(
165+
"rejects invalid public $action limit $limit before Slack API work",
166+
async ({ action, limit }) => {
167+
const { client, calls } = createSlackReactionClient([]);
168+
const conversationLookup = vi
169+
.spyOn(slackActionRuntime, "resolveSlackConversationInfo")
170+
.mockResolvedValue({ type: "channel" });
171+
const reactionLookup = vi
172+
.spyOn(slackActionRuntime, "listSlackReactions")
173+
.mockImplementation((channelId, messageId, options) =>
174+
listSlackReactions(channelId, messageId, { ...options, client }),
175+
);
176+
const messageLookup = vi.spyOn(slackActionRuntime, "readSlackMessages");
177+
178+
await expect(
179+
createSlackActions("slack").handleAction?.({
180+
action,
181+
cfg: slackConfig,
182+
params: { channelId: "C1", messageId: "123.456", limit },
183+
} as never),
184+
).rejects.toThrow("limit must be a positive integer.");
185+
expect(conversationLookup).toHaveBeenCalledOnce();
186+
expect(reactionLookup).not.toHaveBeenCalled();
187+
expect(messageLookup).not.toHaveBeenCalled();
188+
expect(calls).toEqual([]);
189+
},
190+
);
191+
192+
it("preserves all reaction users for existing live approval helper callers", async () => {
193+
const users = [...Array.from({ length: 100 }, (_, index) => `U${index + 1}`), "U_APPROVER"];
194+
const { client } = createSlackReactionClient([
195+
{ name: "white_check_mark", count: users.length, users },
196+
]);
197+
198+
await expect(listSlackReactions("C1", "123.456", { client })).resolves.toEqual([
199+
{ name: "white_check_mark", count: users.length, users },
200+
]);
201+
});
202+
203+
it("removes the bot's own reaction when its user is beyond the public cap", async () => {
204+
const users = [...Array.from({ length: 100 }, (_, index) => `U${index + 1}`), "UBOT"];
205+
const { client, calls } = createSlackReactionClient([
206+
{ name: "eyes", count: users.length, users },
207+
]);
208+
209+
await expect(removeOwnSlackReactions("C1", "123.456", { client })).resolves.toEqual(["eyes"]);
210+
211+
expect(calls.map(({ method }) => method)).toEqual([
212+
"auth.test",
213+
"reactions.get",
214+
"reactions.remove",
215+
]);
216+
expect(calls[2]?.body.get("name")).toBe("eyes");
217+
});
218+
});

‎extensions/slack/src/message-action-dispatch.test.ts‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -856,25 +856,25 @@ describe("handleSlackMessageAction", () => {
856856
expect(firstInvokeCall(invoke)[1]).toEqual({});
857857
});
858858

859-
it("rejects fractional read limits before invoking Slack actions", async () => {
860-
const invoke = createInvokeSpy();
859+
it.each([2.5, "20"])(
860+
"forwards raw read limit %s to the authorized action owner",
861+
async (limit) => {
862+
const invoke = createInvokeSpy();
861863

862-
await expect(
863-
handleSlackMessageAction({
864+
await handleSlackMessageAction({
864865
providerId: "slack",
865866
ctx: {
866867
action: "read",
867868
cfg: {},
868-
params: {
869-
channelId: "C1",
870-
limit: 2.5,
871-
},
869+
params: { channelId: "C1", limit },
872870
} as never,
873871
invoke: invoke as never,
874-
}),
875-
).rejects.toThrow("limit must be a positive integer.");
876-
expect(invoke).not.toHaveBeenCalled();
877-
});
872+
});
873+
874+
expect(firstAction(invoke)).toMatchObject({ action: "readMessages", limit });
875+
expect(invoke).toHaveBeenCalledOnce();
876+
},
877+
);
878878

879879
it("requires filePath, path, or media for upload-file", async () => {
880880
await expect(

‎extensions/slack/src/message-action-dispatch.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -172,15 +172,12 @@ export async function handleSlackMessageAction(params: {
172172
const messageId = readStringParam(actionParams, "messageId", {
173173
required: true,
174174
});
175-
const limit = readPositiveIntegerParam(actionParams, "limit", {
176-
message: "limit must be a positive integer.",
177-
});
178175
return await invoke(
179176
{
180177
action: "reactions",
181178
channelId: resolveChannelId(),
182179
messageId,
183-
limit,
180+
limit: actionParams.limit,
184181
accountId,
185182
},
186183
cfg,
@@ -189,13 +186,10 @@ export async function handleSlackMessageAction(params: {
189186
}
190187

191188
if (action === "read") {
192-
const limit = readPositiveIntegerParam(actionParams, "limit", {
193-
message: "limit must be a positive integer.",
194-
});
195189
const readAction: Record<string, unknown> = {
196190
action: "readMessages",
197191
channelId: resolveChannelId(),
198-
limit,
192+
limit: actionParams.limit,
199193
before: readStringParam(actionParams, "before"),
200194
after: readStringParam(actionParams, "after"),
201195
messageId: readStringParam(actionParams, "messageId"),

0 commit comments

Comments
 (0)