access-token-401-fixture.ts 12 KB

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