Skip to content

Commit c37c2c9

Browse files
steipetevincentkoc
authored andcommitted
fix(msteams): release every guarded Graph response safely
1 parent 105500d commit c37c2c9

2 files changed

Lines changed: 60 additions & 14 deletions

File tree

‎extensions/msteams/src/attachments/graph.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,56 @@ describe("downloadMSTeamsGraphMedia hosted content $value fallback", () => {
297297
expect(failedMessageResponse.bodyUsed).toBe(true);
298298
});
299299

300+
it("releases a cloned failed collection body without awaiting stalled cancellation", async () => {
301+
const failedCollectionResponse = new Response("server error", { status: 500 });
302+
const captureClone = failedCollectionResponse.clone();
303+
const body = failedCollectionResponse.body;
304+
if (!body) {
305+
throw new Error("expected a readable collection error body");
306+
}
307+
const originalCancel = body.cancel.bind(body);
308+
let cancellation: Promise<void> | undefined;
309+
let cancellationSettled = false;
310+
const cancellationStarted = new Promise<void>((resolve) => {
311+
vi.spyOn(body, "cancel").mockImplementation((reason) => {
312+
cancellation = originalCancel(reason).finally(() => {
313+
cancellationSettled = true;
314+
});
315+
resolve();
316+
return cancellation;
317+
});
318+
});
319+
const release = vi.fn(async () => {});
320+
vi.mocked(fetchWithSsrFGuard).mockImplementation(async (params: GuardedFetchParams) => {
321+
if (params.url.endsWith("/hostedContents")) {
322+
return guardedFetchResult(params, failedCollectionResponse, release);
323+
}
324+
return guardedFetchResult(params, mockFetchResponse({ body: {}, attachments: [] }));
325+
});
326+
327+
const operation = downloadMSTeamsGraphMedia({
328+
messageUrl: "https://graph.microsoft.com/v1.0/chats/c/messages/msg-cloned-collection",
329+
tokenProvider: { getAccessToken: vi.fn(async () => "test-token") },
330+
maxBytes: 10 * 1024 * 1024,
331+
});
332+
333+
try {
334+
await cancellationStarted;
335+
expect(release).toHaveBeenCalledOnce();
336+
expect(failedCollectionResponse.bodyUsed).toBe(true);
337+
expect(cancellationSettled).toBe(false);
338+
await expect(operation).resolves.toMatchObject({
339+
media: [],
340+
hostedCount: 0,
341+
hostedStatus: 500,
342+
});
343+
} finally {
344+
void captureClone.body?.cancel().catch(() => undefined);
345+
await cancellation?.catch(() => undefined);
346+
await operation.catch(() => undefined);
347+
}
348+
});
349+
300350
it("ignores unexpected inline bytes and still fetches bounded $value", async () => {
301351
const fetchCalls: string[] = [];
302352
const base64Png = Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString("base64");

‎extensions/msteams/src/attachments/graph.ts‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,13 @@ export function buildMSTeamsGraphMessageUrl(params: {
9999
return `${GRAPH_ROOT}/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(messageId)}`;
100100
}
101101

102+
async function releaseGraphResponse(response: Response, release: () => Promise<void>) {
103+
if (!response.bodyUsed) {
104+
void response.body?.cancel().catch(() => undefined); // Awaiting capture tees can deadlock.
105+
}
106+
await release();
107+
}
108+
102109
async function fetchGraphCollection(params: {
103110
url: string;
104111
accessToken: string;
@@ -120,7 +127,6 @@ async function fetchGraphCollection(params: {
120127
try {
121128
const status = response.status;
122129
if (!response.ok) {
123-
await response.body?.cancel().catch(() => undefined);
124130
return { status, items: [] };
125131
}
126132
try {
@@ -134,7 +140,7 @@ async function fetchGraphCollection(params: {
134140
return { status, items: [] };
135141
}
136142
} finally {
137-
await release();
143+
await releaseGraphResponse(response, release);
138144
}
139145
}
140146

@@ -229,12 +235,7 @@ async function downloadGraphHostedContent(params: {
229235
sourceId: item.id,
230236
});
231237
} finally {
232-
// Guard release does not consume unread bodies. Start cancellation first;
233-
// awaiting can deadlock when response capture tees the stream.
234-
if (!valRes.bodyUsed) {
235-
void valRes.body?.cancel().catch(() => undefined);
236-
}
237-
await release();
238+
await releaseGraphResponse(valRes, release);
238239
}
239240
} catch (err) {
240241
out.push(createGraphHostedContentFact(item));
@@ -343,12 +344,7 @@ export async function downloadMSTeamsGraphMedia(params: {
343344
});
344345
}
345346
} finally {
346-
// Guard release does not consume unread bodies. Start cancellation first;
347-
// awaiting can deadlock when response capture tees the stream.
348-
if (!msgRes.bodyUsed) {
349-
void msgRes.body?.cancel().catch(() => undefined);
350-
}
351-
await release();
347+
await releaseGraphResponse(msgRes, release);
352348
}
353349
} catch (err) {
354350
params.logger?.debug?.("graph media message fetch failed", {

0 commit comments

Comments
 (0)