access-token-401-fixture.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import { once } from "node:events";
  2. import { readFile, writeFile } from "node:fs/promises";
  3. import { createServer, type ServerResponse } from "node:http";
  4. export async function prepareAccessToken401Fixture(options: {
  5. specs: string[];
  6. credentialsFile: string;
  7. settingsFile: string;
  8. }): Promise<(() => Promise<void>) | null> {
  9. const sharedJwt = options.specs.some((spec) => spec.endsWith("jwt-401-auto-logout.test.ts"));
  10. const projectRecovery = options.specs.some((spec) =>
  11. spec.endsWith("project-location-decrypt-recovery.test.ts"),
  12. );
  13. if (
  14. !sharedJwt &&
  15. !projectRecovery &&
  16. !options.specs.some((spec) => spec.endsWith("access-token-401-auto-logout.test.ts"))
  17. )
  18. return null;
  19. const pending: ServerResponse[] = [];
  20. let businessRequestCount = 0;
  21. let rejected = false;
  22. let rejectionStatus = 401;
  23. let emptyRejection = false;
  24. const preserveSession = process.env.ZCODE_E2E_AUTH_VALIDATION_HEADER === "1";
  25. const ordinaryStatus = process.env.ZCODE_E2E_AUTH_EXPIRY_HTTP_STATUS === "200" ? 200 : 403;
  26. let ordinaryBusinessRequestCount = 0;
  27. let rawIdentityRequestCount = 0;
  28. let rejectedIdentityHeaderCount = 0;
  29. let locationRequests = 0;
  30. let tokenRequests = 0;
  31. let loginCompletions = 0;
  32. let locationUnavailable = false;
  33. const provider =
  34. sharedJwt || preserveSession || process.env.ZCODE_E2E_AUTH_EXPIRY_PROVIDER === "zai"
  35. ? "zai"
  36. : "bigmodel";
  37. const rejectResponse = (response: ServerResponse) => {
  38. response.writeHead(rejectionStatus);
  39. response.end(emptyRejection ? "" : '{"code":401,"msg":"登录状态已过期","success":false}');
  40. };
  41. const server = createServer((request, response) => {
  42. const url = new URL(request.url ?? "/", "http://fixture");
  43. const path = url.pathname;
  44. response.setHeader("content-type", "application/json");
  45. if (path === "/__e2e/reject") {
  46. rejectionStatus = url.searchParams.get("status") === "200" ? 200 : 401;
  47. emptyRejection = url.searchParams.get("empty") === "1";
  48. rejected = true;
  49. for (const waiting of pending.splice(0)) {
  50. rejectResponse(waiting);
  51. }
  52. response.end("{}");
  53. return;
  54. }
  55. if (path === "/__e2e/status") {
  56. response.end(
  57. JSON.stringify({
  58. businessRequestCount,
  59. rejectionStatus,
  60. rejected,
  61. emptyRejection,
  62. ordinaryBusinessRequestCount,
  63. rawIdentityRequestCount,
  64. rejectedIdentityHeaderCount,
  65. locationRequests,
  66. tokenRequests,
  67. loginCompletions,
  68. }),
  69. );
  70. return;
  71. }
  72. if (projectRecovery) {
  73. if (path === "/__e2e/location-unavailable" || path === "/__e2e/location-available") {
  74. locationUnavailable = path.endsWith("location-unavailable");
  75. response.end("{}");
  76. return;
  77. }
  78. let data: unknown;
  79. if (path === "/api/v1/client/scenes" || path === "/api/v1/marketing/touch") data = [];
  80. else if (path === "/api/biz/subscription/enterprise/v2/pricing") data = { productList: [] };
  81. else if (path === "/api/v1/oauth/cli/init")
  82. data = {
  83. authorize_url: "https://example.com/authorize?state=project-recovery",
  84. expires_at: Math.floor(Date.now() / 1000) + 300,
  85. flow_id: "project-recovery",
  86. poll_interval_sec: 1,
  87. };
  88. else if (path === "/api/v1/oauth/cli/poll/project-recovery") {
  89. loginCompletions++;
  90. data = {
  91. status: "ready",
  92. token: "e2e-distinct-zcode-jwt",
  93. user: { user_id: "e2e-user", name: "Fixture User" },
  94. bigmodel: { access_token: "e2e-business-access-token" },
  95. };
  96. } else if (path === "/api/biz/customer/getCustomerInfo") {
  97. locationRequests++;
  98. if (locationUnavailable) {
  99. response.writeHead(503);
  100. response.end(JSON.stringify({ code: 503 }));
  101. return;
  102. }
  103. data = {
  104. customerNumber: "e2e-user",
  105. organizations: [
  106. {
  107. organizationId: "org-e2e",
  108. projects: [{ projectId: "project-e2e", projectType: "1" }],
  109. },
  110. ],
  111. };
  112. } else if (path.endsWith("/api_keys")) data = [{ apiKey: "key-e2e", name: "zcode-api-key" }];
  113. else if (path.endsWith("/access_tokens")) {
  114. tokenRequests++;
  115. data = {
  116. accessToken: "e2e-project-token",
  117. tokenType: "Bearer",
  118. expiresIn: 600,
  119. expiresAt: Date.now() / 1000 + 600,
  120. };
  121. } else if (path === "/api/biz/subscription/list")
  122. data = [
  123. {
  124. productId: "coding-pro-fixture",
  125. productName: "Coding Pro",
  126. status: "VALID",
  127. inCurrentPeriod: true,
  128. },
  129. ];
  130. else if (path === "/api/monitor/usage/quota/limit")
  131. data = {
  132. level: "pro",
  133. limits: [
  134. {
  135. type: "TIME_LIMIT",
  136. remaining: 5,
  137. percentage: 10,
  138. nextResetTime: Date.now() + 3600000,
  139. },
  140. ],
  141. };
  142. else if (path === "/api/v1/zcode-plan/billing/balance") data = { plans: [], balances: [] };
  143. if (data !== undefined) {
  144. response.end(JSON.stringify({ code: 0, data }));
  145. return;
  146. }
  147. }
  148. if (preserveSession && path === "/api/biz/customer/getCustomerInfo") {
  149. // PAT 资料读取和异常业务请求后的身份核验必须遵守同一个裸 token 契约。
  150. if (request.headers.authorization !== "e2e-business-access-token") {
  151. rejectedIdentityHeaderCount++;
  152. response.writeHead(401);
  153. response.end('{"code":401}');
  154. } else {
  155. if (ordinaryBusinessRequestCount > 0) rawIdentityRequestCount++;
  156. response.end(
  157. '{"code":200,"success":true,"data":{"customerNumber":"e2e-user","organizations":[{"organizationId":"org-e2e","organizationName":"Fixture Organization","projects":[{"projectId":"project-e2e","projectName":"Fixture Project","projectType":"1"}]}]}}',
  158. );
  159. }
  160. return;
  161. }
  162. if (preserveSession && path === "/api/oauth/userinfo") {
  163. response.end('{"code":200,"data":{"sub":"e2e-user","name":"Fixture User"}}');
  164. return;
  165. }
  166. if (
  167. preserveSession &&
  168. path.startsWith("/api/biz/") &&
  169. request.headers.authorization?.replace(/^Bearer\s+/i, "") === "e2e-business-access-token"
  170. ) {
  171. ordinaryBusinessRequestCount++;
  172. response.writeHead(ordinaryStatus);
  173. response.end("");
  174. return;
  175. }
  176. if (
  177. (sharedJwt && path === "/api/v1/zcode-plan/billing/balance") ||
  178. (!sharedJwt && path === "/api/biz/customer/getCustomerInfo")
  179. ) {
  180. // 只记录是否匹配合成登录凭据,避免 token 原文进入测试产物。
  181. if (
  182. request.headers.authorization?.replace(/^Bearer\s+/i, "") ===
  183. (sharedJwt ? "e2e-distinct-zcode-jwt" : "e2e-business-access-token")
  184. )
  185. businessRequestCount++;
  186. if (rejected) {
  187. rejectResponse(response);
  188. } else pending.push(response);
  189. return;
  190. }
  191. if (sharedJwt && path === "/api/biz/customer/getCustomerInfo") {
  192. response.end(
  193. JSON.stringify({
  194. code: 200,
  195. success: true,
  196. data: { user_id: "e2e-user", customerNumber: "e2e-user", name: "Fixture User" },
  197. }),
  198. );
  199. return;
  200. }
  201. // 其它控制面始终 200,保证失效提示只能来自上面的目标凭据请求。
  202. response.end(
  203. JSON.stringify({
  204. code: 0,
  205. data: { configs: {}, builtinModels: [], config_version: "oauth-401-fixture" },
  206. }),
  207. );
  208. });
  209. server.listen(0, "127.0.0.1");
  210. await once(server, "listening");
  211. const address = server.address();
  212. if (!address || typeof address === "string") throw new Error("OAuth fixture 缺少监听端口");
  213. const baseUrl = `http://127.0.0.1:${address.port}`;
  214. // 用独立 origin 模拟业务域与 ZCode API,避免来源头和端点改写影响业务核验回归。
  215. const controlServer = preserveSession
  216. ? createServer((_request, response) => {
  217. response.setHeader("content-type", "application/json");
  218. response.end(
  219. JSON.stringify({
  220. code: 0,
  221. data: { configs: {}, builtinModels: [], config_version: "oauth-401-fixture" },
  222. }),
  223. );
  224. })
  225. : null;
  226. let controlBaseUrl = baseUrl;
  227. if (controlServer) {
  228. controlServer.listen(0, "127.0.0.1");
  229. await once(controlServer, "listening");
  230. const controlAddress = controlServer.address();
  231. if (!controlAddress || typeof controlAddress === "string")
  232. throw new Error("OAuth control fixture 缺少监听端口");
  233. controlBaseUrl = `http://127.0.0.1:${controlAddress.port}`;
  234. }
  235. const envPatch = {
  236. ZCODE_E2E_ACCESS_TOKEN_401_URL: baseUrl,
  237. BIGMODEL_API_BASE_URL: baseUrl,
  238. BIGMODEL_OAUTH_USERINFO_URL: `${baseUrl}/api/biz/customer/getCustomerInfo`,
  239. ZAI_BUSINESS_BASE_URL: baseUrl,
  240. ZAI_OAUTH_USERINFO_URL: `${baseUrl}${preserveSession ? "/api/oauth/userinfo" : "/api/biz/customer/getCustomerInfo"}`,
  241. ZCODE_BASE_URL: controlBaseUrl,
  242. ZCODE_TEST_BASE_URL: controlBaseUrl,
  243. ZCODE_ENDPOINT_ORIGIN: controlBaseUrl,
  244. };
  245. const previous = Object.fromEntries(Object.keys(envPatch).map((key) => [key, process.env[key]]));
  246. Object.assign(process.env, envPatch);
  247. await writeFile(
  248. options.credentialsFile,
  249. JSON.stringify({
  250. "oauth:active_provider": provider,
  251. [`oauth:${provider}:access_token`]: "e2e-business-access-token",
  252. [`oauth:${provider}:refresh_token`]: "e2e-refresh-token",
  253. [`oauth:${provider}:user_info`]: JSON.stringify(
  254. provider === "zai"
  255. ? { user_id: "e2e-user", name: "Fixture User" }
  256. : {
  257. id: "e2e-user",
  258. username: "Fixture User",
  259. displayName: "Fixture User",
  260. ...(projectRecovery ? { rawProfile: { zcodeProfileSchemaVersion: 2 } } : {}),
  261. },
  262. ),
  263. zcodejwttoken: "e2e-distinct-zcode-jwt",
  264. "bot:e2e:credential": "e2e-independent-bot-token",
  265. ...(projectRecovery
  266. ? {
  267. [`project-key-location:v1:${encodeURIComponent(JSON.stringify([baseUrl, "bigmodel", "e2e-user", null, 1, "non-team"]))}`]:
  268. "enc:v1:broken-project-location",
  269. }
  270. : {}),
  271. }),
  272. { mode: 0o600 },
  273. );
  274. const settings = JSON.parse(await readFile(options.settingsFile, "utf8"));
  275. await writeFile(
  276. options.settingsFile,
  277. JSON.stringify({
  278. ...settings,
  279. providerFamilyDomain: provider,
  280. providerFamilyConnectionSelections: { [provider]: { kind: "individual-coding-plan" } },
  281. }),
  282. );
  283. return async () => {
  284. if (preserveSession)
  285. console.info("[oauth-auth-fixture]", {
  286. ordinaryBusinessRequestCount,
  287. rawIdentityRequestCount,
  288. rejectedIdentityHeaderCount,
  289. });
  290. for (const response of pending.splice(0)) response.destroy();
  291. for (const fixtureServer of [server, controlServer]) {
  292. if (!fixtureServer) continue;
  293. const closed = new Promise<void>((resolve, reject) =>
  294. fixtureServer.close((error) => (error ? reject(error) : resolve())),
  295. );
  296. fixtureServer.closeAllConnections();
  297. await closed;
  298. }
  299. for (const [key, value] of Object.entries(previous)) {
  300. if (value === undefined) delete process.env[key];
  301. else process.env[key] = value;
  302. }
  303. };
  304. }