Skip to content

Commit 0c8220e

Browse files
Alix-007steipete
andauthored
fix(msteams): add timeouts to file consent upload requests (#104120)
* fix(msteams): add timeouts to file consent upload requests * fix(msteams): share file consent upload timeout helper * fix(msteams): size-budget file consent upload timeout * chore(deadcode): allowlist test-only timeout constant exports * style(msteams): format consent timeout test * test(msteams): reject consent aborts with errors --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 202b049 commit 0c8220e

4 files changed

Lines changed: 181 additions & 17 deletions

File tree

‎extensions/msteams/src/file-consent.test.ts‎

Lines changed: 135 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Msteams tests cover file consent plugin behavior.
22
import { describe, expect, it, vi } from "vitest";
33
import { uploadToConsentUrl } from "./file-consent.js";
4+
import { resolveMSTeamsSharePointUploadTimeoutMs } from "./request-timeout.js";
45
import { buildUserAgent } from "./user-agent.js";
56

67
// Helper: a resolveFn that returns a public IP by default
@@ -321,6 +322,132 @@ describe("uploadToConsentUrl", () => {
321322
expect(opts?.body).toEqual(new Uint8Array(Buffer.from("hello")));
322323
});
323324

325+
it("aborts consent uploads that do not finish before the request timeout", async () => {
326+
vi.useFakeTimers();
327+
try {
328+
let observedSignal: AbortSignal | undefined;
329+
const fetchFn = vi.fn<typeof fetch>(
330+
async (_url, init) =>
331+
await new Promise<Response>((_resolve, reject) => {
332+
observedSignal = init?.signal ?? undefined;
333+
observedSignal?.addEventListener(
334+
"abort",
335+
() => {
336+
const reason = observedSignal?.reason;
337+
reject(reason instanceof Error ? reason : new Error("request aborted"));
338+
},
339+
{ once: true },
340+
);
341+
}),
342+
);
343+
344+
const uploadPromise = uploadToConsentUrl({
345+
url: "https://contoso.sharepoint.com/upload",
346+
buffer: Buffer.from("hello"),
347+
fetchFn,
348+
timeoutMs: 25,
349+
validationOpts: { resolveFn: publicResolve },
350+
});
351+
352+
await vi.advanceTimersByTimeAsync(0);
353+
expect(fetchFn).toHaveBeenCalledOnce();
354+
expect(observedSignal?.aborted).toBe(false);
355+
const uploadRejection = expect(uploadPromise).rejects.toMatchObject({
356+
name: "TimeoutError",
357+
message: "request timed out",
358+
});
359+
360+
await vi.advanceTimersByTimeAsync(25);
361+
await uploadRejection;
362+
expect(observedSignal?.aborted).toBe(true);
363+
} finally {
364+
vi.useRealTimers();
365+
}
366+
});
367+
368+
it("allows consent uploads that complete before the request timeout", async () => {
369+
vi.useFakeTimers();
370+
try {
371+
let observedSignal: AbortSignal | undefined;
372+
const fetchFn = vi.fn<typeof fetch>(
373+
async (_url, init) =>
374+
await new Promise<Response>((resolve, reject) => {
375+
observedSignal = init?.signal ?? undefined;
376+
observedSignal?.addEventListener(
377+
"abort",
378+
() => reject(new DOMException("consent upload timed out", "AbortError")),
379+
{ once: true },
380+
);
381+
setTimeout(() => resolve(new Response(null, { status: 200 })), 25);
382+
}),
383+
);
384+
385+
const uploadPromise = uploadToConsentUrl({
386+
url: "https://contoso.sharepoint.com/upload",
387+
buffer: Buffer.from("hello"),
388+
fetchFn,
389+
timeoutMs: 50,
390+
validationOpts: { resolveFn: publicResolve },
391+
});
392+
393+
await vi.advanceTimersByTimeAsync(0);
394+
expect(fetchFn).toHaveBeenCalledOnce();
395+
expect(observedSignal?.aborted).toBe(false);
396+
397+
await vi.advanceTimersByTimeAsync(25);
398+
await expect(uploadPromise).resolves.toBeUndefined();
399+
expect(observedSignal?.aborted).toBe(false);
400+
401+
await vi.advanceTimersByTimeAsync(25);
402+
expect(observedSignal?.aborted).toBe(false);
403+
} finally {
404+
vi.useRealTimers();
405+
}
406+
});
407+
408+
it("allows size-budgeted consent uploads that complete after the base upload deadline", async () => {
409+
vi.useFakeTimers();
410+
try {
411+
const buffer = Buffer.alloc(512 * 1024);
412+
const resolvedTimeoutMs = resolveMSTeamsSharePointUploadTimeoutMs(buffer.length);
413+
const baseTimeoutMs = resolveMSTeamsSharePointUploadTimeoutMs(0);
414+
const completionMs = baseTimeoutMs + 1_000;
415+
let observedSignal: AbortSignal | undefined;
416+
const fetchFn = vi.fn<typeof fetch>(
417+
async (_url, init) =>
418+
await new Promise<Response>((resolve, reject) => {
419+
observedSignal = init?.signal ?? undefined;
420+
observedSignal?.addEventListener(
421+
"abort",
422+
() => reject(new DOMException("consent upload timed out", "AbortError")),
423+
{ once: true },
424+
);
425+
setTimeout(() => resolve(new Response(null, { status: 200 })), completionMs);
426+
}),
427+
);
428+
429+
expect(completionMs).toBeGreaterThan(baseTimeoutMs);
430+
expect(completionMs).toBeLessThan(resolvedTimeoutMs);
431+
432+
const uploadPromise = uploadToConsentUrl({
433+
url: "https://contoso.sharepoint.com/upload",
434+
buffer,
435+
fetchFn,
436+
validationOpts: { resolveFn: publicResolve },
437+
});
438+
439+
await vi.advanceTimersByTimeAsync(0);
440+
expect(fetchFn).toHaveBeenCalledOnce();
441+
expect(observedSignal?.aborted).toBe(false);
442+
443+
await vi.advanceTimersByTimeAsync(completionMs);
444+
await expect(uploadPromise).resolves.toBeUndefined();
445+
expect(observedSignal?.aborted).toBe(false);
446+
} finally {
447+
vi.useRealTimers();
448+
}
449+
});
450+
324451
it("blocks upload to a disallowed host", async () => {
325452
const mockFetch = vi.fn();
326453
await expect(
@@ -364,15 +491,15 @@ describe("uploadToConsentUrl", () => {
364491
expect(mockFetch).toHaveBeenCalledOnce();
365492
const [url, opts] = firstFetchCall(mockFetch);
366493
expect(url).toBe("https://contoso.sharepoint.com/sites/uploads/file.pdf");
367-
expect(opts).toEqual({
368-
method: "PUT",
369-
headers: {
370-
"User-Agent": buildUserAgent(),
371-
"Content-Type": "application/pdf",
372-
"Content-Range": "bytes 0-11/12",
373-
},
374-
body: new Uint8Array(buffer),
494+
expect(opts?.method).toBe("PUT");
495+
expect(opts?.headers).toEqual({
496+
"User-Agent": buildUserAgent(),
497+
"Content-Type": "application/pdf",
498+
"Content-Range": "bytes 0-11/12",
375499
});
500+
expect(opts?.body).toEqual(new Uint8Array(buffer));
501+
expect(opts?.signal).toBeInstanceOf(AbortSignal);
502+
expect(opts?.signal?.aborted).toBe(false);
376503
});
377504

378505
it("throws on non-OK response after passing validation", async () => {

‎extensions/msteams/src/file-consent.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
import { lookup } from "node:dns/promises";
1212
import { isPrivateIpAddress } from "openclaw/plugin-sdk/ssrf-policy";
1313
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
14+
import { fetchWithTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
15+
import { resolveMSTeamsSharePointUploadTimeoutMs } from "./request-timeout.js";
1416
import { buildUserAgent } from "./user-agent.js";
1517

1618
/**
@@ -198,6 +200,7 @@ export async function uploadToConsentUrl(params: {
198200
buffer: Buffer;
199201
contentType?: string;
200202
fetchFn?: typeof fetch;
203+
timeoutMs?: number;
201204
/** Override for testing — custom allowlist and DNS resolver */
202205
validationOpts?: {
203206
allowlist?: readonly string[];
@@ -207,15 +210,20 @@ export async function uploadToConsentUrl(params: {
207210
await validateConsentUploadUrl(params.url, params.validationOpts);
208211

209212
const fetchFn = params.fetchFn ?? fetch;
210-
const res = await fetchFn(params.url, {
211-
method: "PUT",
212-
headers: {
213-
"User-Agent": buildUserAgent(),
214-
"Content-Type": params.contentType ?? "application/octet-stream",
215-
"Content-Range": `bytes 0-${params.buffer.length - 1}/${params.buffer.length}`,
213+
const res = await fetchWithTimeout(
214+
params.url,
215+
{
216+
method: "PUT",
217+
headers: {
218+
"User-Agent": buildUserAgent(),
219+
"Content-Type": params.contentType ?? "application/octet-stream",
220+
"Content-Range": `bytes 0-${params.buffer.length - 1}/${params.buffer.length}`,
221+
},
222+
body: new Uint8Array(params.buffer),
216223
},
217-
body: new Uint8Array(params.buffer),
218-
});
224+
params.timeoutMs ?? resolveMSTeamsSharePointUploadTimeoutMs(params.buffer.length),
225+
fetchFn,
226+
);
219227

220228
if (!res.ok) {
221229
throw new Error(`File upload to consent URL failed: ${res.status} ${res.statusText}`);

‎extensions/msteams/src/request-timeout.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Msteams tests cover shared inbound request deadlines.
22
import { describe, expect, it, vi } from "vitest";
3-
import { withMSTeamsRequestDeadline } from "./request-timeout.js";
3+
import {
4+
resolveMSTeamsSharePointUploadTimeoutMs,
5+
withMSTeamsRequestDeadline,
6+
} from "./request-timeout.js";
47

58
describe("withMSTeamsRequestDeadline", () => {
69
it("does not start work after the operation deadline has expired", async () => {
@@ -21,3 +24,12 @@ describe("withMSTeamsRequestDeadline", () => {
2124
expect(work).not.toHaveBeenCalled();
2225
});
2326
});
27+
28+
describe("resolveMSTeamsSharePointUploadTimeoutMs", () => {
29+
it("adds transfer budget to the base file-consent upload deadline", () => {
30+
const oneHundredMiB = 100 * 1024 * 1024;
31+
32+
expect(resolveMSTeamsSharePointUploadTimeoutMs(0)).toBe(300_000);
33+
expect(resolveMSTeamsSharePointUploadTimeoutMs(oneHundredMiB)).toBe(700_000);
34+
});
35+
});

‎extensions/msteams/src/request-timeout.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Msteams plugin module implements request deadline behavior.
2+
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
23
import {
34
createProviderOperationDeadline,
45
resolveProviderOperationTimeoutMs,
@@ -7,6 +8,10 @@ import {
78
import { withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
89

910
export const MSTEAMS_REQUEST_TIMEOUT_MS = 30_000;
11+
// File-consent PUTs are data-plane transfers: keep a base stall bound, then
12+
// add slow-transfer budget so valid large uploads do not hit a fixed cutoff.
13+
const MSTEAMS_SHAREPOINT_UPLOAD_BASE_TIMEOUT_MS = 5 * 60_000;
14+
const MSTEAMS_SHAREPOINT_UPLOAD_MIN_BYTES_PER_SECOND = 256 * 1024;
1015

1116
// Cap optional enrichment before agent dispatch. The Teams SDK still holds the
1217
// webhook open for the agent turn, so this budget alone cannot prevent retries.
@@ -39,3 +44,15 @@ export async function withMSTeamsRequestDeadline<T>(params: {
3944
const timeoutMs = resolveMSTeamsRequestTimeoutMs(params.deadline);
4045
return await withTimeout(params.work(), timeoutMs, params.label);
4146
}
47+
48+
export function resolveMSTeamsSharePointUploadTimeoutMs(sizeInBytes: number): number {
49+
const bytes = Number.isFinite(sizeInBytes) && sizeInBytes > 0 ? Math.ceil(sizeInBytes) : 0;
50+
const transferBudgetMs = Math.ceil(
51+
(bytes / MSTEAMS_SHAREPOINT_UPLOAD_MIN_BYTES_PER_SECOND) * 1000,
52+
);
53+
return resolveTimerTimeoutMs(
54+
MSTEAMS_SHAREPOINT_UPLOAD_BASE_TIMEOUT_MS + transferBudgetMs,
55+
MSTEAMS_SHAREPOINT_UPLOAD_BASE_TIMEOUT_MS,
56+
1,
57+
);
58+
}

0 commit comments

Comments
 (0)