session-id.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import { describe, expect, it } from "vitest";
  2. import { createCliSessionControl } from "#session-control/application/cli/index";
  3. import { createAppSessionControl } from "#session-control/application/app/index";
  4. import { createOperationFeed, createTestPorts } from "#session-control/testing/index";
  5. import { z } from "zod";
  6. import {
  7. appReadSessionInputSchema,
  8. appRenameSessionInputSchema,
  9. appWaitSessionsInputSchema,
  10. cliReadSessionInputSchema,
  11. cliSendToSessionInputSchema,
  12. type AppSessionRef,
  13. type CliSessionRef,
  14. cliListSessionsInputSchema,
  15. } from "#session-control/contract";
  16. // 会话 ID 写法:与完整引用二选一,由可信端口解析后沿原有授权与 owner 校验执行。
  17. const cliRoot: CliSessionRef = { kind: "cli", workspacePath: "/workspace", sessionId: "sess_root" };
  18. const appRoot: AppSessionRef = {
  19. kind: "app",
  20. workspacePath: "/workspace",
  21. sourceServerId: "source-a",
  22. sessionId: "sess_root",
  23. };
  24. function cli() {
  25. const ports = createTestPorts("cli", cliRoot);
  26. return { ports, ctx: ports.context, control: createCliSessionControl(ports.cli) };
  27. }
  28. function app() {
  29. const ports = createTestPorts("app", appRoot);
  30. return { ports, ctx: ports.context, control: createAppSessionControl(ports.app) };
  31. }
  32. describe("sessionId target", () => {
  33. it("resolves sessionId through the trusted port before authorizing and calling the owner", async () => {
  34. const { control, ctx, ports } = cli();
  35. await control.sendToSession(ctx, { sessionId: "sess_target", prompt: "go", requestId: "r" });
  36. expect(ports.calls.map((call) => call.method)).toEqual([
  37. "resolveSession",
  38. "authorize",
  39. "sendToSession",
  40. ]);
  41. // owner 收到的是解析后的完整引用,不再带 sessionId。
  42. expect(ports.calls.at(-1)?.input).toEqual({
  43. session: { ...cliRoot, sessionId: "sess_target" },
  44. prompt: "go",
  45. requestId: "r",
  46. });
  47. });
  48. it("requires exactly one of session or sessionId on every target tool", async () => {
  49. const { control, ctx, ports } = app();
  50. const session = { ...appRoot, sessionId: "sess_target" };
  51. await expect(
  52. control.readSession(ctx, { session, sessionId: "sess_target", view: "summary" }),
  53. ).rejects.toMatchObject({ code: "invalid_input" });
  54. await expect(control.readSession(ctx, { view: "summary" })).rejects.toMatchObject({
  55. code: "invalid_input",
  56. });
  57. await expect(
  58. control.setSessionPinned(ctx, { pinned: true, requestId: "r" }),
  59. ).rejects.toMatchObject({ code: "invalid_input" });
  60. expect(ports.calls).toEqual([]);
  61. });
  62. it("reports an unknown ID as outside the trusted scope without reaching the owner", async () => {
  63. const { control, ctx, ports } = app();
  64. await expect(
  65. control.renameSession(ctx, { sessionId: "sess_missing-1", title: "x", requestId: "r" }),
  66. ).rejects.toMatchObject({ code: "forbidden" });
  67. expect(ports.calls.map((call) => call.method)).toEqual(["resolveSession"]);
  68. });
  69. // 规格 0.10:模型只有裸 ID 时仍自造 session 引用,被拒后只看到结果、不知道下一步。
  70. // 传 session 被拒时追加固定引导;传 sessionId 被拒时不加,避免暗示该 ID 存在于别处。
  71. it("tells a caller that guessed a full reference to use sessionId instead", async () => {
  72. const { control, ctx } = app();
  73. const foreign = { ...appRoot, sessionId: "sess_guessed", workspacePath: "/elsewhere" };
  74. await expect(
  75. control.readSession(ctx, { session: foreign, view: "summary" }),
  76. ).rejects.toMatchObject({
  77. code: "forbidden",
  78. message: expect.stringContaining("sessionId"),
  79. });
  80. });
  81. it("does not add the sessionId hint when the caller already used sessionId", async () => {
  82. const { control, ctx } = app();
  83. await expect(
  84. control.readSession(ctx, { sessionId: "sess_missing-hint", view: "summary" }),
  85. ).rejects.toMatchObject({ code: "forbidden" });
  86. await expect(
  87. control.readSession(ctx, { sessionId: "sess_missing-hint", view: "summary" }),
  88. ).rejects.not.toMatchObject({ message: expect.stringContaining("Pass only the session id") });
  89. });
  90. it("rejects a resolver that returns a different session", async () => {
  91. const { control, ctx, ports } = app();
  92. ports.app.sessions.resolveSession = async () => ({ ...appRoot, sessionId: "sess_other" });
  93. await expect(
  94. control.readSession(ctx, { sessionId: "sess_target", view: "summary" }),
  95. ).rejects.toMatchObject({ code: "invalid_output" });
  96. });
  97. it("keeps full references working unchanged and never calls the resolver for them", async () => {
  98. const { control, ctx, ports } = app();
  99. await control.openSession(ctx, { session: { ...appRoot, sessionId: "sess_target" } });
  100. expect(ports.calls.map((call) => call.method)).toEqual(["authorize", "openSession"]);
  101. });
  102. it("accepts sessionId on each wait operation and still rejects self-wait", async () => {
  103. const { control, ctx, ports } = cli();
  104. ports.cli.observations.open = async (_ctx, operation) =>
  105. createOperationFeed({ operation, epoch: "e", revision: 0, status: "completed" });
  106. await expect(
  107. control.waitSessions(ctx, {
  108. operations: [{ sessionId: "sess_target", commandId: "c" }],
  109. mode: "all",
  110. timeoutMs: 0,
  111. }),
  112. ).resolves.toMatchObject({
  113. status: "completed",
  114. operations: [{ operation: { session: { sessionId: "sess_target" }, commandId: "c" } }],
  115. });
  116. await expect(
  117. control.waitSessions(ctx, {
  118. operations: [{ sessionId: "sess_root", commandId: "future" }],
  119. mode: "all",
  120. }),
  121. ).rejects.toMatchObject({ code: "self_wait" });
  122. await expect(
  123. control.waitSessions(ctx, {
  124. operations: [{ commandId: "c" }],
  125. mode: "all",
  126. } as never),
  127. ).rejects.toMatchObject({ code: "invalid_input" });
  128. });
  129. });
  130. // 规格 0.11:工具层只暴露 sessionId。模型曾把两个字段都当必填并用 "dummy" 补齐完整引用,
  131. // 一整轮调用因此全部失败;多传 session 必须被明确拒绝,不能静默忽略。
  132. describe("model-facing target schema", () => {
  133. const targets = [
  134. ["app read", appReadSessionInputSchema],
  135. ["app rename", appRenameSessionInputSchema],
  136. ["cli read", cliReadSessionInputSchema],
  137. ["cli send", cliSendToSessionInputSchema],
  138. ] as const;
  139. it.each(targets)("%s exposes sessionId only", (_name, schema) => {
  140. const tool = (schema as unknown as { tool: { safeParse(v: unknown): { success: boolean } } })
  141. .tool;
  142. expect(tool).toBeDefined();
  143. const properties = Object.keys(
  144. (z.toJSONSchema(tool as never) as { properties?: Record<string, unknown> }).properties ?? {},
  145. );
  146. expect(properties).toContain("sessionId");
  147. expect(properties).not.toContain("session");
  148. });
  149. // 会话 ID 有两种历史格式,都是真实身份(本机库实测 sess_ 6006 个、session_ 139 个),
  150. // 必须按原样精确查找,不能改写前缀。占位值要在 schema 这层就被挡住,而不是拖到授权才报越权。
  151. it.each([
  152. ["current sess_ form", "sess_159c9866-62b8-4e86-ba6f-e1bf544e859c", true],
  153. ["legacy session_ 32hex", "session_18f18883641b08761914d1f73bebeb5f", true],
  154. ["legacy session_ uuid", "session_12345678-1234-4234-8234-123456789abc", true],
  155. ["placeholder", "dummy", false],
  156. ["title instead of id", "创建 Markdown 语法示例文档", false],
  157. ["bare uuid without prefix", "159c9866-62b8-4e86-ba6f-e1bf544e859c", false],
  158. ["empty suffix", "sess_", false],
  159. ["path traversal", "sess_../escape", false],
  160. ] as const)("accepts %s: %s", (_name, sessionId, ok) => {
  161. const tool = (
  162. appReadSessionInputSchema as unknown as { tool: typeof appReadSessionInputSchema }
  163. ).tool;
  164. expect(tool.safeParse({ sessionId, view: "summary" }).success).toBe(ok);
  165. });
  166. it("rejects a caller that also sends a full reference", () => {
  167. const tool = (
  168. appReadSessionInputSchema as unknown as { tool: typeof appReadSessionInputSchema }
  169. ).tool;
  170. expect(tool.safeParse({ sessionId: "sess_s-1", view: "summary" }).success).toBe(true);
  171. // 旧行为下模型会补一个 dummy 引用;strictObject 必须直接拒绝,而不是忽略该字段。
  172. expect(
  173. tool.safeParse({
  174. sessionId: "sess_s-1",
  175. view: "summary",
  176. session: {
  177. kind: "app",
  178. sessionId: "dummy",
  179. sourceServerId: "dummy",
  180. workspacePath: "dummy",
  181. },
  182. }).success,
  183. ).toBe(false);
  184. expect(tool.safeParse({ view: "summary" }).success).toBe(false);
  185. });
  186. it("exposes wait operations without a full reference", () => {
  187. const tool = (
  188. appWaitSessionsInputSchema as unknown as { tool: typeof appWaitSessionsInputSchema }
  189. ).tool;
  190. expect(
  191. tool.safeParse({ operations: [{ sessionId: "sess_s-1", commandId: "c-1" }], mode: "all" })
  192. .success,
  193. ).toBe(true);
  194. // 规格 0.14:回执里的 operation 同时带 session 与 sessionId,必须能原样放回来——
  195. // 多出来的 session 被剥掉,而不是拒绝整次调用。
  196. const replayed = tool.safeParse({
  197. operations: [
  198. {
  199. sessionId: "sess_s-1",
  200. commandId: "c-1",
  201. session: { kind: "app", sessionId: "sess_s-1" },
  202. },
  203. ],
  204. mode: "all",
  205. });
  206. expect(replayed.success).toBe(true);
  207. expect(replayed.data?.operations[0]).toEqual({ sessionId: "sess_s-1", commandId: "c-1" });
  208. });
  209. });
  210. describe("standalone CLI read scope", () => {
  211. const otherWorkspace: CliSessionRef = {
  212. kind: "cli",
  213. workspacePath: "/elsewhere",
  214. sessionId: "sess_history",
  215. };
  216. it("reads a session from another workspace only when the trusted context grants local reads", async () => {
  217. const { control, ctx, ports } = cli();
  218. ports.cli.sessions.resolveSession = async () => otherWorkspace;
  219. await expect(
  220. control.readSession(ctx, { sessionId: "sess_history", view: "messages" }),
  221. ).rejects.toMatchObject({ code: "forbidden" });
  222. const reader = { ...ctx, readAnyLocalSession: true };
  223. await expect(
  224. control.readSession(reader, { sessionId: "sess_history", view: "messages" }),
  225. ).resolves.toMatchObject({ view: "messages", session: otherWorkspace });
  226. });
  227. it("does not widen write access to other workspaces", async () => {
  228. const { control, ctx, ports } = cli();
  229. ports.cli.sessions.resolveSession = async () => otherWorkspace;
  230. const reader = { ...ctx, readAnyLocalSession: true };
  231. await expect(
  232. control.renameSession(reader, { sessionId: "sess_history", title: "x", requestId: "r" }),
  233. ).rejects.toMatchObject({ code: "forbidden" });
  234. await expect(
  235. control.sendToSession(reader, { sessionId: "sess_history", prompt: "go", requestId: "r" }),
  236. ).rejects.toMatchObject({ code: "forbidden" });
  237. expect(ports.calls.some((call) => call.method === "sendToSession")).toBe(false);
  238. });
  239. // 规格 0.14:workspace 过滤器已从工具面删除(发现链循环)。只读全库授权在场时读整个本机会话库,
  240. // 不在场时仍收窄到绑定 workspace 并复验返回行。
  241. it("lists the whole local store with the read grant and narrows to the bound workspace without it", async () => {
  242. const { control, ctx, ports } = cli();
  243. const reader = { ...ctx, readAnyLocalSession: true };
  244. ports.cli.sessions.listSessions = async () => ({
  245. sessions: [
  246. {
  247. session: otherWorkspace,
  248. title: "t",
  249. status: "unknown",
  250. availableActions: ["readSession"],
  251. },
  252. ],
  253. });
  254. await expect(control.listSessions(reader, {})).resolves.toMatchObject({
  255. sessions: [{ session: otherWorkspace }],
  256. });
  257. // 没有只读全库授权时,返回行必须落在绑定 workspace 内。
  258. await expect(control.listSessions(ctx, {})).rejects.toMatchObject({ code: "invalid_output" });
  259. expect(
  260. cliListSessionsInputSchema.safeParse({ workspace: { kind: "cli", workspacePath: "/w" } })
  261. .success,
  262. ).toBe(false);
  263. });
  264. });