Skip to content

Commit 7aacd13

Browse files
authored
fix(slack): recover bot identity after transient auth.test failure (#117253)
* fix(slack): recover bot identity after transient auth.test failure * docs(slack): document identity selection invariant * fix(slack): resolve startup auth fetch through plugin runtime
1 parent 08fc4f5 commit 7aacd13

14 files changed

Lines changed: 311 additions & 56 deletions

‎extensions/slack/src/client-options.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { createRequire } from "node:module";
33
import type { RetryOptions, WebClientOptions } from "@slack/web-api";
44
import {
55
addActiveManagedProxyTlsOptions,
6+
resolveFetch,
67
resolveEnvHttpProxyAgentOptions,
78
} from "openclaw/plugin-sdk/fetch-runtime";
89
import type { EnvHttpProxyAgent } from "undici";
@@ -53,9 +54,12 @@ export function resolveSlackProxyDispatcher(): SlackProxyDispatcher | undefined
5354
}
5455
}
5556

56-
function createSlackDispatcherFetch(
57-
dispatcher: SlackProxyDispatcher,
58-
): NonNullable<WebClientOptions["fetch"]> {
57+
function buildSlackFetch(
58+
dispatcher?: SlackProxyDispatcher,
59+
): NonNullable<WebClientOptions["fetch"]> | undefined {
60+
if (!dispatcher) {
61+
return resolveFetch() as NonNullable<WebClientOptions["fetch"]> | undefined;
62+
}
5963
const { fetch: slackFetch } = loadSlackUndiciRuntime();
6064
return ((input: RequestInfo | URL, init?: RequestInit) => {
6165
// Slack Web API invokes this hook with URL/string inputs. The cast only bridges
@@ -76,7 +80,7 @@ function applySlackApiUrlAndProxyOptions(
7680
): void {
7781
const slackApiUrl = options.slackApiUrl ?? resolveSlackApiUrlFromEnv();
7882
if (dispatcher && !options.fetch) {
79-
options.fetch = createSlackDispatcherFetch(dispatcher);
83+
options.fetch = buildSlackFetch(dispatcher);
8084
}
8185
if (slackApiUrl !== undefined) {
8286
options.slackApiUrl = slackApiUrl;
@@ -91,6 +95,7 @@ export function resolveSlackWebClientOptions(
9195
): WebClientOptions {
9296
const resolved: WebClientOptions = Object.assign({}, options);
9397
applySlackApiUrlAndProxyOptions(resolved, dispatcher);
98+
resolved.fetch ??= buildSlackFetch(dispatcher);
9499
resolved.retryConfig ??= SLACK_DEFAULT_RETRY_OPTIONS;
95100
return resolved;
96101
}

‎extensions/slack/src/client.test.ts‎

Lines changed: 39 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,14 @@ describe("slack web client config", () => {
138138
try {
139139
createSlackReadClient("xoxb-read");
140140

141-
expect(WebClient).toHaveBeenCalledWith("xoxb-read", {
142-
retryConfig: SLACK_DEFAULT_RETRY_OPTIONS,
143-
timeout: 30_000,
144-
});
141+
expect(WebClient).toHaveBeenCalledWith(
142+
"xoxb-read",
143+
expect.objectContaining({
144+
fetch: expect.any(Function),
145+
retryConfig: SLACK_DEFAULT_RETRY_OPTIONS,
146+
timeout: 30_000,
147+
}),
148+
);
145149
} finally {
146150
restoreProxyEnvForTest();
147151
}
@@ -152,10 +156,14 @@ describe("slack web client config", () => {
152156
try {
153157
createSlackReadClient("xoxb-read", { timeout: 60_000 });
154158

155-
expect(WebClient).toHaveBeenCalledWith("xoxb-read", {
156-
retryConfig: SLACK_DEFAULT_RETRY_OPTIONS,
157-
timeout: 60_000,
158-
});
159+
expect(WebClient).toHaveBeenCalledWith(
160+
"xoxb-read",
161+
expect.objectContaining({
162+
fetch: expect.any(Function),
163+
retryConfig: SLACK_DEFAULT_RETRY_OPTIONS,
164+
timeout: 60_000,
165+
}),
166+
);
159167
} finally {
160168
restoreProxyEnvForTest();
161169
}
@@ -231,24 +239,33 @@ describe("slack web client config", () => {
231239
slackApiUrl: "https://slack.test/api/",
232240
});
233241

234-
expect(WebClient).toHaveBeenCalledWith("xoxb-startup", {
235-
fetch: customFetch,
236-
rejectRateLimitedCalls: true,
237-
retryConfig: { retries: 2, minTimeout: 0 },
238-
slackApiUrl: "https://slack.test/api/",
239-
timeout: 10_000,
240-
});
242+
expect(WebClient).toHaveBeenCalledWith(
243+
"xoxb-startup",
244+
expect.objectContaining({
245+
fetch: expect.any(Function),
246+
retryConfig: { ...SLACK_DEFAULT_RETRY_OPTIONS, maxRetryTime: 35_000 },
247+
slackApiUrl: "https://slack.test/api/",
248+
timeout: 10_000,
249+
}),
250+
);
251+
const options = WebClient.mock.calls[0]?.[1] as Record<string, unknown>;
252+
expect(options.fetch).not.toBe(customFetch);
253+
expect(options).not.toHaveProperty("rejectRateLimitedCalls");
241254
});
242255

243256
it("applies the default retry config when constructing a client without proxy env", () => {
244257
clearProxyEnvForTest();
245258
try {
246259
createSlackWebClient("xoxb-test", { timeout: 1234 });
247260

248-
expect(WebClient).toHaveBeenCalledWith("xoxb-test", {
249-
retryConfig: SLACK_DEFAULT_RETRY_OPTIONS,
250-
timeout: 1234,
251-
});
261+
expect(WebClient).toHaveBeenCalledWith(
262+
"xoxb-test",
263+
expect.objectContaining({
264+
fetch: expect.any(Function),
265+
retryConfig: SLACK_DEFAULT_RETRY_OPTIONS,
266+
timeout: 1234,
267+
}),
268+
);
252269
} finally {
253270
restoreProxyEnvForTest();
254271
}
@@ -408,9 +425,9 @@ describe("slack proxy dispatcher", () => {
408425
await dispatcher?.close();
409426
});
410427

411-
it("does not attach a fetch when no proxy env var is configured", () => {
428+
it("attaches the shared fetch when no proxy env var is configured", () => {
412429
expect(resolveSlackProxyDispatcher()).toBeUndefined();
413-
expect(resolveSlackWebClientOptions().fetch).toBeUndefined();
430+
expect(requireFetch(resolveSlackWebClientOptions())).toBeTypeOf("function");
414431
});
415432

416433
it("preserves an explicitly provided fetch", async () => {
@@ -459,6 +476,6 @@ describe("slack proxy dispatcher", () => {
459476
process.env.HTTPS_PROXY = "not-a-valid-url://:::bad";
460477

461478
expect(resolveSlackProxyDispatcher()).toBeUndefined();
462-
expect(resolveSlackWebClientOptions().fetch).toBeUndefined();
479+
expect(requireFetch(resolveSlackWebClientOptions())).toBeTypeOf("function");
463480
});
464481
});

‎extensions/slack/src/client.ts‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,21 @@ import {
77
resolveSlackReadClientOptions,
88
resolveSlackWebClientOptions,
99
resolveSlackWriteClientOptions,
10+
SLACK_DEFAULT_RETRY_OPTIONS,
1011
SLACK_WRITE_RETRY_OPTIONS,
1112
} from "./client-options.js";
1213

1314
const SLACK_WRITE_CLIENT_CACHE_MAX = 32;
15+
const SLACK_STARTUP_AUTH_TIMEOUT_MS = 10_000;
16+
const SLACK_STARTUP_AUTH_RETRY_BUDGET_MS = 35_000;
1417
const slackWriteClientCache = new Map<string, WebClient>();
1518
let slackListenerUploadCompletionClientCache = new WeakMap<
1619
WebClient,
1720
{ teamId: string; client: WebClient }
1821
>();
1922

2023
type SlackWriteClientCacheOptions = Pick<WebClientOptions, "slackApiUrl">;
24+
type SlackFetch = NonNullable<WebClientOptions["fetch"]>;
2125

2226
export {
2327
resolveSlackWebClientOptions,
@@ -36,14 +40,41 @@ export function createSlackReadClient(token: string, options: WebClientOptions =
3640
return new WebClient(token, resolveSlackReadClientOptions(options));
3741
}
3842

43+
function createSlackStartupAuthFetch(baseFetch: SlackFetch): SlackFetch {
44+
const deadline = Date.now() + SLACK_STARTUP_AUTH_RETRY_BUDGET_MS;
45+
return async (input, init) => {
46+
const response = await baseFetch(input, init);
47+
if (response.status !== 429) {
48+
return response;
49+
}
50+
const retryAfter = Number.parseInt(response.headers.get("retry-after") ?? "", 10);
51+
const remainingMs = Math.max(0, deadline - Date.now());
52+
if (!Number.isFinite(retryAfter) || retryAfter * 1000 <= remainingMs) {
53+
return response;
54+
}
55+
// Slack sleeps through Retry-After outside its per-attempt timeout. Wait only
56+
// within the startup budget, then let the retry policy terminate the call.
57+
await new Promise<void>((resolve) => {
58+
setTimeout(resolve, remainingMs);
59+
});
60+
throw new Error("Slack startup auth retry budget exhausted after rate limit");
61+
};
62+
}
63+
3964
export function createSlackStartupAuthClient(token: string, options: WebClientOptions = {}) {
40-
// Startup identity stays degraded until restart after auth.test fails. Retry two transient
41-
// transport failures before committing that state, without delaying on Slack rate limits.
42-
return createSlackWebClient(token, {
43-
...options,
44-
rejectRateLimitedCalls: true,
45-
retryConfig: { retries: 2, minTimeout: 0 },
46-
timeout: 10_000,
65+
const resolvedOptions = resolveSlackWebClientOptions(options);
66+
const baseFetch = resolvedOptions.fetch;
67+
if (!baseFetch) {
68+
throw new Error("Slack startup auth fetch is unavailable");
69+
}
70+
return new WebClient(token, {
71+
...resolvedOptions,
72+
fetch: createSlackStartupAuthFetch(baseFetch),
73+
retryConfig: {
74+
...SLACK_DEFAULT_RETRY_OPTIONS,
75+
maxRetryTime: SLACK_STARTUP_AUTH_RETRY_BUDGET_MS,
76+
},
77+
timeout: SLACK_STARTUP_AUTH_TIMEOUT_MS,
4778
});
4879
}
4980

‎extensions/slack/src/client.web-api.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,32 @@ describe("Slack Web API routing", () => {
224224
expect(fetchMock).toHaveBeenCalledTimes(1);
225225
});
226226

227+
it("retries startup auth after a rate limit", async () => {
228+
const fetchMock = vi
229+
.fn()
230+
.mockResolvedValueOnce(
231+
new Response(JSON.stringify({ ok: false, error: "ratelimited" }), {
232+
status: 429,
233+
headers: { "retry-after": "0" },
234+
}),
235+
)
236+
.mockResolvedValueOnce(
237+
new Response(JSON.stringify({ ok: true, team_id: "TMOCK", user_id: "UMOCK" }), {
238+
status: 200,
239+
}),
240+
);
241+
const client = createSlackStartupAuthClient("rate-limited-fixture", {
242+
fetch: fetchMock as never,
243+
});
244+
245+
await expect(client.auth.test()).resolves.toMatchObject({
246+
ok: true,
247+
team_id: "TMOCK",
248+
user_id: "UMOCK",
249+
});
250+
expect(fetchMock).toHaveBeenCalledTimes(2);
251+
});
252+
227253
it("aborts a stalled-header lookup after one request", async () => {
228254
for (const key of TEST_ENV_KEYS) {
229255
delete process.env[key];

‎extensions/slack/src/monitor/context.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ function createTestContext(params?: {
2525
runtime: {} as RuntimeEnv,
2626
botUserId: "U_BOT",
2727
botId: "B_BOT",
28+
identityHealth: { healthState: "healthy", lastError: null },
2829
teamId: "T_EXPECTED",
2930
apiAppId: params?.apiAppId ?? "A_EXPECTED",
3031
historyLimit: 0,

‎extensions/slack/src/monitor/context.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import type { SlackChannelConfigEntries } from "./channel-config.js";
2929
import { resolveSlackChannelConfig } from "./channel-config.js";
3030
import { normalizeSlackChannelType } from "./channel-type.js";
3131
import { resolveSessionKey } from "./config.runtime.js";
32-
import type { SlackInstallationIdentity } from "./enterprise-install.js";
32+
import type { SlackIdentityHealth, SlackInstallationIdentity } from "./enterprise-install.js";
3333
import type { SlackEventScope } from "./event-scope.js";
3434
import { readLruMapEntry, writeLruMapEntry } from "./lru-map-cache.js";
3535
import { isSlackChannelAllowedByPolicy } from "./policy.js";
@@ -122,6 +122,7 @@ export type SlackMonitorContext = {
122122

123123
botUserId: string;
124124
botId?: string;
125+
identityHealth: SlackIdentityHealth;
125126
teamId: string;
126127
apiAppId: string;
127128
installationIdentity: SlackInstallationIdentity;
@@ -219,6 +220,7 @@ export function createSlackMonitorContext(params: {
219220

220221
botUserId: string;
221222
botId?: string;
223+
identityHealth: SlackIdentityHealth;
222224
teamId: string;
223225
apiAppId: string;
224226
installationIdentity?: SlackInstallationIdentity;
@@ -683,6 +685,7 @@ export function createSlackMonitorContext(params: {
683685
channelRuntime: params.channelRuntime,
684686
botUserId: params.botUserId,
685687
botId: params.botId,
688+
identityHealth: params.identityHealth,
686689
teamId: params.teamId,
687690
apiAppId: params.apiAppId,
688691
installationIdentity: params.installationIdentity ?? {

‎extensions/slack/src/monitor/message-handler/prepare.test-helpers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export function createInboundSlackTestContext(params: {
3232
channelRuntime: params.channelRuntime ?? createPluginRuntimeMock().channel,
3333
botUserId: "B1",
3434
botId: "B1",
35+
identityHealth: { healthState: "healthy", lastError: null },
3536
teamId: "T1",
3637
apiAppId: "A1",
3738
historyLimit: 0,

‎extensions/slack/src/monitor/monitor.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ const baseParams = () => ({
197197
runtime: {} as RuntimeEnv,
198198
botUserId: "B1",
199199
botId: "B1",
200+
identityHealth: { healthState: "healthy" as const, lastError: null },
200201
teamId: "T1",
201202
apiAppId: "A1",
202203
historyLimit: 0,

‎extensions/slack/src/monitor/provider-support.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,12 @@ type SlackSelfFilterArgs = {
4040
context?: {
4141
botId?: string;
4242
botUserId?: string;
43+
isEnterpriseInstall?: boolean;
4344
};
4445
event?: unknown;
4546
message?: unknown;
4647
};
48+
type SlackContextIdentity = NonNullable<SlackSelfFilterArgs["context"]>;
4749

4850
function isConstructorFunction<
4951
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- Constructor guard preserves the requested concrete Slack constructor type.
@@ -312,6 +314,7 @@ export function createSlackBoltApp(params: {
312314
clientOptions: Record<string, unknown>;
313315
dispatcher?: SlackSocketModeReceiverOptions["dispatcher"];
314316
wrapReceiver?: (receiver: SlackReceiver) => SlackReceiver;
317+
onContextIdentity?: (identity: SlackContextIdentity) => void;
315318
}) {
316319
const socketModeLogger = createSlackSocketModeLogger();
317320
const socketModeReceiverOptions: SlackSocketModeReceiverOptions = {
@@ -355,6 +358,7 @@ export function createSlackBoltApp(params: {
355358
...(appReceiver ? { receiver: appReceiver } : {}),
356359
});
357360
app.use(async (args) => {
361+
params.onContextIdentity?.(args.context ?? {});
358362
if (shouldSkipOpenClawSlackSelfEvent(args)) {
359363
return;
360364
}
@@ -388,7 +392,7 @@ function createSlackSocketDisconnectWaiter(app: unknown, abortSignal?: AbortSign
388392
export async function startSlackSocketAndWaitForDisconnect(params: {
389393
app: { start: () => unknown };
390394
abortSignal?: AbortSignal;
391-
onStarted?: () => void;
395+
onStarted?: () => void | Promise<void>;
392396
}) {
393397
const disconnectWaiter = createSlackSocketDisconnectWaiter(params.app, params.abortSignal);
394398
try {
@@ -397,7 +401,7 @@ export async function startSlackSocketAndWaitForDisconnect(params: {
397401
disconnectWaiter.cancel();
398402
return null;
399403
}
400-
params.onStarted?.();
404+
await params.onStarted?.();
401405
const disconnect = await disconnectWaiter.promise;
402406
disconnectWaiter.complete();
403407
return disconnect;

0 commit comments

Comments
 (0)