Skip to content

Commit bd15d91

Browse files
authored
fix(feishu): validate document API outcomes before reporting success (#135106)
1 parent d4354ff commit bd15d91

2 files changed

Lines changed: 253 additions & 71 deletions

File tree

‎extensions/feishu/src/docx-create-loopback.test.ts‎

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import { createToolFactoryHarness } from "./tool-factory-test-harness.js";
77

88
const createFeishuClientMock = vi.hoisted(() => vi.fn());
9+
const readRemoteMediaBufferMock = vi.hoisted(() => vi.fn());
910
const toolAccountModule = await import("./tool-account.js");
11+
const runtimeModule = await import("./runtime.js");
1012

1113
vi.spyOn(toolAccountModule, "createFeishuToolClient").mockImplementation(() =>
1214
createFeishuClientMock(),
@@ -23,6 +25,9 @@ vi.spyOn(toolAccountModule, "resolveAnyEnabledFeishuToolsConfig").mockReturnValu
2325
vi.spyOn(toolAccountModule, "resolveFeishuToolAccount").mockReturnValue({
2426
config: { mediaMaxMb: 30 },
2527
} as ReturnType<typeof toolAccountModule.resolveFeishuToolAccount>);
28+
vi.spyOn(runtimeModule, "getFeishuRuntime").mockReturnValue({
29+
channel: { media: { readRemoteMediaBuffer: readRemoteMediaBufferMock } },
30+
} as unknown as ReturnType<typeof runtimeModule.getFeishuRuntime>);
2631

2732
const { registerFeishuDocTools } = await import("./docx.js");
2833

@@ -34,6 +39,10 @@ describe("feishu_doc contract over the real Lark SDK", () => {
3439

3540
beforeEach(() => {
3641
vi.clearAllMocks();
42+
readRemoteMediaBufferMock.mockResolvedValue({
43+
buffer: Buffer.from("loopback image", "utf8"),
44+
fileName: "loopback.png",
45+
});
3746
});
3847

3948
it("rejects create content before HTTP and supports the create-then-write API workflow", async () => {
@@ -306,4 +315,215 @@ describe("feishu_doc contract over the real Lark SDK", () => {
306315
}
307316
},
308317
);
318+
319+
it("reports fulfilled nonzero image and permission responses as partial failures", async () => {
320+
const requests: Array<{ method: string; path: string; body?: string }> = [];
321+
const patchResponses = [
322+
{ code: 230001, msg: "replace rejected" },
323+
{ code: 0, data: { block: { block_id: "image_two", block_type: 27 } } },
324+
];
325+
const server = createServer((request, response) => {
326+
void (async () => {
327+
const bodyChunks: Buffer[] = [];
328+
for await (const chunk of request) {
329+
bodyChunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
330+
}
331+
const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
332+
const rawBody = Buffer.concat(bodyChunks).toString("utf8");
333+
requests.push({
334+
method: request.method ?? "",
335+
path: pathname,
336+
...(rawBody ? { body: rawBody } : {}),
337+
});
338+
339+
const sendJson = (body: unknown) => {
340+
response.writeHead(200, { "content-type": "application/json" });
341+
response.end(JSON.stringify(body));
342+
};
343+
if (request.method === "POST" && pathname === "/open-apis/docx/v1/documents") {
344+
const title = (JSON.parse(rawBody) as { title?: string }).title;
345+
sendJson({
346+
code: 0,
347+
data: {
348+
document: {
349+
document_id: title === "Permission OK" ? "doc_permission_ok" : "doc_permission_no",
350+
title,
351+
},
352+
},
353+
});
354+
return;
355+
}
356+
if (
357+
request.method === "POST" &&
358+
pathname === "/open-apis/drive/v1/permissions/doc_permission_ok/members"
359+
) {
360+
sendJson({ code: 0, data: { member: { member_id: "ou_requester" } } });
361+
return;
362+
}
363+
if (
364+
request.method === "POST" &&
365+
pathname === "/open-apis/drive/v1/permissions/doc_permission_no/members"
366+
) {
367+
sendJson({ code: 999, msg: "grant denied" });
368+
return;
369+
}
370+
if (
371+
request.method === "POST" &&
372+
pathname === "/open-apis/docx/v1/documents/blocks/convert"
373+
) {
374+
sendJson({
375+
code: 0,
376+
data: {
377+
blocks: [
378+
{ block_type: 27, block_id: "image_one" },
379+
{ block_type: 27, block_id: "image_two" },
380+
],
381+
first_level_block_ids: ["image_one", "image_two"],
382+
},
383+
});
384+
return;
385+
}
386+
if (
387+
request.method === "GET" &&
388+
pathname === "/open-apis/docx/v1/documents/doc_images/blocks"
389+
) {
390+
sendJson({ code: 0, data: { items: [] } });
391+
return;
392+
}
393+
if (
394+
request.method === "POST" &&
395+
pathname === "/open-apis/docx/v1/documents/doc_images/blocks/doc_images/descendant"
396+
) {
397+
sendJson({
398+
code: 0,
399+
data: {
400+
children: [
401+
{ block_type: 27, block_id: "image_one" },
402+
{ block_type: 27, block_id: "image_two" },
403+
],
404+
},
405+
});
406+
return;
407+
}
408+
if (request.method === "POST" && pathname === "/open-apis/drive/v1/medias/upload_all") {
409+
sendJson({ code: 0, data: { file_token: `file_${requests.length}` } });
410+
return;
411+
}
412+
if (
413+
request.method === "PATCH" &&
414+
pathname.startsWith("/open-apis/docx/v1/documents/doc_images/blocks/image_")
415+
) {
416+
sendJson(patchResponses.shift());
417+
return;
418+
}
419+
response.writeHead(404).end();
420+
})().catch((error: unknown) => {
421+
response.writeHead(500, { "content-type": "application/json" });
422+
response.end(JSON.stringify({ error: String(error) }));
423+
});
424+
});
425+
426+
await new Promise<void>((resolve, reject) => {
427+
server.once("error", reject);
428+
server.listen(0, "127.0.0.1", resolve);
429+
});
430+
431+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
432+
try {
433+
const address = server.address() as AddressInfo;
434+
const loopbackHttp = Object.create(Lark.defaultHttpInstance) as Lark.HttpInstance;
435+
loopbackHttp.request = async (options) => {
436+
const upstream = new URL(options.url ?? "");
437+
const target = new URL(
438+
`${upstream.pathname}${upstream.search}`,
439+
`http://127.0.0.1:${address.port}`,
440+
);
441+
const method = options.method ?? "GET";
442+
const response = await fetch(target, {
443+
method,
444+
headers: { "content-type": "application/json" },
445+
...(method === "GET" || method === "HEAD"
446+
? {}
447+
: { body: JSON.stringify(options.data ?? {}) }),
448+
});
449+
return response.json();
450+
};
451+
createFeishuClientMock.mockReturnValue(
452+
new Lark.Client({
453+
appId: "loopback-test-app",
454+
appSecret: "loopback-test-placeholder", // pragma: allowlist secret
455+
domain: Lark.Domain.Feishu,
456+
loggerLevel: Lark.LoggerLevel.error,
457+
disableTokenCache: true,
458+
httpInstance: loopbackHttp,
459+
}),
460+
);
461+
462+
const harness = createToolFactoryHarness({
463+
channels: {
464+
feishu: { enabled: true, appId: "app_id", appSecret: "app_secret" },
465+
},
466+
});
467+
registerFeishuDocTools(harness.api);
468+
const requesterContext = {
469+
messageChannel: "feishu",
470+
requesterSenderId: "ou_requester",
471+
} as Parameters<typeof harness.resolveTool>[1] & {
472+
messageChannel: string;
473+
requesterSenderId: string;
474+
};
475+
const tool = harness.resolveTool("feishu_doc", requesterContext);
476+
477+
const permissionOk = await tool.execute("permission-ok", {
478+
action: "create",
479+
title: "Permission OK",
480+
});
481+
expect(JSON.stringify(permissionOk.details)).toBe(
482+
'{"document_id":"doc_permission_ok","title":"Permission OK","url":"https://feishu.cn/docx/doc_permission_ok","requester_permission_added":true,"requester_open_id":"ou_requester","requester_perm_type":"edit"}',
483+
);
484+
485+
const permissionDenied = await tool.execute("permission-denied", {
486+
action: "create",
487+
title: "Permission Denied",
488+
});
489+
expect
490+
.soft(JSON.stringify(permissionDenied.details))
491+
.toBe(
492+
'{"document_id":"doc_permission_no","title":"Permission Denied","url":"https://feishu.cn/docx/doc_permission_no","requester_permission_added":false,"requester_open_id":"ou_requester","requester_perm_type":"edit","requester_permission_error":"grant denied"}',
493+
);
494+
495+
const imageWrite = await tool.execute("image-write", {
496+
action: "write",
497+
doc_token: "doc_images",
498+
content: "![one](https://cdn.test/one.png)\n![two](https://cdn.test/two.png)",
499+
});
500+
expect
501+
.soft(JSON.stringify(imageWrite.details))
502+
.toBe('{"success":true,"blocks_deleted":0,"blocks_added":2,"images_processed":1}');
503+
expect(readRemoteMediaBufferMock).toHaveBeenCalledTimes(2);
504+
expect(
505+
requests.filter((request) => request.method === "PATCH").map((request) => request.path),
506+
).toEqual([
507+
"/open-apis/docx/v1/documents/doc_images/blocks/image_one",
508+
"/open-apis/docx/v1/documents/doc_images/blocks/image_two",
509+
]);
510+
expect(consoleErrorSpy).toHaveBeenCalledWith(
511+
"Failed to process image https://cdn.test/one.png:",
512+
expect.objectContaining({ message: "replace rejected" }),
513+
);
514+
expect(
515+
requests
516+
.filter((request) => request.path.includes("/permissions/"))
517+
.map((request) => request.body),
518+
).toEqual([
519+
'{"member_type":"openid","member_id":"ou_requester","perm":"edit"}',
520+
'{"member_type":"openid","member_id":"ou_requester","perm":"edit"}',
521+
]);
522+
} finally {
523+
consoleErrorSpy.mockRestore();
524+
await new Promise<void>((resolve, reject) => {
525+
server.close((error) => (error ? reject(error) : resolve()));
526+
});
527+
}
528+
});
309529
});

0 commit comments

Comments
 (0)