mcp-oauth.e2e.test.ts 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  1. import { createHash } from "node:crypto";
  2. import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
  3. import { Buffer } from "node:buffer";
  4. import { mkdtemp, rm } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import type {
  8. OAuthClientInformationMixed,
  9. OAuthTokens,
  10. } from "@modelcontextprotocol/sdk/shared/auth.js";
  11. import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
  12. import type { Logger } from "@zcode/contracts";
  13. import { afterEach, describe, expect, it, vi } from "vitest";
  14. import {
  15. createSharedZCodeCredentialStore,
  16. type SharedZCodeCredentialStore,
  17. } from "../src/auth/shared-credentials.js";
  18. import { createMcpAdapter } from "../src/mcp/index.js";
  19. import { publishCanonicalCredentials } from "../src/mcp/oauth-credentials.js";
  20. import { MCP_OAUTH_INTERACTIVE_REQUIRED_ERROR_CODE } from "../src/mcp/oauth-errors.js";
  21. import {
  22. createCredentialKeyPrefix,
  23. createMcpAuthorizationCodeOAuthSession,
  24. type McpOAuthSession,
  25. } from "../src/mcp/oauth.js";
  26. import { createMcpOAuthTokenProvider } from "../src/mcp/oauth-provider.js";
  27. const OAUTH_ACCESS_TOKEN = "oauth-e2e-access-token";
  28. const OAUTH_CLIENT_ID = "zcode-client";
  29. const OAUTH_CLIENT_SECRET = "zcode-secret";
  30. const DYNAMIC_CLIENT_ID = "dynamic-zcode-client";
  31. const DYNAMIC_CLIENT_SECRET = "dynamic-zcode-secret";
  32. const MCP_SCOPE = "mcp:tools";
  33. const servers: Server[] = [];
  34. interface StrictAuthorizationServerState {
  35. authorizationCodes: Map<
  36. string,
  37. {
  38. clientId: string;
  39. codeChallenge: string;
  40. redirectUri: string;
  41. }
  42. >;
  43. clients: Map<
  44. string,
  45. {
  46. clientSecret: string;
  47. redirectUris: string[];
  48. }
  49. >;
  50. refreshTokens: Map<string, string>;
  51. }
  52. describe("MCP OAuth client credentials e2e", () => {
  53. afterEach(async () => {
  54. await Promise.all(servers.splice(0).map(closeServer));
  55. });
  56. it("authenticates a protected HTTP MCP server after a 401 challenge", async () => {
  57. const authTokenRequests: Array<Record<string, string>> = [];
  58. const mcpAuthorizations: string[] = [];
  59. let authBaseUrl = "";
  60. const authServer = await listen(
  61. createServer(async (req, res) => {
  62. await handleAuthServerRequest(req, res, {
  63. authBaseUrl,
  64. tokenRequests: authTokenRequests,
  65. });
  66. }),
  67. );
  68. authBaseUrl = serverBaseUrl(authServer);
  69. let mcpUrl = "";
  70. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  71. const mcpServer = await listen(
  72. createServer(async (req, res) => {
  73. await handleProtectedMcpRequest(req, res, {
  74. authBaseUrl,
  75. authorizations: mcpAuthorizations,
  76. mcpUrl,
  77. resourceMetadataPath,
  78. });
  79. }),
  80. );
  81. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  82. const adapter = createMcpAdapter();
  83. const status = await adapter.connectServer("protected", {
  84. type: "http",
  85. url: mcpUrl,
  86. oauth: {
  87. type: "client_credentials",
  88. clientId: OAUTH_CLIENT_ID,
  89. clientSecret: OAUTH_CLIENT_SECRET,
  90. scope: MCP_SCOPE,
  91. },
  92. });
  93. expect(status).toMatchObject({
  94. status: "connected",
  95. toolCount: 1,
  96. transport: "http",
  97. });
  98. await expect(adapter.listTools()).resolves.toMatchObject([
  99. {
  100. serverName: "protected",
  101. toolName: "oauth_ping",
  102. },
  103. ]);
  104. expect(authTokenRequests).toEqual([
  105. expect.objectContaining({
  106. grant_type: "client_credentials",
  107. resource: mcpUrl,
  108. scope: MCP_SCOPE,
  109. }),
  110. ]);
  111. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  112. await adapter.close();
  113. });
  114. it("completes interactive authorization_code OAuth and reconnects the MCP server", async () => {
  115. const authorizationRequests: Array<Record<string, string>> = [];
  116. const authTokenRequests: Array<Record<string, string>> = [];
  117. const mcpAuthorizations: string[] = [];
  118. const registrationRequests: Array<Record<string, unknown>> = [];
  119. const pkceChallenges = new Map<string, string>();
  120. let authBaseUrl = "";
  121. const authServer = await listen(
  122. createServer(async (req, res) => {
  123. await handleAuthorizationCodeAuthServerRequest(req, res, {
  124. authBaseUrl,
  125. authorizationRequests,
  126. pkceChallenges,
  127. registrationRequests,
  128. tokenRequests: authTokenRequests,
  129. });
  130. }),
  131. );
  132. authBaseUrl = serverBaseUrl(authServer);
  133. let mcpUrl = "";
  134. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  135. const mcpServer = await listen(
  136. createServer(async (req, res) => {
  137. await handleProtectedMcpRequest(req, res, {
  138. authBaseUrl,
  139. authorizations: mcpAuthorizations,
  140. mcpUrl,
  141. resourceMetadataPath,
  142. });
  143. }),
  144. );
  145. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  146. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-"));
  147. const credentialStore = createSharedZCodeCredentialStore({
  148. env: {
  149. ZCODE_CREDENTIAL_SECRET: "mcp-oauth-e2e-secret",
  150. },
  151. filePath: join(credentialsDir, "credentials.json"),
  152. });
  153. const adapter = createMcpAdapter({
  154. mcpOAuth: {
  155. authorizationTimeoutMs: 5_000,
  156. credentialStore,
  157. openAuthorizationUrl: async ({ authorizationUrl }) => {
  158. const authorizationResponse = await fetch(authorizationUrl, {
  159. redirect: "manual",
  160. });
  161. expect(authorizationResponse.status).toBe(302);
  162. const location = authorizationResponse.headers.get("location");
  163. if (!location) {
  164. throw new Error("Authorization server did not redirect to callback URL");
  165. }
  166. const callbackResponse = await fetch(location);
  167. expect(callbackResponse.status).toBe(200);
  168. },
  169. },
  170. });
  171. try {
  172. const status = await adapter.connectServer("figma", {
  173. type: "http",
  174. url: mcpUrl,
  175. oauth: {
  176. type: "authorization_code",
  177. clientName: "ZCode Test",
  178. scope: MCP_SCOPE,
  179. },
  180. });
  181. expect(status).toMatchObject({
  182. status: "connected",
  183. toolCount: 1,
  184. transport: "http",
  185. });
  186. await expect(adapter.listTools()).resolves.toMatchObject([
  187. {
  188. serverName: "figma",
  189. toolName: "oauth_ping",
  190. },
  191. ]);
  192. expect(registrationRequests).toHaveLength(1);
  193. expect(registrationRequests[0]).toMatchObject({
  194. client_name: "ZCode Test",
  195. grant_types: ["authorization_code", "refresh_token"],
  196. response_types: ["code"],
  197. scope: MCP_SCOPE,
  198. });
  199. expect(registrationRequests[0]?.redirect_uris).toEqual([
  200. expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\/mcp\/figma$/),
  201. ]);
  202. expect(authorizationRequests).toEqual([
  203. expect.objectContaining({
  204. client_id: DYNAMIC_CLIENT_ID,
  205. code_challenge_method: "S256",
  206. redirect_uri: expect.stringMatching(
  207. /^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\/mcp\/figma$/,
  208. ),
  209. resource: mcpUrl,
  210. response_type: "code",
  211. scope: MCP_SCOPE,
  212. }),
  213. ]);
  214. expect(authorizationRequests[0]?.code_challenge).toMatch(/^[A-Za-z0-9_-]{43}$/);
  215. expect(authorizationRequests[0]?.state).toMatch(/^[A-Za-z0-9_-]+$/);
  216. expect(authTokenRequests).toEqual([
  217. expect.objectContaining({
  218. code: "interactive-code-1",
  219. grant_type: "authorization_code",
  220. redirect_uri: expect.stringMatching(
  221. /^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\/mcp\/figma$/,
  222. ),
  223. resource: mcpUrl,
  224. }),
  225. ]);
  226. expect(authTokenRequests[0]?.code_verifier).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);
  227. expect(pkceChallenges.size).toBe(0);
  228. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  229. } finally {
  230. await adapter.close();
  231. await rm(credentialsDir, { force: true, recursive: true });
  232. }
  233. });
  234. it("runs a single interactive authorization transaction for concurrent adapters sharing one credential file", async () => {
  235. const authorizationRequests: Array<Record<string, string>> = [];
  236. const authTokenRequests: Array<Record<string, string>> = [];
  237. const mcpAuthorizations: string[] = [];
  238. const registrationRequests: Array<Record<string, unknown>> = [];
  239. const pkceChallenges = new Map<string, string>();
  240. const strictAuthorizationState = createStrictAuthorizationServerState();
  241. let authBaseUrl = "";
  242. const authServer = await listen(
  243. createServer(async (req, res) => {
  244. await handleAuthorizationCodeAuthServerRequest(req, res, {
  245. authBaseUrl,
  246. authorizationRequests,
  247. pkceChallenges,
  248. registrationRequests,
  249. strictAuthorizationState,
  250. tokenRequests: authTokenRequests,
  251. });
  252. }),
  253. );
  254. authBaseUrl = serverBaseUrl(authServer);
  255. let mcpUrl = "";
  256. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  257. const mcpServer = await listen(
  258. createServer(async (req, res) => {
  259. await handleProtectedMcpRequest(req, res, {
  260. authBaseUrl,
  261. authorizations: mcpAuthorizations,
  262. mcpUrl,
  263. resourceMetadataPath,
  264. });
  265. }),
  266. );
  267. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  268. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-race-"));
  269. const credentialStore = createSharedZCodeCredentialStore({
  270. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-race-secret" },
  271. filePath: join(credentialsDir, "credentials.json"),
  272. });
  273. const authorizationUrls: string[] = [];
  274. const driveAuthorization = async ({ authorizationUrl }: { authorizationUrl: string }) => {
  275. authorizationUrls.push(authorizationUrl);
  276. await followAuthorizationRedirect(authorizationUrl);
  277. };
  278. const adapterA = createMcpAdapter({
  279. mcpOAuth: {
  280. authorizationTimeoutMs: 5_000,
  281. credentialStore,
  282. openAuthorizationUrl: driveAuthorization,
  283. },
  284. });
  285. const adapterB = createMcpAdapter({
  286. mcpOAuth: {
  287. authorizationTimeoutMs: 5_000,
  288. credentialStore,
  289. openAuthorizationUrl: driveAuthorization,
  290. },
  291. });
  292. const config = {
  293. type: "http" as const,
  294. url: mcpUrl,
  295. oauth: {
  296. type: "authorization_code" as const,
  297. clientName: "ZCode Concurrent Test",
  298. scope: MCP_SCOPE,
  299. },
  300. };
  301. try {
  302. const [statusA, statusB] = await Promise.all([
  303. adapterA.connectServer("exa", config),
  304. adapterB.connectServer("exa", config),
  305. ]);
  306. // 修复原因(根因 2):过去两个并发 adapter 各跑一套授权事务,产生两个 DCR client、两个
  307. // state、两个授权 URL;用户会点到已超时或非目标事务的链接,且每个 client 的 redirect_uris
  308. // 都锁死在各自的随机端口。现在授权由跨进程 lease 单飞,follower 观察 canonical 换代后
  309. // 复用同一份凭据。
  310. expect(statusA).toMatchObject({ status: "connected", toolCount: 1 });
  311. expect(statusB).toMatchObject({ status: "connected", toolCount: 1 });
  312. expect(authorizationUrls).toHaveLength(1);
  313. expect(authorizationRequests).toHaveLength(1);
  314. expect(registrationRequests).toHaveLength(1);
  315. expect(authTokenRequests).toHaveLength(1);
  316. expect(authTokenRequests[0]).toMatchObject({
  317. client_id: `${DYNAMIC_CLIENT_ID}-1`,
  318. code: "interactive-code-1",
  319. grant_type: "authorization_code",
  320. });
  321. // fresh DCR 的 redirect_uri 必须与本次授权请求实际使用的回调地址一致。
  322. expect(registrationRequests[0]?.redirect_uris).toEqual([
  323. authorizationRequests[0]?.redirect_uri,
  324. ]);
  325. expect(pkceChallenges.size).toBe(0);
  326. } finally {
  327. await Promise.all([adapterA.close(), adapterB.close()]);
  328. await rm(credentialsDir, { force: true, recursive: true });
  329. }
  330. });
  331. it("re-registers a fresh client instead of reusing a stored client bound to a dead callback port", async () => {
  332. const authorizationRequests: Array<Record<string, string>> = [];
  333. const authTokenRequests: Array<Record<string, string>> = [];
  334. const mcpAuthorizations: string[] = [];
  335. const registrationRequests: Array<Record<string, unknown>> = [];
  336. const pkceChallenges = new Map<string, string>();
  337. const strictAuthorizationState = createStrictAuthorizationServerState();
  338. const STALE_CLIENT_ID = "stale-exa-client";
  339. const STALE_REDIRECT_URI = "http://127.0.0.1:54735/oauth/callback/mcp/exa";
  340. let authBaseUrl = "";
  341. const authServer = await listen(
  342. createServer(async (req, res) => {
  343. await handleAuthorizationCodeAuthServerRequest(req, res, {
  344. authBaseUrl,
  345. authorizationRequests,
  346. // 精确匹配 redirect_uri(含端口),模拟对 loopback 不做 RFC 8252 端口豁免的授权服务器。
  347. exactRedirectUriMatch: true,
  348. pkceChallenges,
  349. registrationRequests,
  350. strictAuthorizationState,
  351. tokenRequests: authTokenRequests,
  352. });
  353. }),
  354. );
  355. authBaseUrl = serverBaseUrl(authServer);
  356. let mcpUrl = "";
  357. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  358. const mcpServer = await listen(
  359. createServer(async (req, res) => {
  360. await handleProtectedMcpRequest(req, res, {
  361. authBaseUrl,
  362. authorizations: mcpAuthorizations,
  363. mcpUrl,
  364. resourceMetadataPath,
  365. });
  366. }),
  367. );
  368. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  369. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-stale-client-"));
  370. const credentialStore = createSharedZCodeCredentialStore({
  371. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-stale-client-secret" },
  372. filePath: join(credentialsDir, "credentials.json"),
  373. });
  374. const oauthConfig = {
  375. type: "authorization_code" as const,
  376. clientName: "ZCode exa",
  377. scope: MCP_SCOPE,
  378. };
  379. const keyPrefix = createCredentialKeyPrefix("exa", mcpUrl, oauthConfig);
  380. // 现场复现:client 注册于历史端口 54735,之后每次授权都换新的随机端口。
  381. strictAuthorizationState.clients.set(STALE_CLIENT_ID, {
  382. clientSecret: "stale-exa-secret",
  383. redirectUris: [STALE_REDIRECT_URI],
  384. });
  385. await credentialStore.save(
  386. `${keyPrefix}:client_information`,
  387. JSON.stringify({
  388. client_id: STALE_CLIENT_ID,
  389. client_secret: "stale-exa-secret",
  390. token_endpoint_auth_method: "client_secret_basic",
  391. }),
  392. );
  393. const adapter = createMcpAdapter({
  394. mcpOAuth: {
  395. authorizationTimeoutMs: 5_000,
  396. credentialStore,
  397. openAuthorizationUrl: async ({ authorizationUrl }) => {
  398. await followAuthorizationRedirect(authorizationUrl);
  399. },
  400. },
  401. });
  402. try {
  403. const status = await adapter.connectServer("exa", {
  404. type: "http",
  405. url: mcpUrl,
  406. oauth: oauthConfig,
  407. });
  408. // 修复原因(根因 2):过去这条路径会发出「旧 client_id + 新 redirect_uri」的授权请求。
  409. // 授权服务器按 RFC 6749 §4.1.2.1 禁止回跳、就地渲染错误页(用户看到的 Exa
  410. // "Server Components render error"),回调永不到达,且重试永不自愈。
  411. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  412. expect(registrationRequests).toHaveLength(1);
  413. expect(authorizationRequests).toHaveLength(1);
  414. expect(authorizationRequests[0]?.client_id).toBe(`${DYNAMIC_CLIENT_ID}-1`);
  415. expect(authorizationRequests[0]?.client_id).not.toBe(STALE_CLIENT_ID);
  416. expect(authorizationRequests[0]?.redirect_uri).not.toBe(STALE_REDIRECT_URI);
  417. // fresh DCR 注册的 redirect_uri 必须正是本次授权实际使用的存活 listener 地址。
  418. expect(registrationRequests[0]?.redirect_uris).toEqual([
  419. authorizationRequests[0]?.redirect_uri,
  420. ]);
  421. expect(authTokenRequests).toHaveLength(1);
  422. expect(authTokenRequests[0]?.client_id).toBe(`${DYNAMIC_CLIENT_ID}-1`);
  423. // 发布后的 canonical pair 必须是本次授权的 client,而不是历史 client。
  424. const canonicalRaw = await credentialStore.load(`${keyPrefix}:authorization_credentials`);
  425. expect(canonicalRaw).toBeTruthy();
  426. const canonical = JSON.parse(canonicalRaw ?? "{}") as {
  427. client_information?: { client_id?: string };
  428. generation?: string;
  429. };
  430. expect(canonical.client_information?.client_id).toBe(`${DYNAMIC_CLIENT_ID}-1`);
  431. expect(canonical.generation).toMatch(/^[0-9a-f]{32}$/);
  432. } finally {
  433. await adapter.close();
  434. await rm(credentialsDir, { force: true, recursive: true });
  435. }
  436. });
  437. it("performs zero discovery, zero DCR and opens zero listeners for a passive connect with valid credentials", async () => {
  438. const authorizationRequests: Array<Record<string, string>> = [];
  439. const authTokenRequests: Array<Record<string, string>> = [];
  440. const mcpAuthorizations: string[] = [];
  441. const registrationRequests: Array<Record<string, unknown>> = [];
  442. const pkceChallenges = new Map<string, string>();
  443. let authServerRequests = 0;
  444. let authBaseUrl = "";
  445. const authServer = await listen(
  446. createServer(async (req, res) => {
  447. authServerRequests += 1;
  448. await handleAuthorizationCodeAuthServerRequest(req, res, {
  449. authBaseUrl,
  450. authorizationRequests,
  451. pkceChallenges,
  452. registrationRequests,
  453. tokenRequests: authTokenRequests,
  454. });
  455. }),
  456. );
  457. authBaseUrl = serverBaseUrl(authServer);
  458. let mcpUrl = "";
  459. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  460. const mcpServer = await listen(
  461. createServer(async (req, res) => {
  462. await handleProtectedMcpRequest(req, res, {
  463. authBaseUrl,
  464. authorizations: mcpAuthorizations,
  465. mcpUrl,
  466. resourceMetadataPath,
  467. });
  468. }),
  469. );
  470. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  471. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-passive-"));
  472. const credentialStore = createSharedZCodeCredentialStore({
  473. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-passive-secret" },
  474. filePath: join(credentialsDir, "credentials.json"),
  475. });
  476. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  477. const keyPrefix = createCredentialKeyPrefix("passive", mcpUrl, oauthConfig);
  478. // 现成可用的凭据:还没临期,因此连接期不需要任何 OAuth 动作。
  479. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  480. clientInformation: { client_id: "passive-client" },
  481. publishedBy: "passive-seed",
  482. tokens: {
  483. access_token: OAUTH_ACCESS_TOKEN,
  484. expires_in: 3600,
  485. refresh_token: "passive-refresh-token",
  486. token_type: "Bearer",
  487. },
  488. });
  489. const adapter = createMcpAdapter({ mcpOAuth: { credentialStore } });
  490. const listenersBefore = countTcpServers();
  491. try {
  492. const status = await adapter.connectServer("passive", {
  493. type: "http",
  494. url: mcpUrl,
  495. oauth: oauthConfig,
  496. });
  497. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  498. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  499. // 修复原因:过去任何没有 Authorization header 的 HTTP/SSE MCP 在建连前就会创建完整 OAuth
  500. // session,而 session 返回前就 listen(0) 起了一个 callback server——即使凭据完全有效。
  501. // 纯 AuthProvider 让被动连接彻底不碰 discovery / DCR / listener。
  502. expect(authServerRequests).toBe(0);
  503. expect(registrationRequests).toHaveLength(0);
  504. expect(authorizationRequests).toHaveLength(0);
  505. expect(countTcpServers()).toBe(listenersBefore);
  506. } finally {
  507. await adapter.close();
  508. await rm(credentialsDir, { force: true, recursive: true });
  509. }
  510. });
  511. it("recovers a tool call whose refresh token was revoked by running Phase 2 and reconnecting", async () => {
  512. const authorizationRequests: Array<Record<string, string>> = [];
  513. const authTokenRequests: Array<Record<string, string>> = [];
  514. const mcpAuthorizations: string[] = [];
  515. const registrationRequests: Array<Record<string, unknown>> = [];
  516. const pkceChallenges = new Map<string, string>();
  517. let authBaseUrl = "";
  518. const authServer = await listen(
  519. createServer(async (req, res) => {
  520. await handleAuthorizationCodeAuthServerRequest(req, res, {
  521. authBaseUrl,
  522. authorizationRequests,
  523. pkceChallenges,
  524. registrationRequests,
  525. tokenRequests: authTokenRequests,
  526. });
  527. }),
  528. );
  529. authBaseUrl = serverBaseUrl(authServer);
  530. // 前 N 次工具调用返回 401,模拟运行期 access token 失效。
  531. let rejectToolCalls = true;
  532. let mcpUrl = "";
  533. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  534. const mcpServer = await listen(
  535. createServer(async (req, res) => {
  536. if (rejectToolCalls && req.method === "POST") {
  537. const body = await readRequestBody(req);
  538. if (body.includes('"tools/call"')) {
  539. res.writeHead(401, {
  540. "WWW-Authenticate": [
  541. `Bearer resource_metadata="${new URL(resourceMetadataPath, mcpUrl).href}", scope="${MCP_SCOPE}"`,
  542. ],
  543. });
  544. res.end();
  545. return;
  546. }
  547. await handleProtectedMcpRequest(req, res, {
  548. authBaseUrl,
  549. authorizations: mcpAuthorizations,
  550. body,
  551. mcpUrl,
  552. resourceMetadataPath,
  553. });
  554. return;
  555. }
  556. await handleProtectedMcpRequest(req, res, {
  557. authBaseUrl,
  558. authorizations: mcpAuthorizations,
  559. mcpUrl,
  560. resourceMetadataPath,
  561. });
  562. }),
  563. );
  564. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  565. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-runtime-"));
  566. const credentialStore = createSharedZCodeCredentialStore({
  567. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-runtime-secret" },
  568. filePath: join(credentialsDir, "credentials.json"),
  569. });
  570. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  571. const keyPrefix = createCredentialKeyPrefix("runtime", mcpUrl, oauthConfig);
  572. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  573. clientInformation: { client_id: "revoked-client" },
  574. publishedBy: "runtime-seed",
  575. tokens: {
  576. access_token: OAUTH_ACCESS_TOKEN,
  577. expires_in: 3600,
  578. // 该 refresh token 在 fake AS 上不存在 → 刷新时收到 invalid_grant。
  579. refresh_token: "revoked-refresh-token",
  580. token_type: "Bearer",
  581. },
  582. });
  583. const adapter = createMcpAdapter({
  584. mcpOAuth: {
  585. credentialStore,
  586. openAuthorizationUrl: async ({ authorizationUrl }) => {
  587. rejectToolCalls = false;
  588. await followAuthorizationRedirect(authorizationUrl);
  589. },
  590. },
  591. });
  592. try {
  593. const status = await adapter.connectServer("runtime", {
  594. type: "http",
  595. url: mcpUrl,
  596. oauth: oauthConfig,
  597. });
  598. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  599. // Bugfix 回归:建连后 token 被撤销时,过去 callTool 的 401/403 原样冒泡,用户看到裸错误且
  600. // 永不自愈——OAuth 自愈只存在于 startup connect 路径。现在运行期共用 Phase 2 → Phase 1 编排。
  601. await expect(
  602. adapter.callTool({ serverName: "runtime", toolName: "oauth_ping" }),
  603. ).resolves.toMatchObject({ isError: false });
  604. expect(registrationRequests).toHaveLength(1);
  605. expect(authorizationRequests).toHaveLength(1);
  606. } finally {
  607. await adapter.close();
  608. await rm(credentialsDir, { force: true, recursive: true });
  609. }
  610. });
  611. it("steps up authorization scope with the union of configured, granted, and challenged scopes", async () => {
  612. const authorizationRequests: Array<Record<string, string>> = [];
  613. const authTokenRequests: Array<Record<string, string>> = [];
  614. const mcpAuthorizations: string[] = [];
  615. const registrationRequests: Array<Record<string, unknown>> = [];
  616. const pkceChallenges = new Map<string, string>();
  617. const STEP_UP_SCOPE = "admin:tools";
  618. let authBaseUrl = "";
  619. const authServer = await listen(
  620. createServer(async (req, res) => {
  621. await handleAuthorizationCodeAuthServerRequest(req, res, {
  622. authBaseUrl,
  623. authorizationRequests,
  624. pkceChallenges,
  625. registrationRequests,
  626. tokenRequests: authTokenRequests,
  627. });
  628. }),
  629. );
  630. authBaseUrl = serverBaseUrl(authServer);
  631. let mcpUrl = "";
  632. let stepUpRequired = true;
  633. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  634. const mcpServer = await listen(
  635. createServer(async (req, res) => {
  636. await handleProtectedMcpRequest(req, res, {
  637. authBaseUrl,
  638. authorizations: mcpAuthorizations,
  639. mcpUrl,
  640. resourceMetadataPath,
  641. ...(stepUpRequired ? { stepUpScope: STEP_UP_SCOPE } : {}),
  642. });
  643. }),
  644. );
  645. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  646. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-stepup-"));
  647. const credentialStore = createSharedZCodeCredentialStore({
  648. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-stepup-secret" },
  649. filePath: join(credentialsDir, "credentials.json"),
  650. });
  651. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  652. const keyPrefix = createCredentialKeyPrefix("stepup", mcpUrl, oauthConfig);
  653. // 现存凭据:token 有效、已授予 mcp:tools,但服务端现在要求 admin:tools。
  654. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  655. clientInformation: { client_id: "stepup-client" },
  656. publishedBy: "stepup-seed",
  657. tokens: {
  658. access_token: OAUTH_ACCESS_TOKEN,
  659. expires_in: 3600,
  660. scope: MCP_SCOPE,
  661. token_type: "Bearer",
  662. },
  663. });
  664. const adapter = createMcpAdapter({
  665. mcpOAuth: {
  666. credentialStore,
  667. openAuthorizationUrl: async ({ authorizationUrl }) => {
  668. stepUpRequired = false;
  669. await followAuthorizationRedirect(authorizationUrl);
  670. },
  671. },
  672. });
  673. try {
  674. const status = await adapter.connectServer("stepup", {
  675. type: "http",
  676. url: mcpUrl,
  677. oauth: oauthConfig,
  678. });
  679. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  680. // 修复原因(spec §5.2,复核 P1):只带 challenge scope 重新授权时,授权服务器可能按新请求
  681. // 收回先前授予的 scope,下一个请求换个 challenge 又 403,形成重授权乒乓。重新授权请求
  682. // 必须携带 config ∪ token.scope ∪ challenge 的并集,且 DCR 注册同一个值。
  683. expect(authorizationRequests).toHaveLength(1);
  684. expect(authorizationRequests[0]?.scope).toBe(`${MCP_SCOPE} ${STEP_UP_SCOPE}`);
  685. expect(registrationRequests).toHaveLength(1);
  686. expect(registrationRequests[0]?.scope).toBe(`${MCP_SCOPE} ${STEP_UP_SCOPE}`);
  687. // challenge 携带的 resource_metadata 要传导为授权请求的 resource 受众参数。
  688. expect(authorizationRequests[0]?.resource).toBe(mcpUrl);
  689. expect(authTokenRequests).toHaveLength(1);
  690. } finally {
  691. await adapter.close();
  692. await rm(credentialsDir, { force: true, recursive: true });
  693. }
  694. });
  695. it("binds dynamically registered client information to each OAuth transaction", async () => {
  696. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-client-transaction-"));
  697. const credentialStore = createSharedZCodeCredentialStore({
  698. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-client-transaction-secret" },
  699. filePath: join(credentialsDir, "credentials.json"),
  700. });
  701. const sessions: McpOAuthSession[] = [];
  702. try {
  703. const sessionA = await createTestOAuthSession(credentialStore, "transaction-a");
  704. const sessionB = await createTestOAuthSession(credentialStore, "transaction-b");
  705. sessions.push(sessionA, sessionB);
  706. const clientA = dynamicClientInformation("transaction-client-a");
  707. const clientB = dynamicClientInformation("transaction-client-b");
  708. await saveDynamicClientInformation(sessionA, clientA);
  709. await saveDynamicClientInformation(sessionB, clientB);
  710. await expect(sessionA.provider.clientInformation()).resolves.toEqual(clientA);
  711. await expect(sessionB.provider.clientInformation()).resolves.toEqual(clientB);
  712. } finally {
  713. await Promise.all(sessions.map((session) => session.close()));
  714. await rm(credentialsDir, { force: true, recursive: true });
  715. }
  716. });
  717. it("restores dynamically registered client information after provider reconstruction", async () => {
  718. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-client-recovery-"));
  719. const credentialStore = createSharedZCodeCredentialStore({
  720. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-client-recovery-secret" },
  721. filePath: join(credentialsDir, "credentials.json"),
  722. });
  723. const sessions: McpOAuthSession[] = [];
  724. try {
  725. const registered = await createTestOAuthSession(credentialStore, "recovery-registered");
  726. sessions.push(registered);
  727. const client = dynamicClientInformation("recovery-client");
  728. await saveDynamicClientInformation(registered, client);
  729. await registered.close();
  730. sessions.splice(sessions.indexOf(registered), 1);
  731. const reconstructed = await createTestOAuthSession(credentialStore, "recovery-reconstructed");
  732. sessions.push(reconstructed);
  733. await expect(reconstructed.provider.clientInformation()).resolves.toEqual(client);
  734. } finally {
  735. await Promise.all(sessions.map((session) => session.close()));
  736. await rm(credentialsDir, { force: true, recursive: true });
  737. }
  738. });
  739. it("retries credential snapshots after a transient load failure", async () => {
  740. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-load-retry-"));
  741. const credentialStore = createSharedZCodeCredentialStore({
  742. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-load-retry-secret" },
  743. filePath: join(credentialsDir, "credentials.json"),
  744. });
  745. const sessions: McpOAuthSession[] = [];
  746. try {
  747. const publisher = await createTestOAuthSession(credentialStore, "load-retry-publisher");
  748. sessions.push(publisher);
  749. const client = dynamicClientInformation("load-retry-client");
  750. const tokens = oauthTokens("load-retry-client");
  751. await saveDynamicClientInformation(publisher, client);
  752. await publisher.provider.saveTokens(tokens);
  753. let loadAttempts = 0;
  754. const transientFailure = new Error("injected transient credential load failure");
  755. const retryingStore: SharedZCodeCredentialStore = {
  756. ...credentialStore,
  757. async loadMany(keys: string[]): Promise<Record<string, string | null>> {
  758. loadAttempts += 1;
  759. if (loadAttempts === 1) throw transientFailure;
  760. return await credentialStore.loadMany(keys);
  761. },
  762. };
  763. const reader = await createTestOAuthSession(retryingStore, "load-retry-reader");
  764. sessions.push(reader);
  765. await expect(reader.provider.tokens()).rejects.toThrow(transientFailure.message);
  766. await expect(reader.provider.tokens()).resolves.toEqual(tokens);
  767. await expect(reader.provider.clientInformation()).resolves.toEqual(client);
  768. expect(loadAttempts).toBe(2);
  769. } finally {
  770. await Promise.all(sessions.map((session) => session.close()));
  771. await rm(credentialsDir, { force: true, recursive: true });
  772. }
  773. });
  774. it("does not fail session close when verifier cleanup fails", async () => {
  775. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-close-cleanup-"));
  776. const credentialStore = createSharedZCodeCredentialStore({
  777. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-close-cleanup-secret" },
  778. filePath: join(credentialsDir, "credentials.json"),
  779. });
  780. const cleanupError = new Error("injected verifier cleanup failure");
  781. const failingStore: SharedZCodeCredentialStore = {
  782. ...credentialStore,
  783. async delete(key: string): Promise<void> {
  784. if (key.includes(":code_verifier:")) throw cleanupError;
  785. await credentialStore.delete(key);
  786. },
  787. };
  788. const { logger, warn } = createTestLogger();
  789. const session = await createMcpAuthorizationCodeOAuthSession({
  790. adapterInstanceId: "close-cleanup",
  791. config: testAuthorizationCodeConfig(),
  792. logger,
  793. options: { credentialStore: failingStore },
  794. serverName: "credential-pair-test",
  795. serverUrl: "https://mcp.example.test/mcp",
  796. });
  797. try {
  798. await session.provider.saveCodeVerifier("close-cleanup-verifier");
  799. await expect(session.close()).resolves.toBeUndefined();
  800. expect(warn).toHaveBeenCalledWith(
  801. "MCP OAuth verifier cleanup failed",
  802. expect.objectContaining({
  803. error: cleanupError.message,
  804. event: "mcp.oauth.verifier.cleanup_failed",
  805. mcpServerName: "credential-pair-test",
  806. }),
  807. );
  808. } finally {
  809. await rm(credentialsDir, { force: true, recursive: true });
  810. }
  811. });
  812. it("publishes client information and tokens as one credential snapshot", async () => {
  813. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-client-token-pair-"));
  814. const credentialStore = createSharedZCodeCredentialStore({
  815. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-client-token-pair-secret" },
  816. filePath: join(credentialsDir, "credentials.json"),
  817. });
  818. const sessions: McpOAuthSession[] = [];
  819. try {
  820. const sessionA = await createTestOAuthSession(credentialStore, "pair-a");
  821. const sessionB = await createTestOAuthSession(credentialStore, "pair-b");
  822. sessions.push(sessionA, sessionB);
  823. const clientA = dynamicClientInformation("pair-client-a");
  824. const clientB = dynamicClientInformation("pair-client-b");
  825. const tokensA = oauthTokens("pair-client-a");
  826. const tokensB = oauthTokens("pair-client-b");
  827. await saveDynamicClientInformation(sessionA, clientA);
  828. await saveDynamicClientInformation(sessionB, clientB);
  829. await sessionB.provider.saveTokens(tokensB);
  830. await sessionA.provider.saveTokens(tokensA);
  831. const reader = await createTestOAuthSession(credentialStore, "pair-reader");
  832. sessions.push(reader);
  833. await expect(reader.provider.clientInformation()).resolves.toEqual(clientA);
  834. await expect(reader.provider.tokens()).resolves.toEqual(tokensA);
  835. } finally {
  836. await Promise.all(sessions.map((session) => session.close()));
  837. await rm(credentialsDir, { force: true, recursive: true });
  838. }
  839. });
  840. it("preserves v1 canonical credentials across legacy migration states", async () => {
  841. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-v1-migration-"));
  842. const credentialStore = createSharedZCodeCredentialStore({
  843. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-v1-migration-secret" },
  844. filePath: join(credentialsDir, "credentials.json"),
  845. });
  846. const sessions: McpOAuthSession[] = [];
  847. const config = testAuthorizationCodeConfig();
  848. const serverUrl = "https://mcp.example.test/mcp";
  849. const keyPrefix = createCredentialKeyPrefix("credential-pair-test", serverUrl, config);
  850. const canonicalKey = `${keyPrefix}:authorization_credentials`;
  851. const legacyClientKey = `${keyPrefix}:client_information`;
  852. const legacyTokensKey = `${keyPrefix}:tokens`;
  853. const canonicalClient = dynamicClientInformation("v1-canonical-client");
  854. const canonicalTokens = oauthTokens("v1-canonical-client");
  855. const canonicalRaw = JSON.stringify({
  856. client_information: canonicalClient,
  857. expires_at: Date.now() + 3_600_000,
  858. published_by: "v1-publisher",
  859. tokens: canonicalTokens,
  860. version: 1,
  861. });
  862. try {
  863. // v1 发布时会删除 legacy 镜像;无镜像是正常稳态,不能因此丢弃 canonical token。
  864. await credentialStore.save(canonicalKey, canonicalRaw);
  865. const canonicalReader = await createTestOAuthSession(credentialStore, "v1-canonical-reader");
  866. sessions.push(canonicalReader);
  867. await expect(canonicalReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  868. await expect(canonicalReader.provider.tokens()).resolves.toEqual(canonicalTokens);
  869. const phaseOneProvider = createMcpOAuthTokenProvider({
  870. config,
  871. credentialStore,
  872. keyPrefix,
  873. serverName: "credential-pair-test",
  874. serverUrl,
  875. });
  876. await expect(phaseOneProvider.token()).resolves.toBe(canonicalTokens.access_token);
  877. // 旧 provider 可能只写回 refresh 后的 tokens;缺少 legacy client 时复用 canonical 身份。
  878. const tokenOnlyRefresh = {
  879. ...canonicalTokens,
  880. access_token: "v1-token-only-refreshed-access-token",
  881. };
  882. await credentialStore.save(legacyTokensKey, JSON.stringify(tokenOnlyRefresh));
  883. const tokenOnlyReader = await createTestOAuthSession(credentialStore, "v1-token-only-reader");
  884. sessions.push(tokenOnlyReader);
  885. await expect(tokenOnlyReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  886. await expect(tokenOnlyReader.provider.tokens()).resolves.toEqual(tokenOnlyRefresh);
  887. // legacy client 与 canonical 身份一致时,可以确认 tokens 属于同一 client 的更新。
  888. const matchingRefresh = {
  889. ...canonicalTokens,
  890. access_token: "v1-matching-refreshed-access-token",
  891. };
  892. await credentialStore.saveMany({
  893. [legacyClientKey]: JSON.stringify(canonicalClient),
  894. [legacyTokensKey]: JSON.stringify(matchingRefresh),
  895. });
  896. const matchingReader = await createTestOAuthSession(credentialStore, "v1-matching-reader");
  897. sessions.push(matchingReader);
  898. await expect(matchingReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  899. await expect(matchingReader.provider.tokens()).resolves.toEqual(matchingRefresh);
  900. // legacy client 身份不一致时无法确认 token 归属,必须保留完整 canonical pair。
  901. const mismatchedClient = dynamicClientInformation("v1-mismatched-client");
  902. const mismatchedTokens = oauthTokens("v1-mismatched-client");
  903. await credentialStore.saveMany({
  904. [legacyClientKey]: JSON.stringify(mismatchedClient),
  905. [legacyTokensKey]: JSON.stringify(mismatchedTokens),
  906. });
  907. const mismatchedReader = await createTestOAuthSession(
  908. credentialStore,
  909. "v1-mismatched-reader",
  910. );
  911. sessions.push(mismatchedReader);
  912. await expect(mismatchedReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  913. await expect(mismatchedReader.provider.tokens()).resolves.toEqual(canonicalTokens);
  914. } finally {
  915. await Promise.all(sessions.map((session) => session.close()));
  916. await rm(credentialsDir, { force: true, recursive: true });
  917. }
  918. });
  919. it("keeps legacy readers and writers coherent during the canonical migration window", async () => {
  920. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-mixed-version-"));
  921. const credentialStore = createSharedZCodeCredentialStore({
  922. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-mixed-version-secret" },
  923. filePath: join(credentialsDir, "credentials.json"),
  924. });
  925. const sessions: McpOAuthSession[] = [];
  926. const config = testAuthorizationCodeConfig();
  927. const keyPrefix = createCredentialKeyPrefix(
  928. "credential-pair-test",
  929. "https://mcp.example.test/mcp",
  930. config,
  931. );
  932. const legacyClientKey = `${keyPrefix}:client_information`;
  933. const legacyTokensKey = `${keyPrefix}:tokens`;
  934. const client = dynamicClientInformation("mixed-version-client");
  935. const initialTokens = oauthTokens("mixed-version-client");
  936. const reauthorizedClient = dynamicClientInformation("mixed-version-reauthorized-client");
  937. const reauthorizedTokens = oauthTokens("mixed-version-reauthorized-client");
  938. const refreshedByLegacy = {
  939. ...reauthorizedTokens,
  940. access_token: "mixed-version-reauthorized-client-legacy-refreshed-access-token",
  941. };
  942. try {
  943. const publisher = await createTestOAuthSession(credentialStore, "mixed-version-publisher");
  944. sessions.push(publisher);
  945. await saveDynamicClientInformation(publisher, client);
  946. await publisher.provider.saveTokens(initialTokens);
  947. // 目标分支旧 provider 只认识这两个 legacy key,发布后必须仍能读取同一 pair。
  948. await expect(credentialStore.load(legacyClientKey)).resolves.toBe(JSON.stringify(client));
  949. await expect(credentialStore.load(legacyTokensKey)).resolves.toBe(
  950. JSON.stringify(initialTokens),
  951. );
  952. // 旧 provider 的 DCR 与 token exchange 不是同一次写入;只更新 client 时仍须读取旧 canonical pair。
  953. await credentialStore.save(legacyClientKey, JSON.stringify(reauthorizedClient));
  954. const pendingReader = await createTestOAuthSession(
  955. credentialStore,
  956. "mixed-version-pending-reader",
  957. );
  958. sessions.push(pendingReader);
  959. await expect(pendingReader.provider.clientInformation()).resolves.toEqual(client);
  960. await expect(pendingReader.provider.tokens()).resolves.toEqual(initialTokens);
  961. // legacy 没有 generation;client/token 都变化时无法区分已完成重授权与跨事务交错。
  962. // 新 provider 保留 client 但丢弃不可信 token,完成自己的 token exchange 后再发布 pair。
  963. await credentialStore.save(legacyTokensKey, JSON.stringify(reauthorizedTokens));
  964. const reauthorizedReader = await createTestOAuthSession(
  965. credentialStore,
  966. "mixed-version-reauthorized-reader",
  967. );
  968. sessions.push(reauthorizedReader);
  969. await expect(reauthorizedReader.provider.clientInformation()).resolves.toEqual(
  970. reauthorizedClient,
  971. );
  972. await expect(reauthorizedReader.provider.tokens()).resolves.toBeUndefined();
  973. await reauthorizedReader.provider.saveTokens(reauthorizedTokens);
  974. // 模拟旧 provider refresh:它只更新 legacy tokens,新 provider 不得继续读取 stale canonical。
  975. await credentialStore.save(legacyTokensKey, JSON.stringify(refreshedByLegacy));
  976. const refreshedReader = await createTestOAuthSession(
  977. credentialStore,
  978. "mixed-version-refreshed-reader",
  979. );
  980. sessions.push(refreshedReader);
  981. await expect(refreshedReader.provider.clientInformation()).resolves.toEqual(
  982. reauthorizedClient,
  983. );
  984. await expect(refreshedReader.provider.tokens()).resolves.toEqual(refreshedByLegacy);
  985. // 模拟旧 provider invalidate tokens:canonical 不能把已失效 token 复活。
  986. await credentialStore.delete(legacyTokensKey);
  987. const invalidatedReader = await createTestOAuthSession(
  988. credentialStore,
  989. "mixed-version-invalidated-reader",
  990. );
  991. sessions.push(invalidatedReader);
  992. await expect(invalidatedReader.provider.clientInformation()).resolves.toEqual(
  993. reauthorizedClient,
  994. );
  995. await expect(invalidatedReader.provider.tokens()).resolves.toBeUndefined();
  996. } finally {
  997. await Promise.all(sessions.map((session) => session.close()));
  998. await rm(credentialsDir, { force: true, recursive: true });
  999. }
  1000. });
  1001. it("does not combine a pending legacy client with another legacy refresh", async () => {
  1002. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-legacy-race-"));
  1003. const credentialStore = createSharedZCodeCredentialStore({
  1004. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-legacy-race-secret" },
  1005. filePath: join(credentialsDir, "credentials.json"),
  1006. });
  1007. const sessions: McpOAuthSession[] = [];
  1008. const config = testAuthorizationCodeConfig();
  1009. const keyPrefix = createCredentialKeyPrefix(
  1010. "credential-pair-test",
  1011. "https://mcp.example.test/mcp",
  1012. config,
  1013. );
  1014. const clientA = dynamicClientInformation("legacy-race-client-a");
  1015. const tokensA = oauthTokens("legacy-race-client-a");
  1016. const pendingClientB = dynamicClientInformation("legacy-race-client-b");
  1017. const refreshedTokensA = {
  1018. ...tokensA,
  1019. access_token: "legacy-race-client-a-refreshed-access-token",
  1020. };
  1021. try {
  1022. const publisher = await createTestOAuthSession(credentialStore, "legacy-race-publisher");
  1023. sessions.push(publisher);
  1024. await saveDynamicClientInformation(publisher, clientA);
  1025. await publisher.provider.saveTokens(tokensA);
  1026. // 旧 provider B 只完成动态注册;旧 provider A 随后只刷新 token。两次独立写入
  1027. // 没有 generation 可证明归属,新 reader 不能把 client B 与 token A2 拼成一对。
  1028. await credentialStore.save(`${keyPrefix}:client_information`, JSON.stringify(pendingClientB));
  1029. await credentialStore.save(`${keyPrefix}:tokens`, JSON.stringify(refreshedTokensA));
  1030. const reader = await createTestOAuthSession(credentialStore, "legacy-race-reader");
  1031. sessions.push(reader);
  1032. await expect(reader.provider.clientInformation()).resolves.toEqual(pendingClientB);
  1033. await expect(reader.provider.tokens()).resolves.toBeUndefined();
  1034. } finally {
  1035. await Promise.all(sessions.map((session) => session.close()));
  1036. await rm(credentialsDir, { force: true, recursive: true });
  1037. }
  1038. });
  1039. it("does not invalidate a credential snapshot replaced by another transaction", async () => {
  1040. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-compare-delete-"));
  1041. const credentialStore = createSharedZCodeCredentialStore({
  1042. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-compare-delete-secret" },
  1043. filePath: join(credentialsDir, "credentials.json"),
  1044. });
  1045. const sessions: McpOAuthSession[] = [];
  1046. try {
  1047. const publisherA = await createTestOAuthSession(credentialStore, "publisher-a");
  1048. const staleReader = await createTestOAuthSession(credentialStore, "stale-reader");
  1049. const publisherB = await createTestOAuthSession(credentialStore, "publisher-b");
  1050. sessions.push(publisherA, staleReader, publisherB);
  1051. const clientA = dynamicClientInformation("published-client-a");
  1052. const tokensA = oauthTokens("published-client-a");
  1053. const clientB = dynamicClientInformation("published-client-b");
  1054. const tokensB = oauthTokens("published-client-b");
  1055. await saveDynamicClientInformation(publisherA, clientA);
  1056. await publisherA.provider.saveTokens(tokensA);
  1057. await expect(staleReader.provider.clientInformation()).resolves.toEqual(clientA);
  1058. await expect(staleReader.provider.tokens()).resolves.toEqual(tokensA);
  1059. await saveDynamicClientInformation(publisherB, clientB);
  1060. await publisherB.provider.saveTokens(tokensB);
  1061. await staleReader.provider.invalidateCredentials?.("tokens");
  1062. // 同一个失败 provider 的 SDK 重试也必须丢弃旧 client 缓存并读取获胜事务的 pair。
  1063. await expect(staleReader.provider.clientInformation()).resolves.toEqual(clientB);
  1064. await expect(staleReader.provider.tokens()).resolves.toEqual(tokensB);
  1065. const verifier = await createTestOAuthSession(credentialStore, "compare-delete-verifier");
  1066. sessions.push(verifier);
  1067. await expect(verifier.provider.clientInformation()).resolves.toEqual(clientB);
  1068. await expect(verifier.provider.tokens()).resolves.toEqual(tokensB);
  1069. } finally {
  1070. await Promise.all(sessions.map((session) => session.close()));
  1071. await rm(credentialsDir, { force: true, recursive: true });
  1072. }
  1073. });
  1074. it("refreshes the last concurrently published canonical pair with one client identity", async () => {
  1075. const authorizationRequests: Array<Record<string, string>> = [];
  1076. const tokenRequests: Array<Record<string, string>> = [];
  1077. const registrationRequests: Array<Record<string, unknown>> = [];
  1078. const pkceChallenges = new Map<string, string>();
  1079. const strictAuthorizationState = createStrictAuthorizationServerState();
  1080. let authBaseUrl = "";
  1081. const authServer = await listen(
  1082. createServer(async (req, res) => {
  1083. await handleAuthorizationCodeAuthServerRequest(req, res, {
  1084. authBaseUrl,
  1085. authorizationRequests,
  1086. pkceChallenges,
  1087. registrationRequests,
  1088. strictAuthorizationState,
  1089. tokenRequests,
  1090. });
  1091. }),
  1092. );
  1093. authBaseUrl = serverBaseUrl(authServer);
  1094. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-refresh-pair-"));
  1095. const credentialStore = createSharedZCodeCredentialStore({
  1096. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-refresh-pair-secret" },
  1097. filePath: join(credentialsDir, "credentials.json"),
  1098. });
  1099. const sessions: McpOAuthSession[] = [];
  1100. const clientA = dynamicClientInformation("refresh-pair-client-a");
  1101. const tokensA = oauthTokens("refresh-pair-client-a");
  1102. const clientB = dynamicClientInformation("refresh-pair-client-b");
  1103. const tokensB = oauthTokens("refresh-pair-client-b");
  1104. for (const [client, tokens] of [
  1105. [clientA, tokensA],
  1106. [clientB, tokensB],
  1107. ] as const) {
  1108. strictAuthorizationState.clients.set(client.client_id, {
  1109. clientSecret: client.client_secret ?? "",
  1110. redirectUris: [],
  1111. });
  1112. strictAuthorizationState.refreshTokens.set(tokens.refresh_token ?? "", client.client_id);
  1113. }
  1114. try {
  1115. const publisherA = await createTestOAuthSession(
  1116. credentialStore,
  1117. "refresh-publisher-a",
  1118. `${authBaseUrl}/mcp`,
  1119. );
  1120. const publisherB = await createTestOAuthSession(
  1121. credentialStore,
  1122. "refresh-publisher-b",
  1123. `${authBaseUrl}/mcp`,
  1124. );
  1125. sessions.push(publisherA, publisherB);
  1126. await saveDynamicClientInformation(publisherA, clientA);
  1127. await saveDynamicClientInformation(publisherB, clientB);
  1128. await publisherB.provider.saveTokens(tokensB);
  1129. await publisherA.provider.saveTokens(tokensA);
  1130. const reader = await createTestOAuthSession(
  1131. credentialStore,
  1132. "refresh-reader",
  1133. `${authBaseUrl}/mcp`,
  1134. );
  1135. sessions.push(reader);
  1136. await expect(auth(reader.provider, { serverUrl: `${authBaseUrl}/mcp` })).resolves.toBe(
  1137. "AUTHORIZED",
  1138. );
  1139. expect(authorizationRequests).toHaveLength(0);
  1140. expect(registrationRequests).toHaveLength(0);
  1141. expect(tokenRequests).toEqual([
  1142. expect.objectContaining({
  1143. client_id: clientA.client_id,
  1144. grant_type: "refresh_token",
  1145. refresh_token: tokensA.refresh_token,
  1146. }),
  1147. ]);
  1148. await expect(reader.provider.clientInformation()).resolves.toEqual(clientA);
  1149. await expect(reader.provider.tokens()).resolves.toMatchObject({
  1150. access_token: `${clientA.client_id}-refreshed-access-token`,
  1151. refresh_token: tokensA.refresh_token,
  1152. });
  1153. } finally {
  1154. await Promise.all(sessions.map((session) => session.close()));
  1155. await rm(credentialsDir, { force: true, recursive: true });
  1156. }
  1157. });
  1158. it("preserves a canonical credential snapshot written by a newer version", async () => {
  1159. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-future-credentials-"));
  1160. const credentialStore = createSharedZCodeCredentialStore({
  1161. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-future-credentials-secret" },
  1162. filePath: join(credentialsDir, "credentials.json"),
  1163. });
  1164. const sessions: McpOAuthSession[] = [];
  1165. const keyPrefix = createCredentialKeyPrefix(
  1166. "credential-pair-test",
  1167. "https://mcp.example.test/mcp",
  1168. testAuthorizationCodeConfig(),
  1169. );
  1170. const futureSnapshot = JSON.stringify({
  1171. client_information: dynamicClientInformation("future-client"),
  1172. published_by: "future-publisher",
  1173. tokens: oauthTokens("future-client"),
  1174. version: 3,
  1175. });
  1176. try {
  1177. await credentialStore.save(`${keyPrefix}:authorization_credentials`, futureSnapshot);
  1178. const session = await createTestOAuthSession(credentialStore, "future-reader");
  1179. sessions.push(session);
  1180. // 未知版本必须保留原值:CLI 与 desktop 独立升级、共享同一份凭据文件,旧版本不能把新版本
  1181. // 写入的 canonical pair 当损坏数据删除。没有可用 client 时改为要求交互授权(PR2 过渡 seam),
  1182. // 而不是返回 undefined 让 SDK 自行做一次动态注册。
  1183. await expect(session.provider.clientInformation()).rejects.toMatchObject({
  1184. code: MCP_OAUTH_INTERACTIVE_REQUIRED_ERROR_CODE,
  1185. reason: "no_credentials",
  1186. });
  1187. await expect(session.provider.tokens()).resolves.toBeUndefined();
  1188. await expect(credentialStore.load(`${keyPrefix}:authorization_credentials`)).resolves.toBe(
  1189. futureSnapshot,
  1190. );
  1191. } finally {
  1192. await Promise.all(sessions.map((session) => session.close()));
  1193. await rm(credentialsDir, { force: true, recursive: true });
  1194. }
  1195. });
  1196. it("removes both legacy credential halves when the legacy client is invalid", async () => {
  1197. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-legacy-invalidation-"));
  1198. const credentialStore = createSharedZCodeCredentialStore({
  1199. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-legacy-invalidation-secret" },
  1200. filePath: join(credentialsDir, "credentials.json"),
  1201. });
  1202. const sessions: McpOAuthSession[] = [];
  1203. const config = testAuthorizationCodeConfig();
  1204. const keyPrefix = createCredentialKeyPrefix(
  1205. "credential-pair-test",
  1206. "https://mcp.example.test/mcp",
  1207. config,
  1208. );
  1209. try {
  1210. await credentialStore.save(
  1211. `${keyPrefix}:client_information`,
  1212. JSON.stringify(dynamicClientInformation("legacy-client")),
  1213. );
  1214. await credentialStore.save(
  1215. `${keyPrefix}:tokens`,
  1216. JSON.stringify(oauthTokens("legacy-client")),
  1217. );
  1218. const session = await createTestOAuthSession(credentialStore, "legacy-invalidation");
  1219. sessions.push(session);
  1220. await expect(session.provider.clientInformation()).resolves.toBeDefined();
  1221. await expect(session.provider.tokens()).resolves.toBeDefined();
  1222. await session.provider.invalidateCredentials?.("client");
  1223. await expect(credentialStore.load(`${keyPrefix}:client_information`)).resolves.toBeNull();
  1224. await expect(credentialStore.load(`${keyPrefix}:tokens`)).resolves.toBeNull();
  1225. } finally {
  1226. await Promise.all(sessions.map((session) => session.close()));
  1227. await rm(credentialsDir, { force: true, recursive: true });
  1228. }
  1229. });
  1230. it("discovers authorization_code OAuth for a bare HTTP MCP config", async () => {
  1231. const authorizationRequests: Array<Record<string, string>> = [];
  1232. const authTokenRequests: Array<Record<string, string>> = [];
  1233. const mcpAuthorizations: string[] = [];
  1234. const registrationRequests: Array<Record<string, unknown>> = [];
  1235. const pkceChallenges = new Map<string, string>();
  1236. let authBaseUrl = "";
  1237. const authServer = await listen(
  1238. createServer(async (req, res) => {
  1239. await handleAuthorizationCodeAuthServerRequest(req, res, {
  1240. authBaseUrl,
  1241. authorizationRequests,
  1242. pkceChallenges,
  1243. registrationRequests,
  1244. tokenRequests: authTokenRequests,
  1245. });
  1246. }),
  1247. );
  1248. authBaseUrl = serverBaseUrl(authServer);
  1249. let mcpUrl = "";
  1250. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  1251. const mcpServer = await listen(
  1252. createServer(async (req, res) => {
  1253. await handleProtectedMcpRequest(req, res, {
  1254. authBaseUrl,
  1255. authorizations: mcpAuthorizations,
  1256. mcpUrl,
  1257. resourceMetadataPath,
  1258. });
  1259. }),
  1260. );
  1261. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  1262. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-auto-"));
  1263. const credentialStore = createSharedZCodeCredentialStore({
  1264. env: {
  1265. ZCODE_CREDENTIAL_SECRET: "mcp-oauth-e2e-secret",
  1266. },
  1267. filePath: join(credentialsDir, "credentials.json"),
  1268. });
  1269. const adapter = createMcpAdapter({
  1270. mcpOAuth: {
  1271. authorizationTimeoutMs: 5_000,
  1272. credentialStore,
  1273. openAuthorizationUrl: async ({ authorizationUrl }) => {
  1274. const authorizationResponse = await fetch(authorizationUrl, {
  1275. redirect: "manual",
  1276. });
  1277. expect(authorizationResponse.status).toBe(302);
  1278. const location = authorizationResponse.headers.get("location");
  1279. if (!location) {
  1280. throw new Error("Authorization server did not redirect to callback URL");
  1281. }
  1282. const callbackResponse = await fetch(location);
  1283. expect(callbackResponse.status).toBe(200);
  1284. },
  1285. },
  1286. });
  1287. try {
  1288. const status = await adapter.connectServer("notion", {
  1289. type: "http",
  1290. url: mcpUrl,
  1291. });
  1292. expect(status).toMatchObject({
  1293. status: "connected",
  1294. toolCount: 1,
  1295. transport: "http",
  1296. });
  1297. await expect(adapter.listTools()).resolves.toMatchObject([
  1298. {
  1299. serverName: "notion",
  1300. toolName: "oauth_ping",
  1301. },
  1302. ]);
  1303. expect(registrationRequests).toHaveLength(1);
  1304. expect(registrationRequests[0]).toMatchObject({
  1305. client_name: "ZCode notion",
  1306. grant_types: ["authorization_code", "refresh_token"],
  1307. response_types: ["code"],
  1308. scope: MCP_SCOPE,
  1309. });
  1310. expect(authorizationRequests).toEqual([
  1311. expect.objectContaining({
  1312. client_id: DYNAMIC_CLIENT_ID,
  1313. resource: mcpUrl,
  1314. response_type: "code",
  1315. scope: MCP_SCOPE,
  1316. }),
  1317. ]);
  1318. expect(authTokenRequests).toEqual([
  1319. expect.objectContaining({
  1320. code: "interactive-code-1",
  1321. grant_type: "authorization_code",
  1322. resource: mcpUrl,
  1323. }),
  1324. ]);
  1325. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  1326. } finally {
  1327. await adapter.close();
  1328. await rm(credentialsDir, { force: true, recursive: true });
  1329. }
  1330. });
  1331. it("isolates persisted authorization_code credentials by authorization config", async () => {
  1332. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-"));
  1333. const credentialStore = createSharedZCodeCredentialStore({
  1334. env: {
  1335. ZCODE_CREDENTIAL_SECRET: "mcp-oauth-e2e-secret",
  1336. },
  1337. filePath: join(credentialsDir, "credentials.json"),
  1338. });
  1339. const serverName = "figma";
  1340. const serverUrl = "https://mcp.example.test/mcp";
  1341. const keyPrefixA = createCredentialKeyPrefix(serverName, serverUrl, {
  1342. type: "authorization_code",
  1343. clientName: "ZCode Test",
  1344. scope: MCP_SCOPE,
  1345. });
  1346. const keyPrefixB = createCredentialKeyPrefix(serverName, serverUrl, {
  1347. type: "authorization_code",
  1348. clientName: "ZCode Test",
  1349. scope: "mcp:tools:readonly",
  1350. });
  1351. try {
  1352. await credentialStore.save(
  1353. `${keyPrefixA}:client_information`,
  1354. JSON.stringify({
  1355. client_id: DYNAMIC_CLIENT_ID,
  1356. client_secret: DYNAMIC_CLIENT_SECRET,
  1357. }),
  1358. );
  1359. await credentialStore.save(
  1360. `${keyPrefixA}:tokens`,
  1361. JSON.stringify({
  1362. access_token: OAUTH_ACCESS_TOKEN,
  1363. refresh_token: "oauth-e2e-refresh-token",
  1364. token_type: "Bearer",
  1365. }),
  1366. );
  1367. expect(keyPrefixB).not.toBe(keyPrefixA);
  1368. await expect(credentialStore.load(`${keyPrefixA}:client_information`)).resolves.toContain(
  1369. DYNAMIC_CLIENT_ID,
  1370. );
  1371. await expect(credentialStore.load(`${keyPrefixA}:tokens`)).resolves.toContain(
  1372. OAUTH_ACCESS_TOKEN,
  1373. );
  1374. await expect(credentialStore.load(`${keyPrefixB}:client_information`)).resolves.toBeNull();
  1375. await expect(credentialStore.load(`${keyPrefixB}:tokens`)).resolves.toBeNull();
  1376. } finally {
  1377. await rm(credentialsDir, { force: true, recursive: true });
  1378. }
  1379. });
  1380. });
  1381. async function handleAuthServerRequest(
  1382. req: IncomingMessage,
  1383. res: ServerResponse,
  1384. options: {
  1385. authBaseUrl: string;
  1386. tokenRequests: Array<Record<string, string>>;
  1387. },
  1388. ): Promise<void> {
  1389. const url = new URL(req.url ?? "/", "http://localhost");
  1390. if (req.method === "GET" && url.pathname === "/.well-known/oauth-authorization-server") {
  1391. sendJson(res, 200, {
  1392. issuer: options.authBaseUrl,
  1393. authorization_endpoint: `${options.authBaseUrl}/authorize`,
  1394. token_endpoint: `${options.authBaseUrl}/token`,
  1395. response_types_supported: ["code"],
  1396. grant_types_supported: ["client_credentials"],
  1397. token_endpoint_auth_methods_supported: ["client_secret_basic"],
  1398. });
  1399. return;
  1400. }
  1401. if (req.method === "POST" && url.pathname === "/token") {
  1402. if (!isValidClientSecretBasic(req.headers.authorization)) {
  1403. sendJson(res, 401, {
  1404. error: "invalid_client",
  1405. });
  1406. return;
  1407. }
  1408. const body = new URLSearchParams(await readRequestBody(req));
  1409. options.tokenRequests.push(Object.fromEntries(body.entries()));
  1410. sendJson(res, 200, {
  1411. access_token: OAUTH_ACCESS_TOKEN,
  1412. expires_in: 3600,
  1413. scope: body.get("scope") ?? MCP_SCOPE,
  1414. token_type: "Bearer",
  1415. });
  1416. return;
  1417. }
  1418. res.writeHead(404);
  1419. res.end();
  1420. }
  1421. async function handleAuthorizationCodeAuthServerRequest(
  1422. req: IncomingMessage,
  1423. res: ServerResponse,
  1424. options: {
  1425. authBaseUrl: string;
  1426. authorizationRequests: Array<Record<string, string>>;
  1427. /**
  1428. * 要求 redirect_uri 与注册值完全一致(含端口)。
  1429. *
  1430. * 默认的 loopback 比较按 RFC 8252 忽略端口,这恰好掩盖了根因 2:真实授权服务器(如
  1431. * auth.exa.ai)可能做精确匹配,失配时按 RFC 6749 §4.1.2.1 禁止回跳、就地渲染错误页。
  1432. */
  1433. exactRedirectUriMatch?: boolean;
  1434. pkceChallenges: Map<string, string>;
  1435. registrationRequests: Array<Record<string, unknown>>;
  1436. strictAuthorizationState?: StrictAuthorizationServerState;
  1437. tokenRequests: Array<Record<string, string>>;
  1438. },
  1439. ): Promise<void> {
  1440. const url = new URL(req.url ?? "/", "http://localhost");
  1441. if (req.method === "GET" && url.pathname === "/.well-known/oauth-authorization-server") {
  1442. sendJson(res, 200, {
  1443. issuer: options.authBaseUrl,
  1444. authorization_endpoint: `${options.authBaseUrl}/authorize`,
  1445. token_endpoint: `${options.authBaseUrl}/token`,
  1446. registration_endpoint: `${options.authBaseUrl}/register`,
  1447. response_types_supported: ["code"],
  1448. grant_types_supported: ["authorization_code", "refresh_token"],
  1449. token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"],
  1450. code_challenge_methods_supported: ["S256"],
  1451. scopes_supported: [MCP_SCOPE],
  1452. });
  1453. return;
  1454. }
  1455. if (req.method === "POST" && url.pathname === "/register") {
  1456. const body = JSON.parse(await readRequestBody(req)) as Record<string, unknown>;
  1457. options.registrationRequests.push(body);
  1458. const registrationIndex = options.registrationRequests.length;
  1459. const clientId = options.strictAuthorizationState
  1460. ? `${DYNAMIC_CLIENT_ID}-${registrationIndex}`
  1461. : DYNAMIC_CLIENT_ID;
  1462. const clientSecret = options.strictAuthorizationState
  1463. ? `${DYNAMIC_CLIENT_SECRET}-${registrationIndex}`
  1464. : DYNAMIC_CLIENT_SECRET;
  1465. if (options.strictAuthorizationState) {
  1466. const redirectUris = Array.isArray(body.redirect_uris)
  1467. ? body.redirect_uris.filter((entry): entry is string => typeof entry === "string")
  1468. : [];
  1469. options.strictAuthorizationState.clients.set(clientId, { clientSecret, redirectUris });
  1470. }
  1471. sendJson(res, 201, {
  1472. ...body,
  1473. client_id: clientId,
  1474. client_secret: clientSecret,
  1475. client_id_issued_at: 1,
  1476. client_secret_expires_at: 0,
  1477. token_endpoint_auth_method: "client_secret_basic",
  1478. });
  1479. return;
  1480. }
  1481. if (req.method === "GET" && url.pathname === "/authorize") {
  1482. options.authorizationRequests.push(Object.fromEntries(url.searchParams.entries()));
  1483. const clientId = url.searchParams.get("client_id") ?? "";
  1484. const redirectUri = url.searchParams.get("redirect_uri");
  1485. const codeChallenge = url.searchParams.get("code_challenge");
  1486. const registeredClient = options.strictAuthorizationState?.clients.get(clientId);
  1487. if (
  1488. !redirectUri ||
  1489. !codeChallenge ||
  1490. url.searchParams.get("code_challenge_method") !== "S256" ||
  1491. (options.strictAuthorizationState &&
  1492. (!registeredClient ||
  1493. !registeredClient.redirectUris.some((registeredUri) =>
  1494. options.exactRedirectUriMatch
  1495. ? redirectUri === registeredUri
  1496. : matchesRegisteredRedirectUri(redirectUri, registeredUri),
  1497. )))
  1498. ) {
  1499. sendJson(res, 400, {
  1500. error: "invalid_request",
  1501. });
  1502. return;
  1503. }
  1504. const authorizationCode = `interactive-code-${options.authorizationRequests.length}`;
  1505. options.pkceChallenges.set(authorizationCode, codeChallenge);
  1506. options.strictAuthorizationState?.authorizationCodes.set(authorizationCode, {
  1507. clientId,
  1508. codeChallenge,
  1509. redirectUri,
  1510. });
  1511. const callbackUrl = new URL(redirectUri);
  1512. callbackUrl.searchParams.set("code", authorizationCode);
  1513. const state = url.searchParams.get("state");
  1514. if (state) callbackUrl.searchParams.set("state", state);
  1515. res.writeHead(302, {
  1516. Location: callbackUrl.toString(),
  1517. });
  1518. res.end();
  1519. return;
  1520. }
  1521. if (req.method === "POST" && url.pathname === "/token") {
  1522. const body = new URLSearchParams(await readRequestBody(req));
  1523. const clientCredentials = parseClientSecretBasic(req.headers.authorization);
  1524. options.tokenRequests.push({
  1525. ...Object.fromEntries(body.entries()),
  1526. ...(clientCredentials ? { client_id: clientCredentials.clientId } : {}),
  1527. });
  1528. if (body.get("grant_type") === "refresh_token") {
  1529. const refreshToken = body.get("refresh_token") ?? "";
  1530. const refreshClientId = options.strictAuthorizationState?.refreshTokens.get(refreshToken);
  1531. const refreshClient = refreshClientId
  1532. ? options.strictAuthorizationState?.clients.get(refreshClientId)
  1533. : undefined;
  1534. if (
  1535. !refreshClientId ||
  1536. !refreshClient ||
  1537. clientCredentials?.clientId !== refreshClientId ||
  1538. clientCredentials.clientSecret !== refreshClient.clientSecret
  1539. ) {
  1540. sendJson(res, 400, { error: "invalid_grant" });
  1541. return;
  1542. }
  1543. sendJson(res, 200, {
  1544. access_token: `${refreshClientId}-refreshed-access-token`,
  1545. expires_in: 3600,
  1546. refresh_token: refreshToken,
  1547. scope: MCP_SCOPE,
  1548. token_type: "Bearer",
  1549. });
  1550. return;
  1551. }
  1552. const authorizationCode = body.get("code") ?? "";
  1553. const codeVerifier = body.get("code_verifier") ?? "";
  1554. const expectedChallenge = options.pkceChallenges.get(authorizationCode);
  1555. const actualChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
  1556. const strictAuthorization =
  1557. options.strictAuthorizationState?.authorizationCodes.get(authorizationCode);
  1558. const strictClient = strictAuthorization
  1559. ? options.strictAuthorizationState?.clients.get(strictAuthorization.clientId)
  1560. : undefined;
  1561. const hasValidClient = options.strictAuthorizationState
  1562. ? Boolean(
  1563. strictAuthorization &&
  1564. strictClient &&
  1565. clientCredentials?.clientId === strictAuthorization.clientId &&
  1566. clientCredentials.clientSecret === strictClient.clientSecret &&
  1567. body.get("redirect_uri") === strictAuthorization.redirectUri,
  1568. )
  1569. : isValidClientSecretBasic(
  1570. req.headers.authorization,
  1571. DYNAMIC_CLIENT_ID,
  1572. DYNAMIC_CLIENT_SECRET,
  1573. );
  1574. if (!hasValidClient) {
  1575. sendJson(res, 400, { error: "invalid_grant" });
  1576. return;
  1577. }
  1578. if (!expectedChallenge || actualChallenge !== expectedChallenge) {
  1579. sendJson(res, 400, { error: "invalid_grant" });
  1580. return;
  1581. }
  1582. options.pkceChallenges.delete(authorizationCode);
  1583. options.strictAuthorizationState?.authorizationCodes.delete(authorizationCode);
  1584. sendJson(res, 200, {
  1585. access_token: OAUTH_ACCESS_TOKEN,
  1586. expires_in: 3600,
  1587. refresh_token: "oauth-e2e-refresh-token",
  1588. scope: MCP_SCOPE,
  1589. token_type: "Bearer",
  1590. });
  1591. return;
  1592. }
  1593. res.writeHead(404);
  1594. res.end();
  1595. }
  1596. async function followAuthorizationRedirect(authorizationUrl: string): Promise<void> {
  1597. const authorizationResponse = await fetch(authorizationUrl, { redirect: "manual" });
  1598. expect(authorizationResponse.status).toBe(302);
  1599. const location = authorizationResponse.headers.get("location");
  1600. if (!location) throw new Error("Authorization server did not redirect to callback URL");
  1601. const callbackResponse = await fetch(location);
  1602. expect(callbackResponse.status).toBe(200);
  1603. }
  1604. async function handleProtectedMcpRequest(
  1605. req: IncomingMessage,
  1606. res: ServerResponse,
  1607. options: {
  1608. authBaseUrl: string;
  1609. authorizations: string[];
  1610. /** 调用方已经消费过请求体时传入,避免二次读取空流。 */
  1611. body?: string;
  1612. mcpUrl: string;
  1613. resourceMetadataPath: string;
  1614. /** 403 insufficient_scope challenge 的 scope;置位时对 tools/list 生效。 */
  1615. stepUpScope?: string;
  1616. },
  1617. ): Promise<void> {
  1618. const url = new URL(req.url ?? "/", "http://localhost");
  1619. if (req.method === "GET" && url.pathname === options.resourceMetadataPath) {
  1620. sendJson(res, 200, {
  1621. authorization_servers: [options.authBaseUrl],
  1622. resource: options.mcpUrl,
  1623. resource_name: "ZCode OAuth E2E MCP",
  1624. scopes_supported: [MCP_SCOPE],
  1625. });
  1626. return;
  1627. }
  1628. if (req.method === "GET" && url.pathname === "/mcp") {
  1629. res.writeHead(405);
  1630. res.end();
  1631. return;
  1632. }
  1633. if (req.method !== "POST" || url.pathname !== "/mcp") {
  1634. res.writeHead(404);
  1635. res.end();
  1636. return;
  1637. }
  1638. const authorization = req.headers.authorization;
  1639. if (authorization) options.authorizations.push(authorization);
  1640. if (authorization !== `Bearer ${OAUTH_ACCESS_TOKEN}`) {
  1641. res.writeHead(401, {
  1642. "WWW-Authenticate": [
  1643. `Bearer resource_metadata="${new URL(options.resourceMetadataPath, options.mcpUrl).href}", scope="${MCP_SCOPE}"`,
  1644. ],
  1645. });
  1646. res.end();
  1647. return;
  1648. }
  1649. const message = JSON.parse(options.body ?? (await readRequestBody(req))) as {
  1650. id?: string | number;
  1651. method?: string;
  1652. };
  1653. // 403 insufficient_scope:Bearer 合法但 scope 不足。challenge 同时带 resource_metadata,
  1654. // 验证编排层把 challenge 的发现线索传进 Phase 2(spec §5.2 / §8 item 15)。
  1655. if (options.stepUpScope && message.method === "tools/list") {
  1656. res.writeHead(403, {
  1657. "WWW-Authenticate": [
  1658. `Bearer error="insufficient_scope", scope="${options.stepUpScope}", resource_metadata="${new URL(options.resourceMetadataPath, options.mcpUrl).href}"`,
  1659. ],
  1660. });
  1661. res.end();
  1662. return;
  1663. }
  1664. if (message.method === "initialize") {
  1665. sendJson(res, 200, {
  1666. id: message.id,
  1667. jsonrpc: "2.0",
  1668. result: {
  1669. capabilities: { tools: {} },
  1670. protocolVersion: "2025-11-25",
  1671. serverInfo: {
  1672. name: "oauth-e2e-mcp",
  1673. version: "1.0.0",
  1674. },
  1675. },
  1676. });
  1677. return;
  1678. }
  1679. if (message.method === "tools/list") {
  1680. sendJson(res, 200, {
  1681. id: message.id,
  1682. jsonrpc: "2.0",
  1683. result: {
  1684. tools: [
  1685. {
  1686. description: "OAuth protected ping",
  1687. inputSchema: {
  1688. properties: {},
  1689. type: "object",
  1690. },
  1691. name: "oauth_ping",
  1692. },
  1693. ],
  1694. },
  1695. });
  1696. return;
  1697. }
  1698. if (message.method === "tools/call") {
  1699. sendJson(res, 200, {
  1700. id: message.id,
  1701. jsonrpc: "2.0",
  1702. result: {
  1703. content: [{ type: "text", text: "pong" }],
  1704. isError: false,
  1705. },
  1706. });
  1707. return;
  1708. }
  1709. if (message.method === "server/discover") {
  1710. sendJson(res, 200, {
  1711. error: {
  1712. code: -32601,
  1713. message: "Method not found",
  1714. },
  1715. id: message.id,
  1716. jsonrpc: "2.0",
  1717. });
  1718. return;
  1719. }
  1720. sendJson(res, 202, {});
  1721. }
  1722. function isValidClientSecretBasic(
  1723. value: string | undefined,
  1724. clientId = OAUTH_CLIENT_ID,
  1725. clientSecret = OAUTH_CLIENT_SECRET,
  1726. ): boolean {
  1727. if (!value?.startsWith("Basic ")) return false;
  1728. const decoded = Buffer.from(value.slice("Basic ".length), "base64").toString("utf8");
  1729. return decoded === `${clientId}:${clientSecret}`;
  1730. }
  1731. function createStrictAuthorizationServerState(): StrictAuthorizationServerState {
  1732. return {
  1733. authorizationCodes: new Map(),
  1734. clients: new Map(),
  1735. refreshTokens: new Map(),
  1736. };
  1737. }
  1738. async function createTestOAuthSession(
  1739. credentialStore: SharedZCodeCredentialStore,
  1740. adapterInstanceId: string,
  1741. serverUrl = "https://mcp.example.test/mcp",
  1742. ): Promise<McpOAuthSession> {
  1743. return await createMcpAuthorizationCodeOAuthSession({
  1744. adapterInstanceId,
  1745. config: testAuthorizationCodeConfig(),
  1746. options: { credentialStore },
  1747. serverName: "credential-pair-test",
  1748. serverUrl,
  1749. });
  1750. }
  1751. function testAuthorizationCodeConfig() {
  1752. return {
  1753. type: "authorization_code" as const,
  1754. clientName: "ZCode Credential Pair Test",
  1755. scope: MCP_SCOPE,
  1756. };
  1757. }
  1758. function dynamicClientInformation(clientId: string): OAuthClientInformationMixed {
  1759. return {
  1760. client_id: clientId,
  1761. client_secret: `${clientId}-secret`,
  1762. token_endpoint_auth_method: "client_secret_basic",
  1763. };
  1764. }
  1765. function oauthTokens(clientId: string): OAuthTokens {
  1766. return {
  1767. access_token: `${clientId}-access-token`,
  1768. refresh_token: `${clientId}-refresh-token`,
  1769. token_type: "Bearer",
  1770. };
  1771. }
  1772. function createTestLogger(): { logger: Logger; warn: ReturnType<typeof vi.fn> } {
  1773. const warn = vi.fn();
  1774. const logger: Logger = {
  1775. child: () => logger,
  1776. debug: vi.fn(),
  1777. error: vi.fn(),
  1778. info: vi.fn(),
  1779. warn,
  1780. };
  1781. return { logger, warn };
  1782. }
  1783. async function saveDynamicClientInformation(
  1784. session: McpOAuthSession,
  1785. clientInformation: OAuthClientInformationMixed,
  1786. ): Promise<void> {
  1787. if (!session.provider.saveClientInformation) {
  1788. throw new Error("OAuth provider does not support dynamic client registration");
  1789. }
  1790. await session.provider.saveClientInformation(clientInformation);
  1791. }
  1792. function parseClientSecretBasic(
  1793. value: string | undefined,
  1794. ): { clientId: string; clientSecret: string } | undefined {
  1795. if (!value?.startsWith("Basic ")) return undefined;
  1796. const decoded = Buffer.from(value.slice("Basic ".length), "base64").toString("utf8");
  1797. const separatorIndex = decoded.indexOf(":");
  1798. if (separatorIndex < 0) return undefined;
  1799. return {
  1800. clientId: decoded.slice(0, separatorIndex),
  1801. clientSecret: decoded.slice(separatorIndex + 1),
  1802. };
  1803. }
  1804. function matchesRegisteredRedirectUri(requestedValue: string, registeredValue: string): boolean {
  1805. try {
  1806. const requested = new URL(requestedValue);
  1807. const registered = new URL(registeredValue);
  1808. const isLoopback =
  1809. requested.protocol === "http:" &&
  1810. registered.protocol === "http:" &&
  1811. requested.hostname === registered.hostname &&
  1812. (requested.hostname === "127.0.0.1" || requested.hostname === "[::1]");
  1813. if (!isLoopback) return requested.href === registered.href;
  1814. return (
  1815. requested.pathname === registered.pathname &&
  1816. requested.search === registered.search &&
  1817. requested.hash === registered.hash
  1818. );
  1819. } catch {
  1820. return false;
  1821. }
  1822. }
  1823. /** 统计当前活跃的 TCP server handle 数,用来断言连接期没有新开 callback listener。 */
  1824. function countTcpServers(): number {
  1825. return process.getActiveResourcesInfo().filter((resource) => resource === "TCPSERVERWRAP").length;
  1826. }
  1827. function sendJson(res: ServerResponse, statusCode: number, body: unknown): void {
  1828. res.writeHead(statusCode, {
  1829. "Content-Type": "application/json",
  1830. });
  1831. res.end(JSON.stringify(body));
  1832. }
  1833. async function readRequestBody(req: IncomingMessage): Promise<string> {
  1834. const chunks: Buffer[] = [];
  1835. for await (const chunk of req) {
  1836. chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  1837. }
  1838. return Buffer.concat(chunks).toString("utf8");
  1839. }
  1840. async function listen(server: Server): Promise<Server> {
  1841. await new Promise<void>((resolve) => {
  1842. server.listen(0, "127.0.0.1", resolve);
  1843. });
  1844. servers.push(server);
  1845. return server;
  1846. }
  1847. async function closeServer(server: Server): Promise<void> {
  1848. if (!server.listening) return;
  1849. await new Promise<void>((resolve, reject) => {
  1850. server.close((error) => {
  1851. if (error) reject(error);
  1852. else resolve();
  1853. });
  1854. });
  1855. }
  1856. function serverBaseUrl(server: Server): string {
  1857. const address = server.address();
  1858. if (!address || typeof address === "string") {
  1859. throw new Error("Test server is not listening on a TCP port");
  1860. }
  1861. return `http://127.0.0.1:${address.port}`;
  1862. }