botTopicResource.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { BotContextState, BotsStateFile } from "@zcode/shared";
  3. import { readAuthorizedTopicResource } from "../src/bots/topicResource.js";
  4. import {
  5. feishuConfig,
  6. createBotsService,
  7. createCredentialService,
  8. createLegacyTaskService,
  9. createMemoryRepo,
  10. } from "./botsService.fixtures.js";
  11. function setup() {
  12. const group = {
  13. chatId: "chat-a",
  14. name: "Test",
  15. ownerId: "ou_user",
  16. enabled: true,
  17. authorizationId: "auth-a",
  18. taskIds: ["task-a"],
  19. currentOptions: {},
  20. };
  21. const topic: BotContextState = {
  22. botId: "feishu-1",
  23. workspacePath: "/workspace",
  24. workspaceIdentity: "remote:ssh:a",
  25. mode: "task",
  26. activeTaskId: "task-a",
  27. updatedAt: 1,
  28. group: {
  29. ...group,
  30. threadId: "thread-a",
  31. inputs: {
  32. "input-a": {
  33. taskId: "task-a",
  34. admission: "accepted",
  35. source: {
  36. provider: "feishu",
  37. botId: "feishu-1",
  38. chatId: "chat-a",
  39. threadId: "thread-a",
  40. messageId: "mention-a",
  41. senderId: "member",
  42. senderName: "Member",
  43. authorizationId: "auth-a",
  44. topicContext: {
  45. checkpoint: "mention-a",
  46. hasGap: false,
  47. messages: [
  48. {
  49. id: "file-a",
  50. chatId: "chat-a",
  51. threadId: "thread-a",
  52. senderId: "member",
  53. senderType: "user",
  54. text: "[file: example.txt]",
  55. kind: "file",
  56. createdAt: 1,
  57. },
  58. ],
  59. },
  60. },
  61. },
  62. },
  63. },
  64. };
  65. const parent: BotContextState = { ...topic, group: { ...group, historyEnabled: true } };
  66. const state: BotsStateFile = { version: 2, bots: { parent, topic } };
  67. const config = structuredClone(feishuConfig);
  68. const native = {
  69. messageId: "file-a",
  70. chatId: "chat-a",
  71. threadId: "thread-a",
  72. deleted: false,
  73. attachments: [{ kind: "file" as const, filename: "example.txt", providerFileId: "key-a" }],
  74. };
  75. const deps = {
  76. readState: async () => state,
  77. readConfig: async () => config,
  78. readMessage: vi.fn(async () => native),
  79. download: vi.fn(async () => ({
  80. attachment: native.attachments[0]!,
  81. data: new Uint8Array([1, 2]),
  82. })),
  83. };
  84. const request = {
  85. taskId: "task-a",
  86. inputId: "input-a",
  87. messageId: "file-a",
  88. authorizationId: "auth-a",
  89. workspacePath: "/workspace",
  90. workspaceIdentity: "remote:ssh:a",
  91. };
  92. return { topic, parent, config, state, native, deps, request };
  93. }
  94. describe("task-scoped topic resource retrieval", () => {
  95. it("allows an admitted app-authored resource with the same task authorization", async () => {
  96. const { topic, request, deps } = setup();
  97. topic.group!.inputs!["input-a"]!.source.topicContext!.messages[0]!.senderType = "app";
  98. expect((await readAuthorizedTopicResource(request, deps)).data).toEqual(new Uint8Array([1, 2]));
  99. });
  100. it("exposes the authorized download through the service as a transport-ready attachment", async () => {
  101. const { config, state, request } = setup();
  102. config.bots[0]!.feishuAppId = "resource-service-test";
  103. vi.stubGlobal(
  104. "fetch",
  105. vi.fn(async (url: string) => {
  106. if (url.includes("tenant_access_token"))
  107. return Response.json({ code: 0, tenant_access_token: "test-token", expire: 3600 });
  108. if (url.includes("/resources/")) return new Response(new Uint8Array([1, 2]));
  109. return Response.json({
  110. code: 0,
  111. data: {
  112. items: [
  113. {
  114. message_id: "file-a",
  115. chat_id: "chat-a",
  116. thread_id: "thread-a",
  117. msg_type: "file",
  118. body: { content: JSON.stringify({ file_key: "key-a", file_name: "example.txt" }) },
  119. },
  120. ],
  121. },
  122. });
  123. }),
  124. );
  125. const service = createBotsService({
  126. repo: createMemoryRepo(config, state),
  127. credentialService: createCredentialService({ "feishu-secret": "secret" }),
  128. zcodeTaskService: createLegacyTaskService(),
  129. runStartupBackgroundTasks: false,
  130. });
  131. try {
  132. expect(await service.readTopicResource!(request)).toEqual({
  133. kind: "file",
  134. filename: "example.txt",
  135. mimeType: "application/octet-stream",
  136. sizeBytes: 2,
  137. dataBase64: "AQI=",
  138. });
  139. } finally {
  140. await service.disposeAllAndWait();
  141. }
  142. });
  143. it("downloads only an archived resource in the invoking task's topic", async () => {
  144. const { deps, request } = setup();
  145. expect((await readAuthorizedTopicResource(request, deps)).data).toEqual(new Uint8Array([1, 2]));
  146. expect(deps.download).toHaveBeenCalledOnce();
  147. });
  148. it.each([
  149. "task",
  150. "input",
  151. "archive",
  152. "workspace",
  153. "authorization",
  154. "input-authorization",
  155. "legacy-authorization",
  156. "disabled",
  157. "history",
  158. "owner",
  159. ])("rejects invalid %s before native I/O", async (reason) => {
  160. const { request, deps, parent, config, topic } = setup();
  161. if (reason === "task") request.taskId = "other";
  162. if (reason === "input") request.inputId = "other";
  163. if (reason === "archive") request.messageId = "unread";
  164. if (reason === "workspace") request.workspaceIdentity = "remote:ssh:b";
  165. if (reason === "authorization") request.authorizationId = "old";
  166. if (reason === "input-authorization")
  167. topic.group!.inputs!["input-a"]!.source.authorizationId = "old";
  168. if (reason === "legacy-authorization")
  169. delete topic.group!.inputs!["input-a"]!.source.authorizationId;
  170. if (reason === "disabled") parent.group!.enabled = false;
  171. if (reason === "history") parent.group!.historyEnabled = false;
  172. if (reason === "owner") config.bots[0]!.providerUserId = "other";
  173. await expect(readAuthorizedTopicResource(request, deps)).rejects.toThrow();
  174. expect(deps.readMessage).not.toHaveBeenCalled();
  175. expect(deps.download).not.toHaveBeenCalled();
  176. });
  177. it.each(["chatId", "threadId", "messageId", "deleted"] as const)(
  178. "rejects native %s mismatch before download",
  179. async (field) => {
  180. const { request, deps, native } = setup();
  181. if (field === "deleted") native.deleted = true;
  182. else native[field] = "other";
  183. await expect(readAuthorizedTopicResource(request, deps)).rejects.toThrow();
  184. expect(deps.download).not.toHaveBeenCalled();
  185. },
  186. );
  187. it("does not expose downloaded bytes after authorization changes", async () => {
  188. const { request, deps, parent } = setup();
  189. deps.download.mockImplementationOnce(async () => {
  190. parent.group!.authorizationId = "new";
  191. return {
  192. attachment: { kind: "file", filename: "example.txt", providerFileId: "key-a" },
  193. data: new Uint8Array([1]),
  194. };
  195. });
  196. await expect(readAuthorizedTopicResource(request, deps)).rejects.toThrow();
  197. });
  198. it("rechecks authorization after metadata lookup before fetching any bytes", async () => {
  199. const { request, deps, parent, native } = setup();
  200. deps.readMessage.mockImplementationOnce(async () => {
  201. parent.group!.enabled = false;
  202. return native;
  203. });
  204. await expect(readAuthorizedTopicResource(request, deps)).rejects.toThrow();
  205. expect(deps.download).not.toHaveBeenCalled();
  206. });
  207. it.each([-1, 1, 0.5])(
  208. "rejects invalid resource index %s before download",
  209. async (resourceIndex) => {
  210. const { request, deps } = setup();
  211. await expect(
  212. readAuthorizedTopicResource({ ...request, resourceIndex }, deps),
  213. ).rejects.toThrow();
  214. expect(deps.download).not.toHaveBeenCalled();
  215. },
  216. );
  217. it("propagates download failure without returning a partial resource", async () => {
  218. const { request, deps } = setup();
  219. deps.download.mockRejectedValueOnce(new Error("native download failed"));
  220. await expect(readAuthorizedTopicResource(request, deps)).rejects.toThrow(
  221. "native download failed",
  222. );
  223. });
  224. it("rejects cancelled requests before I/O", async () => {
  225. const { request, deps } = setup();
  226. await expect(
  227. readAuthorizedTopicResource({ ...request, signal: AbortSignal.abort() }, deps),
  228. ).rejects.toThrow();
  229. expect(deps.readMessage).not.toHaveBeenCalled();
  230. });
  231. });