oauthUnauthorizedRequest.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. isCurrentOAuthCredentialRequest,
  4. isOAuthBusinessRequest,
  5. resolveOAuthBusinessCredentialValidationRequest,
  6. } from "#src/oauth/oauthUnauthorizedRequest.js";
  7. import { createNodeApiClient } from "#src/providers/api/nodeApiClient.js";
  8. import {
  9. createBigModelLoginAuthHeaders,
  10. createZaiLoginAuthHeaders,
  11. } from "#src/coding-plan-subscription/bigmodelCodingPlanSubscriptionProvider.js";
  12. function createFixture(provider = "zai", env: NodeJS.ProcessEnv = { ZCODE_ENV: "production" }) {
  13. const credentials = new Map([
  14. ["oauth:active_provider", provider],
  15. ["oauth:zai:access_token", "zai-business-token"],
  16. ["oauth:bigmodel:access_token", "bigmodel-business-token"],
  17. ["zcodejwttoken", "current-zcode-jwt"],
  18. ]);
  19. const credentialService = { load: vi.fn(async (key: string) => credentials.get(key) ?? null) };
  20. const observe = (url: string | URL, headers: Headers) =>
  21. isCurrentOAuthCredentialRequest({ input: url, headers, credentialService, env });
  22. const observeBusiness = (url: string | URL, _headers: Headers) =>
  23. isOAuthBusinessRequest({ input: url, credentialService, env });
  24. const notified = vi.fn();
  25. const fetchImpl = vi.fn(async () => new Response("", { status: 401 }));
  26. const client = createNodeApiClient({
  27. fetchImpl,
  28. isZcodeJwtRequest: observe,
  29. isBusinessUnauthorizedRequest: observeBusiness,
  30. resolveBusinessCredentialValidationRequest: (input, headers) =>
  31. resolveOAuthBusinessCredentialValidationRequest({ input, headers, credentialService, env }),
  32. onZcodeJwtInvalid: notified,
  33. });
  34. return { credentials, credentialService, observe, notified, fetchImpl, client };
  35. }
  36. describe("当前 App 登录凭据的 HTTP 401 识别", () => {
  37. it.each(["bigmodel", "zai"])("%s 身份核验与既有裸 token helper 保持一致", async (provider) => {
  38. const f = createFixture(provider);
  39. const token = `${provider}-business-token`;
  40. const origin = provider === "bigmodel" ? "https://bigmodel.cn" : "https://api.z.ai";
  41. const expected =
  42. provider === "bigmodel"
  43. ? createBigModelLoginAuthHeaders(token)
  44. : createZaiLoginAuthHeaders(token);
  45. for (const prefix of ["", "Bearer "]) {
  46. const check = await resolveOAuthBusinessCredentialValidationRequest({
  47. input: origin + "/api/biz/subscription/enterprise/v2/pricing",
  48. headers: new Headers({ Authorization: prefix + token }),
  49. credentialService: f.credentialService,
  50. });
  51. expect(check?.authorization).toBe(expected.Authorization);
  52. }
  53. });
  54. it.each(["bigmodel", "zai"])(
  55. "%s PAT/支付使用当前业务 token 的明确401均识别",
  56. async (provider) => {
  57. const f = createFixture(provider),
  58. origin = provider === "bigmodel" ? "https://bigmodel.cn" : "https://api.z.ai";
  59. for (const path of [
  60. "/api/biz/v1/organization/org/projects/project/api_keys/key/access_tokens",
  61. "/api/biz/pay/preview",
  62. "/api/pay/stripe/pay",
  63. ]) {
  64. await f.client.request(origin + path, {
  65. headers: { Authorization: `Bearer ${provider}-business-token` },
  66. });
  67. }
  68. expect(f.notified).toHaveBeenCalledTimes(3);
  69. },
  70. );
  71. it("BigModel 身份空200确认失效,ZAI 空200不作同样推断", async () => {
  72. for (const provider of ["bigmodel", "zai"]) {
  73. const f = createFixture(provider),
  74. origin = provider === "bigmodel" ? "https://bigmodel.cn" : "https://api.z.ai";
  75. f.fetchImpl.mockResolvedValueOnce(new Response(""));
  76. await f.client.request(origin + "/api/biz/customer/getCustomerInfo", {
  77. headers: { Authorization: provider + "-business-token" },
  78. });
  79. expect(f.notified.mock.calls.length).toBe(provider === "bigmodel" ? 1 : 0);
  80. expect(f.fetchImpl).toHaveBeenCalledOnce();
  81. }
  82. });
  83. it("核验材料构造期间切换平台,不把旧 token 发往新平台", async () => {
  84. const f = createFixture("bigmodel");
  85. let reads = 0;
  86. f.credentialService.load.mockImplementation(async (key) => {
  87. const value = f.credentials.get(key) ?? null;
  88. if (key === "oauth:active_provider" && ++reads === 3) f.credentials.set(key, "zai");
  89. return value;
  90. });
  91. const request = await resolveOAuthBusinessCredentialValidationRequest({
  92. input: "https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing",
  93. headers: new Headers({ Authorization: "bigmodel-business-token" }),
  94. credentialService: f.credentialService,
  95. });
  96. expect(request).toBeNull();
  97. });
  98. it.each([
  99. ["bigmodel", "https://bigmodel.cn/api/biz/customer/getCustomerInfo"],
  100. ["zai", "https://api.z.ai/api/biz/customer/getCustomerInfo"],
  101. ["zai", "https://chat.z.ai/api/oauth/userinfo"],
  102. ["bigmodel", "https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing"],
  103. ["zai", "https://api.z.ai/api/biz/subscription/enterprise/v2/pricing"],
  104. ["bigmodel", "https://bigmodel.cn/api/biz/team/subscribe/product/querySubscribeDetail"],
  105. ["zai", "https://api.z.ai/api/biz/team/subscribe/product/querySubscribeDetail"],
  106. ])("%s 用户/团队查询兼容裸 token 与 Bearer", async (provider, url) => {
  107. const fixture = createFixture(provider);
  108. for (const prefix of ["", "Bearer "]) {
  109. const response = await fixture.client.request(new URL(`${url}?source=e2e`), {
  110. headers: { Authorization: `${prefix}${provider}-business-token` },
  111. });
  112. expect(response.status).toBe(401);
  113. }
  114. expect(fixture.notified).toHaveBeenCalledTimes(2);
  115. });
  116. it.each([
  117. "https://api.z.ai/api/anthropic/v1/messages",
  118. "https://untrusted.example/api/biz/customer/getCustomerInfo",
  119. "https://api.z.ai.evil.example/api/biz/customer/getCustomerInfo",
  120. ])("不扩散至模型接口、错误域名/环境或非业务路径:%s", async (url) => {
  121. const fixture = createFixture();
  122. await fixture.client.request(url, { headers: { Authorization: "Bearer zai-business-token" } });
  123. expect(fixture.notified).not.toHaveBeenCalled();
  124. });
  125. it.each(["", "old-zai-token", "model-api-key", "Bearer model-api-key"])(
  126. "目标接口的匿名/旧凭据/API key 不退出:%s",
  127. async (authorization) => {
  128. const fixture = createFixture();
  129. await fixture.client.request("https://api.z.ai/api/biz/customer/getCustomerInfo", {
  130. headers: { Authorization: authorization },
  131. });
  132. expect(fixture.notified).not.toHaveBeenCalled();
  133. },
  134. );
  135. it("非 active 平台的残留 access token 不退出当前登录", async () => {
  136. const fixture = createFixture("bigmodel");
  137. await fixture.client.request("https://api.z.ai/api/biz/customer/getCustomerInfo", {
  138. headers: { Authorization: "zai-business-token" },
  139. });
  140. expect(fixture.notified).not.toHaveBeenCalled();
  141. });
  142. it.each(["token", "provider"])("401 返回前已更新 %s 时忽略旧请求", async (change) => {
  143. const fixture = createFixture();
  144. let complete!: (response: Response) => void;
  145. fixture.fetchImpl.mockImplementationOnce(
  146. () =>
  147. new Promise((resolve) => {
  148. complete = resolve;
  149. }),
  150. );
  151. const request = fixture.client.request("https://api.z.ai/api/biz/customer/getCustomerInfo", {
  152. headers: { Authorization: "zai-business-token" },
  153. });
  154. if (change === "token") fixture.credentials.set("oauth:zai:access_token", "new-token");
  155. else fixture.credentials.set("oauth:active_provider", "bigmodel");
  156. complete(new Response("", { status: 401 }));
  157. await request;
  158. expect(fixture.notified).not.toHaveBeenCalled();
  159. });
  160. it("读取 access token 期间切换平台,不使用跨平台读取快照", async () => {
  161. const fixture = createFixture();
  162. fixture.credentialService.load.mockImplementation(async (key) => {
  163. const value = fixture.credentials.get(key) ?? null;
  164. if (key === "oauth:zai:access_token")
  165. fixture.credentials.set("oauth:active_provider", "bigmodel");
  166. return value;
  167. });
  168. await fixture.client.request("https://api.z.ai/api/biz/customer/getCustomerInfo", {
  169. headers: { Authorization: "zai-business-token" },
  170. });
  171. expect(fixture.notified).not.toHaveBeenCalled();
  172. });
  173. it("HTTP 500 不因业务正文提示过期而登出", async () => {
  174. const fixture = createFixture();
  175. fixture.fetchImpl.mockResolvedValueOnce(
  176. new Response('{"code":401,"msg":"token expired"}', { status: 500 }),
  177. );
  178. await fixture.client.request("https://api.z.ai/api/biz/customer/getCustomerInfo", {
  179. headers: { Authorization: "zai-business-token" },
  180. });
  181. expect(fixture.notified).not.toHaveBeenCalled();
  182. });
  183. it.each([
  184. ["bigmodel", 200],
  185. ["bigmodel", 403],
  186. ["zai", 200],
  187. ["zai", 403],
  188. ] as const)("%s HTTP %i 的三个接口业务 401 均通知失效", async (provider, status) => {
  189. const fixture = createFixture(provider);
  190. const origin = provider === "bigmodel" ? "https://bigmodel.cn" : "https://api.z.ai";
  191. for (const path of [
  192. "/api/biz/customer/getCustomerInfo",
  193. "/api/biz/subscription/enterprise/v2/pricing",
  194. "/api/biz/team/subscribe/product/querySubscribeDetail",
  195. ]) {
  196. fixture.fetchImpl.mockResolvedValueOnce(
  197. Response.json({ code: 401, msg: "登录状态已过期", success: false }, { status }),
  198. );
  199. const response = await fixture.client.request(`${origin}${path}`, {
  200. headers: { Authorization: `${provider}-business-token` },
  201. });
  202. expect(await response.json()).toMatchObject({ code: 401 });
  203. }
  204. expect(fixture.notified).toHaveBeenCalledTimes(3);
  205. });
  206. it.each([
  207. ["https://api.z.ai/api/biz/customer/getCustomerInfo", "old-token"],
  208. ["https://api.z.ai/api/biz/subscription/enterprise/v2/pricing", "model-api-key"],
  209. [
  210. "https://untrusted.example/api/biz/team/subscribe/product/querySubscribeDetail",
  211. "zai-business-token",
  212. ],
  213. ["https://bigmodel.cn/api/biz/customer/getCustomerInfo", "bigmodel-business-token"],
  214. ])("业务 401 不扩散到旧凭据、非 active 平台或白名单外:%s", async (url, authorization) => {
  215. const fixture = createFixture();
  216. fixture.fetchImpl.mockResolvedValueOnce(Response.json({ code: 401, success: false }));
  217. await fixture.client.request(url, { headers: { Authorization: authorization } });
  218. expect(fixture.notified).not.toHaveBeenCalled();
  219. });
  220. it("保留原 ZCode JWT 401 判断", async () => {
  221. const fixture = createFixture();
  222. await fixture.client.request("https://zcode.z.ai/api/v1/zcode-plan/billing/balance", {
  223. headers: { Authorization: "Bearer current-zcode-jwt" },
  224. });
  225. expect(fixture.notified).toHaveBeenCalledOnce();
  226. });
  227. it("按当前环境和显式 userinfo 配置匹配,不硬编码生产域名", async () => {
  228. const fixture = createFixture("bigmodel", {
  229. ZCODE_ENV: "test",
  230. BIGMODEL_OAUTH_USERINFO_URL: "http://127.0.0.1:18080/custom/userinfo",
  231. });
  232. for (const url of [
  233. "https://bigmodel.cn/api/biz/customer/getCustomerInfo",
  234. "http://127.0.0.1:18080/custom/userinfo",
  235. ]) {
  236. await fixture.client.request(url, { headers: { Authorization: "bigmodel-business-token" } });
  237. }
  238. expect(fixture.notified).toHaveBeenCalledTimes(2);
  239. });
  240. describe.each([
  241. [
  242. "bigmodel",
  243. "BIGMODEL_API_BASE_URL",
  244. "BIGMODEL_OAUTH_USERINFO_URL",
  245. "https://bigmodel.cn/api/biz/customer/getCustomerInfo",
  246. ],
  247. [
  248. "zai",
  249. "ZAI_BUSINESS_BASE_URL",
  250. "ZAI_OAUTH_USERINFO_URL",
  251. "https://api.z.ai/api/biz/customer/getCustomerInfo",
  252. ],
  253. ])("%s URL 配置边界", (provider, baseKey, userinfoKey, customerInfoUrl) => {
  254. it.each(["production", "test"])("%s 环境仅识别当前配置的身份接口", async (environment) => {
  255. // 原用例依赖真实测试域名与生产域名不同,导出地址改写后会把否定用例变成肯定用例。
  256. // 用独立示例域名注入两套环境,开闭源保留相同的 origin 隔离断言。
  257. const currentOrigin = `https://${environment}.example`;
  258. const otherOrigin = `https://${environment === "test" ? "production" : "test"}.example`;
  259. const fixture = createFixture(provider, {
  260. ZCODE_ENV: environment,
  261. [baseKey]: currentOrigin,
  262. [userinfoKey]: `${currentOrigin}/userinfo`,
  263. });
  264. const headers = { Authorization: `Bearer ${provider}-business-token` };
  265. for (const path of ["/api/biz/customer/getCustomerInfo", "/userinfo"]) {
  266. const response = await fixture.client.request(`${otherOrigin}${path}`, { headers });
  267. expect(response.status).toBe(401);
  268. }
  269. expect(fixture.notified).not.toHaveBeenCalled();
  270. for (const path of ["/api/biz/customer/getCustomerInfo", "/userinfo"]) {
  271. const response = await fixture.client.request(`${currentOrigin}${path}`, { headers });
  272. expect(response.status).toBe(401);
  273. }
  274. expect(fixture.notified).toHaveBeenCalledTimes(2);
  275. });
  276. it.each(["not a URL", "/relative/userinfo", "file:///userinfo"])(
  277. "无效 userinfo %s 不影响有效 customerInfo 的 401",
  278. async (userinfo) => {
  279. const fixture = createFixture(provider, {
  280. ZCODE_ENV: "production",
  281. [userinfoKey]: userinfo,
  282. });
  283. await expect(
  284. fixture.observe(
  285. customerInfoUrl,
  286. new Headers({ Authorization: `${provider}-business-token` }),
  287. ),
  288. ).resolves.toBe(true);
  289. const response = await fixture.client.request(customerInfoUrl, {
  290. headers: { Authorization: `${provider}-business-token` },
  291. });
  292. expect(response.status).toBe(401);
  293. expect(fixture.notified).toHaveBeenCalledOnce();
  294. },
  295. );
  296. it.each(["not a URL", "/relative/base", "file:///base"])(
  297. "无效业务 base %s 不影响显式 userinfo 的 401",
  298. async (base) => {
  299. const userinfo = "https://userinfo.example/current";
  300. const fixture = createFixture(provider, {
  301. ZCODE_ENV: "production",
  302. [baseKey]: base,
  303. [userinfoKey]: userinfo,
  304. });
  305. await expect(
  306. fixture.observe(
  307. userinfo,
  308. new Headers({ Authorization: `Bearer ${provider}-business-token` }),
  309. ),
  310. ).resolves.toBe(true);
  311. const response = await fixture.client.request(userinfo, {
  312. headers: { Authorization: `Bearer ${provider}-business-token` },
  313. });
  314. expect(response.status).toBe(401);
  315. expect(fixture.notified).toHaveBeenCalledOnce();
  316. },
  317. );
  318. it.each(["", " "])("空白 override %j 保留默认地址", async (blank) => {
  319. const fixture = createFixture(provider, {
  320. ZCODE_ENV: "production",
  321. [baseKey]: blank,
  322. [userinfoKey]: blank,
  323. });
  324. const url = provider === "zai" ? "https://chat.z.ai/api/oauth/userinfo" : customerInfoUrl;
  325. await expect(
  326. fixture.observe(url, new Headers({ Authorization: `${provider}-business-token` })),
  327. ).resolves.toBe(true);
  328. });
  329. it("全部候选非法时返回 false,不吞掉 HTTP 响应", async () => {
  330. const fixture = createFixture(provider, {
  331. ZCODE_ENV: "production",
  332. [baseKey]: "invalid",
  333. [userinfoKey]: "/userinfo",
  334. });
  335. await expect(
  336. fixture.observe(
  337. customerInfoUrl,
  338. new Headers({ Authorization: `${provider}-business-token` }),
  339. ),
  340. ).resolves.toBe(false);
  341. const response = await fixture.client.request(customerInfoUrl, {
  342. headers: { Authorization: `${provider}-business-token` },
  343. });
  344. expect(response.status).toBe(401);
  345. expect(fixture.notified).not.toHaveBeenCalled();
  346. });
  347. });
  348. it("ZAI 业务 base 异常时仍匹配默认 OAuth userinfo", async () => {
  349. const fixture = createFixture("zai", {
  350. ZCODE_ENV: "production",
  351. ZAI_BUSINESS_BASE_URL: "invalid",
  352. });
  353. await expect(
  354. fixture.observe(
  355. "https://chat.z.ai/api/oauth/userinfo",
  356. new Headers({ Authorization: "zai-business-token" }),
  357. ),
  358. ).resolves.toBe(true);
  359. });
  360. it.each(["", "/relative/userinfo", "not a URL", "file:///userinfo"])(
  361. "非法 access token 请求地址 %j 不抛错",
  362. async (url) => {
  363. const fixture = createFixture();
  364. await expect(
  365. fixture.observe(url, new Headers({ Authorization: "zai-business-token" })),
  366. ).resolves.toBe(false);
  367. },
  368. );
  369. it("userinfo 分类不受无关的 ZCode base 配置异常影响", async () => {
  370. const fixture = createFixture("zai", { ZCODE_ENV: "production", ZCODE_BASE_URL: "invalid" });
  371. await expect(
  372. fixture.observe(
  373. "https://chat.z.ai/api/oauth/userinfo",
  374. new Headers({ Authorization: "zai-business-token" }),
  375. ),
  376. ).resolves.toBe(true);
  377. });
  378. it("URL 配置异常不影响原 JWT 分支", async () => {
  379. const fixture = createFixture("zai", {
  380. ZCODE_ENV: "production",
  381. ZAI_BUSINESS_BASE_URL: "invalid",
  382. ZAI_OAUTH_USERINFO_URL: "invalid",
  383. });
  384. await expect(
  385. fixture.observe(
  386. "https://zcode.z.ai/api/v1/zcode-plan/billing/balance",
  387. new Headers({ Authorization: "Bearer current-zcode-jwt" }),
  388. ),
  389. ).resolves.toBe(true);
  390. });
  391. });