officialMcpCredentials.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. /* OMCP-005/006/009/021/023/024/026/027 —— 官方 MCP 凭证解析与身份头构造(spec §6.1 / §6.2.1 / §6.3.3)。
  2. *
  3. * OMCP-025(Off-Peak 零回归,验证 §6.1.1 的隔离)不是本文件的用例,而是一条回归动作:
  4. * npx vitest run packages/services/test/offPeakRuntimeModel.test.ts \
  5. * packages/services/test/offPeakServerClient.test.ts \
  6. * packages/services/test/offPeakTaskService.test.ts \
  7. * packages/services/test/offPeakE2eIntegration.test.ts \
  8. * packages/services/test/offPeakClientConfig.test.ts \
  9. * packages/services/test/offPeakTaskRepo.test.ts
  10. * 本次实现后为 6 files / 77 tests 全绿,且未修改 offPeakRuntimeModel.ts 的任何导出。
  11. */
  12. import { describe, expect, it, vi } from "vitest";
  13. import { BUILTIN_MODEL_PROVIDER_IDS, type ZCodeAccountAccess } from "@zcode/shared";
  14. import type { ModelSelectionView } from "@zcode/provider";
  15. // 凭证解析日志的级别断言(OMCP-LOG-*):mock 掉 serviceLogger 才能观察到模块级
  16. // `const log` 的调用;该文件其余用例不断言日志,mock 对它们是透明的。
  17. const { serviceInfo } = vi.hoisted(() => ({ serviceInfo: vi.fn() }));
  18. vi.mock("#src/logger/serviceLogger.js", () => ({
  19. createServiceLogger: () => ({
  20. debug: vi.fn(),
  21. info: serviceInfo,
  22. warn: vi.fn(),
  23. error: vi.fn(),
  24. }),
  25. }));
  26. import {
  27. buildOfficialMcpAuthHeaders,
  28. createCredentialResolvedLogKey,
  29. createOfficialMcpAuthHeadersResolver,
  30. resolveOfficialMcpCredentials,
  31. type OfficialMcpCredentialResolverDeps,
  32. } from "../src/official-mcp/officialMcpCredentials.js";
  33. const JWT = "zcode-jwt-value";
  34. /** MaaS 登录 JWT:Coding Plan 凭证自 2026-08 起走这条通道(X-Bigmodel-Authorization)。 */
  35. const MAAS_JWT = "bigmodel-maas-jwt";
  36. const ZAI_MAAS_JWT = "zai-maas-jwt";
  37. function createRegistry(
  38. providers: Array<{ providerId: string; config: { access: Record<string, unknown> } }>,
  39. ): ModelSelectionView {
  40. return { revision: 1, providers } as unknown as ModelSelectionView;
  41. }
  42. function individualProvider(family: "zai" | "bigmodel") {
  43. return {
  44. providerId:
  45. family === "zai"
  46. ? BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
  47. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  48. config: {
  49. access: {
  50. type: "zhipu-account",
  51. accountType: family,
  52. mode: "individual-coding-plan",
  53. entitled: true,
  54. },
  55. },
  56. };
  57. }
  58. function teamProvider(family: "zai" | "bigmodel") {
  59. return {
  60. providerId:
  61. family === "zai"
  62. ? BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan
  63. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  64. config: {
  65. access: {
  66. type: "zhipu-account",
  67. accountType: family,
  68. mode: "team-coding-plan",
  69. entitled: true,
  70. },
  71. },
  72. };
  73. }
  74. interface DepsOverrides {
  75. activeProvider?: string | null;
  76. activeProviderSequence?: Array<string | null>;
  77. jwt?: string | null;
  78. /** 依次返回的 JWT,用于模拟 registry 读取期间的 token 轮换(SG-01)。 */
  79. jwtSequence?: Array<string | null>;
  80. /** 覆盖 `oauth:<provider>:access_token`(MaaS 登录 JWT)。 */
  81. maasJwt?: string | null;
  82. /** 依次返回的 MaaS JWT,用于模拟它在 registry 读取期间轮换。 */
  83. maasJwtSequence?: Array<string | null>;
  84. registry?: ModelSelectionView;
  85. registrySequence?: ModelSelectionView[];
  86. settings?: Record<string, unknown>;
  87. settingsSequence?: Array<Record<string, unknown>>;
  88. accountAccess?: ZCodeAccountAccess | null;
  89. accountAccessSequence?: Array<ZCodeAccountAccess | null>;
  90. }
  91. function createDeps(overrides: DepsOverrides = {}): OfficialMcpCredentialResolverDeps {
  92. let activeProviderCalls = 0;
  93. let jwtCalls = 0;
  94. let maasJwtCalls = 0;
  95. let registryCalls = 0;
  96. let accountAccessCalls = 0;
  97. return {
  98. accountRequestAuthService: {
  99. resolveAccessCurrent: async (access) => {
  100. if (overrides.accountAccessSequence) {
  101. const value =
  102. overrides.accountAccessSequence[
  103. Math.min(accountAccessCalls, overrides.accountAccessSequence.length - 1)
  104. ];
  105. accountAccessCalls += 1;
  106. return value ?? null;
  107. }
  108. if (overrides.accountAccess !== undefined) return overrides.accountAccess;
  109. return access.mode === "individual-coding-plan"
  110. ? {
  111. type: "zhipu-account" as const,
  112. family: access.accountType,
  113. planKind: "individual-coding-plan" as const,
  114. }
  115. : null;
  116. },
  117. },
  118. credentialService: {
  119. load: async (key: string) => {
  120. if (key === "oauth:active_provider") {
  121. if (overrides.activeProviderSequence) {
  122. const value =
  123. overrides.activeProviderSequence[
  124. Math.min(activeProviderCalls, overrides.activeProviderSequence.length - 1)
  125. ];
  126. activeProviderCalls += 1;
  127. return value ?? null;
  128. }
  129. return overrides.activeProvider === undefined ? "bigmodel" : overrides.activeProvider;
  130. }
  131. if (key === "zcodejwttoken") {
  132. if (overrides.jwtSequence) {
  133. const value =
  134. overrides.jwtSequence[Math.min(jwtCalls, overrides.jwtSequence.length - 1)];
  135. jwtCalls += 1;
  136. return value ?? null;
  137. }
  138. return overrides.jwt === undefined ? JWT : overrides.jwt;
  139. }
  140. // MaaS 登录 JWT 按 family 精确取键,禁止跨 family 回退。
  141. if (key === "oauth:bigmodel:access_token" || key === "oauth:zai:access_token") {
  142. if (overrides.maasJwtSequence) {
  143. const value =
  144. overrides.maasJwtSequence[
  145. Math.min(maasJwtCalls, overrides.maasJwtSequence.length - 1)
  146. ];
  147. maasJwtCalls += 1;
  148. return value ?? null;
  149. }
  150. if (overrides.maasJwt !== undefined) return overrides.maasJwt;
  151. return key === "oauth:zai:access_token" ? ZAI_MAAS_JWT : MAAS_JWT;
  152. }
  153. return null;
  154. },
  155. },
  156. modelSelectionService: {
  157. getView: async () => {
  158. const fallback = overrides.registry ?? createRegistry([individualProvider("bigmodel")]);
  159. const value =
  160. overrides.registrySequence?.[
  161. Math.min(registryCalls, overrides.registrySequence.length - 1)
  162. ];
  163. registryCalls += 1;
  164. return value ?? fallback;
  165. },
  166. },
  167. };
  168. }
  169. describe("official mcp credential resolver", () => {
  170. it("OMCP-021: emits PERSONAL target type for a personal coding plan", async () => {
  171. const outcome = await resolveOfficialMcpCredentials(createDeps());
  172. expect(outcome).toMatchObject({ ok: true });
  173. if (!outcome.ok) return;
  174. expect(outcome.snapshot.planScope).toEqual({ targetType: "PERSONAL" });
  175. expect(outcome.snapshot.wireScope).toEqual({ targetType: "PERSONAL" });
  176. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  177. Authorization: `Bearer ${JWT}`,
  178. "Bigmodel-Target-Type": "PERSONAL",
  179. "X-Bigmodel-Authorization": `Bearer ${MAAS_JWT}`,
  180. });
  181. // 旧通道必须彻底消失:两个头同时发会让服务端额外校验 API key 归属,
  182. // 一把过期 key 就能让整个请求 403。
  183. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)["X-Coding-Plan-Api-Key"]).toBeUndefined();
  184. });
  185. it("OMCP-005/021: emits TEAM target type with paired identity for a BigModel team plan", async () => {
  186. const outcome = await resolveOfficialMcpCredentials(
  187. createDeps({
  188. registry: createRegistry([teamProvider("bigmodel")]),
  189. accountAccess: {
  190. type: "zhipu-account",
  191. family: "bigmodel",
  192. planKind: "team-coding-plan",
  193. productId: "coding",
  194. organizationId: "org-1",
  195. projectId: "project-1",
  196. },
  197. settings: {
  198. providerFamilyConnectionSelections: {
  199. bigmodel: {
  200. kind: "team-coding-plan",
  201. productId: "coding",
  202. organizationId: "org-1",
  203. projectId: "project-1",
  204. },
  205. },
  206. providerFamilyDomain: "bigmodel",
  207. },
  208. }),
  209. );
  210. expect(outcome).toMatchObject({ ok: true });
  211. if (!outcome.ok) return;
  212. expect(outcome.snapshot).toMatchObject({
  213. planScope: {
  214. organizationId: "org-1",
  215. projectId: "project-1",
  216. targetType: "TEAM",
  217. },
  218. wireScope: {
  219. organizationId: "org-1",
  220. projectId: "project-1",
  221. targetType: "TEAM",
  222. },
  223. });
  224. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  225. Authorization: `Bearer ${JWT}`,
  226. "Bigmodel-Organization": "org-1",
  227. "Bigmodel-Project": "project-1",
  228. "Bigmodel-Target-Type": "TEAM",
  229. "X-Bigmodel-Authorization": `Bearer ${MAAS_JWT}`,
  230. });
  231. });
  232. it("OMCP-006: wireScope=null never emits partial team headers", () => {
  233. expect(
  234. buildOfficialMcpAuthHeaders({
  235. codingPlanAuthorization: MAAS_JWT,
  236. jwt: JWT,
  237. planScope: null,
  238. providerFamily: "bigmodel",
  239. wireScope: null,
  240. }),
  241. ).toEqual({
  242. Authorization: `Bearer ${JWT}`,
  243. "X-Bigmodel-Authorization": `Bearer ${MAAS_JWT}`,
  244. });
  245. });
  246. it("OMCP-021: keeps zai-team consistent with Off-Peak by omitting Target-Type entirely", async () => {
  247. const outcome = await resolveOfficialMcpCredentials(
  248. createDeps({
  249. activeProvider: "zai",
  250. registry: createRegistry([teamProvider("zai")]),
  251. accountAccess: {
  252. type: "zhipu-account",
  253. family: "zai",
  254. planKind: "team-coding-plan",
  255. productId: "coding",
  256. organizationId: "org-z",
  257. projectId: "project-z",
  258. },
  259. settings: {
  260. providerFamilyConnectionSelections: {
  261. zai: {
  262. kind: "team-coding-plan",
  263. productId: "coding",
  264. organizationId: "org-z",
  265. projectId: "project-z",
  266. },
  267. },
  268. providerFamilyDomain: "zai",
  269. },
  270. }),
  271. );
  272. expect(outcome).toMatchObject({ ok: true });
  273. if (!outcome.ok) return;
  274. expect(outcome.snapshot.planScope).toEqual({
  275. organizationId: "org-z",
  276. projectId: "project-z",
  277. targetType: "TEAM",
  278. });
  279. expect(outcome.snapshot.wireScope).toBeNull();
  280. const headers = buildOfficialMcpAuthHeaders(outcome.snapshot);
  281. expect(headers["Bigmodel-Target-Type"]).toBeUndefined();
  282. expect(headers["Bigmodel-Organization"]).toBeUndefined();
  283. expect(headers["Bigmodel-Project"]).toBeUndefined();
  284. });
  285. it("OMCP-023: sends only the ZCode JWT for a Start Plan connection", async () => {
  286. const outcome = await resolveOfficialMcpCredentials(
  287. createDeps({
  288. registry: createRegistry([
  289. {
  290. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  291. config: {
  292. access: {
  293. type: "zhipu-account",
  294. family: "bigmodel",
  295. mode: "start-plan",
  296. },
  297. },
  298. },
  299. ]),
  300. }),
  301. );
  302. expect(outcome).toEqual({
  303. ok: true,
  304. snapshot: {
  305. jwt: JWT,
  306. planScope: null,
  307. providerFamily: "bigmodel",
  308. wireScope: null,
  309. },
  310. });
  311. if (!outcome.ok) return;
  312. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  313. Authorization: `Bearer ${JWT}`,
  314. });
  315. });
  316. it("OMCP-009: reports unavailable when not logged in and plan-required without Account Access", async () => {
  317. await expect(resolveOfficialMcpCredentials(createDeps({ jwt: "" }))).resolves.toEqual({
  318. ok: false,
  319. reason: "official_auth_unavailable",
  320. });
  321. await expect(
  322. resolveOfficialMcpCredentials(
  323. createDeps({
  324. accountAccess: null,
  325. registry: createRegistry([individualProvider("bigmodel")]),
  326. }),
  327. ),
  328. ).resolves.toEqual({ ok: false, reason: "official_auth_plan_required" });
  329. });
  330. it("rejects a login identity that does not match the selected family", async () => {
  331. // ZAI JWT + BigModel key 拼进同一请求,服务端只能在业务校验时才拒绝,这里提前挡掉。
  332. await expect(
  333. resolveOfficialMcpCredentials(createDeps({ activeProvider: "zai" })),
  334. ).resolves.toEqual({ ok: false, reason: "official_auth_unavailable" });
  335. });
  336. it("sends only the ZCode JWT when the selected coding plan connection is absent", async () => {
  337. const outcome = await resolveOfficialMcpCredentials(
  338. createDeps({ registry: createRegistry([]) }),
  339. );
  340. expect(outcome).toMatchObject({ ok: true });
  341. if (!outcome.ok) return;
  342. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  343. Authorization: `Bearer ${JWT}`,
  344. });
  345. });
  346. it("does not require a MaaS JWT when no Coding Plan provider is selected", async () => {
  347. const outcome = await resolveOfficialMcpCredentials(
  348. createDeps({ maasJwt: null, registry: createRegistry([]) }),
  349. );
  350. expect(outcome).toMatchObject({ ok: true });
  351. if (!outcome.ok) return;
  352. expect(outcome.snapshot.codingPlanAuthorization).toBeUndefined();
  353. });
  354. it("rejects an identity-only snapshot while the active provider remains unstable", async () => {
  355. await expect(
  356. resolveOfficialMcpCredentials(
  357. createDeps({
  358. activeProviderSequence: ["bigmodel", "zai", "bigmodel", "zai"],
  359. registry: createRegistry([]),
  360. }),
  361. ),
  362. ).resolves.toEqual({ ok: false, reason: "official_auth_unavailable" });
  363. });
  364. it("still resolves when the connection exists but its business key is absent", async () => {
  365. // 行为变更(2026-08):业务 key 不再是凭证,因此不再当门槛。此前"key 正在刷新"的瞬态
  366. // 会被误判成"没有套餐",把一次本可成功的调用挡在本地。
  367. const outcome = await resolveOfficialMcpCredentials(
  368. createDeps({
  369. registry: createRegistry([individualProvider("bigmodel")]),
  370. }),
  371. );
  372. expect(outcome).toMatchObject({ ok: true });
  373. if (!outcome.ok) return;
  374. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)["X-Bigmodel-Authorization"]).toBe(
  375. `Bearer ${MAAS_JWT}`,
  376. );
  377. });
  378. it("reports official_auth_unavailable when the MaaS login JWT is missing", async () => {
  379. // 登录态不完整(需重新登录),不是"没有套餐"——两个 provider adapter 登录时都硬性要求
  380. // 写入该 token,因此这主要出现在历史迁移过来的旧登录态上。
  381. await expect(resolveOfficialMcpCredentials(createDeps({ maasJwt: "" }))).resolves.toEqual({
  382. ok: false,
  383. reason: "official_auth_unavailable",
  384. });
  385. });
  386. it("takes the MaaS JWT of the selected family, never the other one", async () => {
  387. const outcome = await resolveOfficialMcpCredentials(
  388. createDeps({
  389. activeProvider: "zai",
  390. registry: createRegistry([individualProvider("zai")]),
  391. settings: {
  392. providerFamilyConnectionSelections: {
  393. zai: { kind: "individual-coding-plan" },
  394. },
  395. providerFamilyDomain: "zai",
  396. },
  397. }),
  398. );
  399. expect(outcome).toMatchObject({ ok: true });
  400. if (!outcome.ok) return;
  401. // 跨 family 回退会发出一次注定失败的请求,且失败原因会指向"没有套餐"这种误导结论。
  402. expect(outcome.snapshot.codingPlanAuthorization).toBe(ZAI_MAAS_JWT);
  403. expect(outcome.snapshot.codingPlanAuthorization).not.toBe(MAAS_JWT);
  404. });
  405. it("re-resolves once when the selection changes mid-flight, then gives up", async () => {
  406. // 前后指纹不一致必须重来,绝不拼接两代凭证。两轮都不稳定则按不可用返回。
  407. const flipping = [
  408. createRegistry([individualProvider("bigmodel")]),
  409. createRegistry([individualProvider("zai")]),
  410. ];
  411. const outcome = await resolveOfficialMcpCredentials(
  412. createDeps({ registrySequence: [flipping[0]!, flipping[1]!, flipping[0]!, flipping[1]!] }),
  413. );
  414. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  415. });
  416. it("动态 Team scope 在解析前后变化时不拼接两代身份", async () => {
  417. const teamAccess = (projectId: string): ZCodeAccountAccess => ({
  418. type: "zhipu-account",
  419. family: "bigmodel",
  420. planKind: "team-coding-plan",
  421. productId: "coding",
  422. organizationId: "org-1",
  423. projectId,
  424. });
  425. const outcome = await resolveOfficialMcpCredentials(
  426. createDeps({
  427. registry: createRegistry([teamProvider("bigmodel")]),
  428. accountAccessSequence: [
  429. teamAccess("project-a"),
  430. teamAccess("project-b"),
  431. teamAccess("project-a"),
  432. teamAccess("project-b"),
  433. ],
  434. }),
  435. );
  436. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  437. });
  438. it("SG-01: discards the round when the JWT rotates during the registry read", async () => {
  439. // 读取顺序:每轮 首次 JWT -> registry -> 二次一致性检查再读 JWT。
  440. // 四个互不相同的值让**两轮**的前后读取都不一致 => 按不可用返回,
  441. // 绝不产出"旧 JWT + 新 key"的混代快照。
  442. const outcome = await resolveOfficialMcpCredentials(
  443. createDeps({
  444. jwtSequence: ["jwt-gen-1", "jwt-gen-2", "jwt-gen-3", "jwt-gen-4"],
  445. }),
  446. );
  447. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  448. });
  449. it("discards the round when the MaaS JWT rotates during the registry read", async () => {
  450. // 与上一条同理:MaaS JWT 现在是真正的 Coding Plan 凭证,必须一起纳入前后一致性检查,
  451. // 否则会拼出"旧 zcode JWT + 新 MaaS JWT"的混代快照。
  452. const outcome = await resolveOfficialMcpCredentials(
  453. createDeps({
  454. maasJwtSequence: ["maas-gen-1", "maas-gen-2", "maas-gen-3", "maas-gen-4"],
  455. }),
  456. );
  457. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  458. });
  459. it("SG-01: accepts the snapshot when the JWT stays stable across the registry read", async () => {
  460. // 第 1、2 次读取一致(同一代),必须成功且快照使用该 JWT。
  461. const outcome = await resolveOfficialMcpCredentials(
  462. createDeps({ jwtSequence: ["jwt-stable", "jwt-stable"] }),
  463. );
  464. expect(outcome).toMatchObject({ ok: true });
  465. if (!outcome.ok) return;
  466. expect(outcome.snapshot.jwt).toBe("jwt-stable");
  467. });
  468. it("SG-01: recovers when the JWT rotates once and then settles", async () => {
  469. // 第一轮不一致(gen1 -> gen2),第二轮稳定在 gen2 => 最终成功且用 gen2。
  470. const outcome = await resolveOfficialMcpCredentials(
  471. createDeps({ jwtSequence: ["jwt-gen-1", "jwt-gen-2", "jwt-gen-2", "jwt-gen-2"] }),
  472. );
  473. expect(outcome).toMatchObject({ ok: true });
  474. if (!outcome.ok) return;
  475. expect(outcome.snapshot.jwt).toBe("jwt-gen-2");
  476. });
  477. it("OMCP-024: has no mock credential branch at all", async () => {
  478. // Off-Peak 的 ZCODE_OFFPEAK_MOCK 占位凭证分支不得在官方 MCP 路径复现。
  479. const previous = process.env["ZCODE_OFFPEAK_MOCK"];
  480. process.env["ZCODE_OFFPEAK_MOCK"] = "1";
  481. try {
  482. const outcome = await resolveOfficialMcpCredentials(createDeps({ jwt: "" }));
  483. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  484. const ok = await resolveOfficialMcpCredentials(createDeps());
  485. expect(ok).toMatchObject({ ok: true });
  486. if (!ok.ok) return;
  487. expect(ok.snapshot.jwt).toBe(JWT);
  488. expect(ok.snapshot.codingPlanAuthorization).toBe(MAAS_JWT);
  489. } finally {
  490. if (previous === undefined) delete process.env["ZCODE_OFFPEAK_MOCK"];
  491. else process.env["ZCODE_OFFPEAK_MOCK"] = previous;
  492. }
  493. });
  494. it("OMCP-026: dedupes concurrent resolves into a single underlying resolution", async () => {
  495. const deps = createDeps();
  496. const spy = vi.spyOn(deps.modelSelectionService, "getView");
  497. const resolver = createOfficialMcpAuthHeadersResolver(deps);
  498. const results = await Promise.all([
  499. resolver.resolveHeaders(),
  500. resolver.resolveHeaders(),
  501. resolver.resolveHeaders(),
  502. resolver.resolveHeaders(),
  503. ]);
  504. expect(spy).toHaveBeenCalledTimes(2);
  505. for (const result of results) {
  506. expect(result).toEqual(results[0]);
  507. }
  508. });
  509. it("OMCP-027: re-resolves after settle, so a connection switch is picked up", async () => {
  510. const deps = createDeps();
  511. const spy = vi.spyOn(deps.modelSelectionService, "getView");
  512. const resolver = createOfficialMcpAuthHeadersResolver(deps);
  513. await resolver.resolveHeaders();
  514. await resolver.resolveHeaders();
  515. // 无时间维度缓存:顺序两次调用必须各解析一遍
  516. expect(spy).toHaveBeenCalledTimes(4);
  517. });
  518. it("clears the in-flight slot when a resolution throws", async () => {
  519. let shouldThrow = true;
  520. const deps = createDeps();
  521. deps.modelSelectionService.getView = async () => {
  522. if (shouldThrow) throw new Error("registry unavailable");
  523. return createRegistry([individualProvider("bigmodel")]);
  524. };
  525. const resolver = createOfficialMcpAuthHeadersResolver(deps);
  526. await expect(resolver.resolveHeaders()).rejects.toThrow("registry unavailable");
  527. shouldThrow = false;
  528. // 失败的 Promise 不得被后续请求永久复用
  529. await expect(resolver.resolveHeaders()).resolves.toMatchObject({ ok: true });
  530. });
  531. });
  532. /* OMCP-LOG —— 凭证解析成功日志:info 级 + 小时分桶去重(spec §4 审计规则)。
  533. *
  534. * 背景:MaaS JWT 无刷新链路,过期被服务端 3101 折叠成 "coding plan is required"(2026-09-12
  535. * 用户事故),剩余有效期是客户端唯一可自证的线索,因此必须 info(生产 debug 不落盘);
  536. * 但解析与官方 MCP 请求数同数量级,必须去重(见 createCredentialResolvedLogKey)。
  537. */
  538. describe("official mcp credential resolved log", () => {
  539. it("OMCP-LOG-01: dedup key buckets expiry by hour and separates family/scope", () => {
  540. const personal = { providerFamily: "bigmodel", planTargetType: "PERSONAL" } as const;
  541. expect(
  542. createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: 3600 }),
  543. ).toBe("bigmodel|PERSONAL|t1");
  544. // 桶边界:3599 落在 t0,跨过 3600 进入 t1
  545. expect(
  546. createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: 3599 }),
  547. ).toBe("bigmodel|PERSONAL|t0");
  548. // 过期(≤0)与解析失败(undefined)是独立桶:跨过零点、token 形态变化必落新键
  549. expect(
  550. createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: -5 }),
  551. ).toBe("bigmodel|PERSONAL|expired");
  552. expect(
  553. createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: undefined }),
  554. ).toBe("bigmodel|PERSONAL|unparsable");
  555. expect(
  556. createCredentialResolvedLogKey({
  557. providerFamily: "zai",
  558. planTargetType: null,
  559. maasJwtExpiresInSeconds: 100,
  560. }),
  561. ).toBe("zai|none|t0");
  562. // PERSONAL↔TEAM 切换是身份头语义变化,必须可分辨
  563. expect(
  564. createCredentialResolvedLogKey({
  565. providerFamily: "zai",
  566. planTargetType: "TEAM",
  567. maasJwtExpiresInSeconds: 100,
  568. }),
  569. ).not.toBe(
  570. createCredentialResolvedLogKey({
  571. providerFamily: "zai",
  572. planTargetType: "PERSONAL",
  573. maasJwtExpiresInSeconds: 100,
  574. }),
  575. );
  576. });
  577. it("OMCP-LOG-02: logs jwt expiry at info level and dedupes same-bucket re-resolves", async () => {
  578. // 123456s ≈ 34.3h → t34 桶:本文件其他用例都用解析不出 exp 的假 token(unparsable
  579. // 桶),独特桶值保证本用例首调不被模块级去重键吞掉,用例间不依赖执行顺序。
  580. const deps = createDeps({ maasJwt: makeMaasJwtWithExpiry(123456) });
  581. serviceInfo.mockClear();
  582. const first = await resolveOfficialMcpCredentials(deps);
  583. expect(first.ok).toBe(true);
  584. const resolvedCalls = () =>
  585. serviceInfo.mock.calls.filter(
  586. (call): call is [string, Record<string, unknown>] =>
  587. call[0] === "official mcp credentials resolved",
  588. );
  589. expect(resolvedCalls()).toHaveLength(1);
  590. const fields = resolvedCalls()[0]![1]!;
  591. expect(fields).toMatchObject({
  592. providerFamily: "bigmodel",
  593. planTargetType: "PERSONAL",
  594. wireTargetType: "PERSONAL",
  595. });
  596. expect(fields["maasJwtExpiresInSeconds"]).toBeGreaterThan(123_000);
  597. expect(fields["maasJwtExpiresInSeconds"]).toBeLessThan(123_900);
  598. // resolver 无时间缓存,同一桶内重复解析(两次构造 token 相差 0~1s,同落 t34)
  599. // 不得重复记录——否则日志量与官方 MCP 请求数同数量级。
  600. const second = await resolveOfficialMcpCredentials(
  601. createDeps({ maasJwt: makeMaasJwtWithExpiry(123456) }),
  602. );
  603. expect(second.ok).toBe(true);
  604. expect(resolvedCalls()).toHaveLength(1);
  605. });
  606. it("OMCP-LOG-03: identity-only degradation stays out of info logs", async () => {
  607. // 已登录但 Registry 无 coding plan provider → identity-only 降级仍走 debug,
  608. // 不产生 info 噪音(本次升级范围仅限带 MaaS JWT 的成功解析)。
  609. const deps = createDeps({ registry: createRegistry([]) });
  610. const outcome = await resolveOfficialMcpCredentials(deps);
  611. expect(outcome).toMatchObject({ ok: true });
  612. expect(
  613. serviceInfo.mock.calls.filter((call) => String(call[0]).includes("identity-only")),
  614. ).toHaveLength(0);
  615. });
  616. });
  617. /** 造一个能被 readJwtExpiresInSeconds 解析出 exp 的三段式 MaaS JWT(base64url payload)。 */
  618. function makeMaasJwtWithExpiry(expiresInSeconds: number): string {
  619. const payload = Buffer.from(
  620. JSON.stringify({ exp: Math.round(Date.now() / 1000) + expiresInSeconds }),
  621. ).toString("base64url");
  622. return `header.${payload}.signature`;
  623. }