oauthUnauthorizedRequest.test.ts 14 KB

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