mcp-oauth-lease.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import { spawn } from "node:child_process";
  2. import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createSharedZCodeCredentialStore } from "../src/auth/shared-credentials.js";
  7. import {
  8. deletePendingAuthorizationIfOwned,
  9. loadPendingAuthorization,
  10. publishPendingAuthorization,
  11. resolveAuthorizationLeasePath,
  12. tryAcquireAuthorizationLease,
  13. } from "../src/mcp/oauth-lease.js";
  14. const KEY_PREFIX = "mcp:oauth:c50fd1fa63fb88a233be0688";
  15. const temporaryDirectories: string[] = [];
  16. const spawnedPids: number[] = [];
  17. afterEach(async () => {
  18. for (const pid of spawnedPids.splice(0)) {
  19. try {
  20. process.kill(pid, "SIGKILL");
  21. } catch {
  22. // 已退出
  23. }
  24. }
  25. await Promise.all(
  26. temporaryDirectories
  27. .splice(0)
  28. .map((directory) => rm(directory, { force: true, recursive: true })),
  29. );
  30. });
  31. async function createCredentialsPath(): Promise<string> {
  32. const directory = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-lease-"));
  33. temporaryDirectories.push(directory);
  34. return join(directory, "credentials.json");
  35. }
  36. /** 起一个真实的长驻子进程,只为拿到一个确定存活、随后可被杀死的 PID。 */
  37. async function spawnIdleProcess(): Promise<number> {
  38. const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60_000)"], {
  39. stdio: "ignore",
  40. });
  41. await new Promise<void>((resolve, reject) => {
  42. child.once("spawn", resolve);
  43. child.once("error", reject);
  44. });
  45. const pid = child.pid;
  46. if (pid === undefined) throw new Error("Failed to spawn helper process");
  47. spawnedPids.push(pid);
  48. return pid;
  49. }
  50. /**
  51. * 按 `acquireFileLock` 的磁盘格式写一把属于 `pid` 的锁。
  52. *
  53. * 跨进程互斥的契约就是这份磁盘布局,因此直接构造它比在子进程里加载 TS 模块更贴近被测行为。
  54. */
  55. async function writeForeignLease(leasePath: string, pid: number): Promise<void> {
  56. const lockDirectory = `${leasePath}.lock`;
  57. await mkdir(lockDirectory, { recursive: true });
  58. await writeFile(
  59. join(lockDirectory, `owner-${pid}-foreign.json`),
  60. `${JSON.stringify({ pid, createdAt: Date.now(), token: `${pid}-foreign` })}\n`,
  61. "utf-8",
  62. );
  63. }
  64. describe("MCP OAuth authorization lease", () => {
  65. it("uses a lease path whose basename is legal on Windows", async () => {
  66. const credentialsPath = await createCredentialsPath();
  67. const leasePath = resolveAuthorizationLeasePath(credentialsPath, KEY_PREFIX);
  68. // credential key prefix 形如 `mcp:oauth:<hash>`;冒号在 Windows 文件名中非法,
  69. // 直接拼进锁路径会让整个授权流程在 Windows 上失败。
  70. expect(leasePath).not.toContain(":");
  71. expect(leasePath.endsWith(".authz")).toBe(true);
  72. });
  73. it("grants the lease to exactly one holder and releases it again", async () => {
  74. const credentialsPath = await createCredentialsPath();
  75. const first = await tryAcquireAuthorizationLease({
  76. credentialsFilePath: credentialsPath,
  77. keyPrefix: KEY_PREFIX,
  78. });
  79. expect(first).toBeDefined();
  80. const second = await tryAcquireAuthorizationLease({
  81. credentialsFilePath: credentialsPath,
  82. keyPrefix: KEY_PREFIX,
  83. });
  84. expect(second).toBeUndefined();
  85. await first?.release();
  86. const third = await tryAcquireAuthorizationLease({
  87. credentialsFilePath: credentialsPath,
  88. keyPrefix: KEY_PREFIX,
  89. });
  90. expect(third).toBeDefined();
  91. expect(third?.attemptId).not.toBe(first?.attemptId);
  92. await third?.release();
  93. });
  94. it("does not steal a lease held by a live process, and reclaims it once that process dies", async () => {
  95. const credentialsPath = await createCredentialsPath();
  96. const leasePath = resolveAuthorizationLeasePath(credentialsPath, KEY_PREFIX);
  97. const holderPid = await spawnIdleProcess();
  98. await writeForeignLease(leasePath, holderPid);
  99. const contended = await tryAcquireAuthorizationLease({
  100. credentialsFilePath: credentialsPath,
  101. keyPrefix: KEY_PREFIX,
  102. });
  103. expect(contended).toBeUndefined();
  104. process.kill(holderPid, "SIGKILL");
  105. await new Promise((resolve) => setTimeout(resolve, 50));
  106. // Bug 回归:零等待预算会让 `acquireFileLock` 在竞争时直接超时,永远不执行 owner-dead
  107. // 回收;持锁进程崩溃后授权功能将永久不可用。
  108. const reclaimed = await tryAcquireAuthorizationLease({
  109. credentialsFilePath: credentialsPath,
  110. keyPrefix: KEY_PREFIX,
  111. });
  112. expect(reclaimed).toBeDefined();
  113. await reclaimed?.release();
  114. await expect(readdir(`${leasePath}.lock`)).rejects.toMatchObject({ code: "ENOENT" });
  115. });
  116. });
  117. describe("MCP OAuth pending authorization record", () => {
  118. it("only lets the owning attempt delete the pending record", async () => {
  119. const credentialsPath = await createCredentialsPath();
  120. const credentialStore = createSharedZCodeCredentialStore({
  121. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-pending-secret" },
  122. filePath: credentialsPath,
  123. });
  124. await publishPendingAuthorization(credentialStore, KEY_PREFIX, {
  125. attemptId: "attempt-new",
  126. authorizationUrl: "https://auth.example.test/authorize?state=new",
  127. baselineGeneration: "generation-0",
  128. expiresAt: Date.now() + 60_000,
  129. state: "state-new",
  130. });
  131. // Bug 回归:旧 leader 的 finally 若无条件删除 pending,会抹掉新 leader 刚发布的记录,
  132. // follower 随即失去授权 URL。删除必须按 attempt CAS。
  133. await expect(
  134. deletePendingAuthorizationIfOwned(credentialStore, KEY_PREFIX, "attempt-stale"),
  135. ).resolves.toBe(false);
  136. await expect(loadPendingAuthorization(credentialStore, KEY_PREFIX)).resolves.toMatchObject({
  137. attemptId: "attempt-new",
  138. authorizationUrl: "https://auth.example.test/authorize?state=new",
  139. });
  140. await expect(
  141. deletePendingAuthorizationIfOwned(credentialStore, KEY_PREFIX, "attempt-new"),
  142. ).resolves.toBe(true);
  143. await expect(loadPendingAuthorization(credentialStore, KEY_PREFIX)).resolves.toBeUndefined();
  144. });
  145. it("hides an expired pending record without deleting it", async () => {
  146. const credentialsPath = await createCredentialsPath();
  147. const credentialStore = createSharedZCodeCredentialStore({
  148. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-pending-expiry-secret" },
  149. filePath: credentialsPath,
  150. });
  151. await publishPendingAuthorization(credentialStore, KEY_PREFIX, {
  152. attemptId: "attempt-expired",
  153. authorizationUrl: "https://auth.example.test/authorize?state=expired",
  154. expiresAt: Date.now() - 1,
  155. state: "state-expired",
  156. });
  157. // TTL 只用于展示过期判断,不承担锁所有权语义:过期记录对读取方不可见,但仍只能由
  158. // 归属 attempt 清理。
  159. await expect(loadPendingAuthorization(credentialStore, KEY_PREFIX)).resolves.toBeUndefined();
  160. await expect(
  161. deletePendingAuthorizationIfOwned(credentialStore, KEY_PREFIX, "attempt-other"),
  162. ).resolves.toBe(false);
  163. await expect(
  164. deletePendingAuthorizationIfOwned(credentialStore, KEY_PREFIX, "attempt-expired"),
  165. ).resolves.toBe(true);
  166. });
  167. });