off-peak-request-auth-refresh.test.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { runWithModelInvocationContext } from "@zcode/contracts";
  2. import { TestAiSdkModelAdapter, TestProviderConfigFixture } from "./test-provider-config.js";
  3. import { describe, expect, it, vi } from "vitest";
  4. import { refreshOffPeakRequestAuth } from "../src/model/off-peak-request-auth.js";
  5. const scope = "a".repeat(64);
  6. const auth = {
  7. apiKey: "zcode-jwt",
  8. accountScope: scope,
  9. apiKeyId: "old-key-id",
  10. headers: {
  11. Authorization: "Bearer zcode-jwt",
  12. "X-Coding-Plan-Api-Key": "old-pat",
  13. "X-Off-Peak-Ticket-ID": "ticket",
  14. "bigmodel-project": "project",
  15. },
  16. };
  17. const input = { providerId: "account:bigmodel-off-peak", modelId: "glm", attempt: 1 };
  18. const accountAccess = { type: "zhipu-account", accountType: "bigmodel", mode: "off-peak" } as const;
  19. describe("闲时每次模型请求刷新 PAT", () => {
  20. it("每次都向 owner 解析,更新 PAT 且保持票据和本轮身份头", async () => {
  21. let generation = 0;
  22. const refresh = vi.fn(async () => ({
  23. headersApplied: true,
  24. requestAuth: {
  25. apiKey: `pat-${++generation}`,
  26. apiKeyId: `key-id-${generation}`,
  27. accountScope: scope,
  28. },
  29. }));
  30. for (const attempt of [1, 2]) {
  31. const result = await refreshOffPeakRequestAuth({
  32. auth,
  33. input: { ...input, attempt },
  34. accountAccess,
  35. refresh,
  36. });
  37. expect(result).toEqual({
  38. ...auth,
  39. apiKeyId: `key-id-${attempt}`,
  40. headers: { ...auth.headers, "X-Coding-Plan-Api-Key": `pat-${attempt}` },
  41. });
  42. }
  43. expect(refresh).toHaveBeenCalledTimes(2);
  44. expect(refresh.mock.calls[0]?.[0]).toMatchObject({
  45. expectedAccountScope: scope,
  46. accountAccess,
  47. });
  48. });
  49. it("owner 缺失或拒绝刷新不得沿用静态 PAT", async () => {
  50. await expect(refreshOffPeakRequestAuth({ auth, input, accountAccess })).rejects.toThrow();
  51. await expect(
  52. refreshOffPeakRequestAuth({
  53. auth,
  54. input,
  55. accountAccess,
  56. refresh: async () => {
  57. throw new Error("scope changed");
  58. },
  59. }),
  60. ).rejects.toThrow("scope changed");
  61. await expect(
  62. refreshOffPeakRequestAuth({
  63. auth,
  64. input,
  65. accountAccess,
  66. refresh: async () => ({
  67. headersApplied: true,
  68. requestAuth: { apiKey: "other-pat", accountScope: "b".repeat(64) },
  69. }),
  70. }),
  71. ).rejects.toThrow();
  72. });
  73. it("保留无真实 Token 的 mock 静态注入", async () => {
  74. const refresh = vi.fn();
  75. const mock = { apiKey: "mock", headers: { "X-Coding-Plan-Api-Key": "mock" } };
  76. expect(await refreshOffPeakRequestAuth({ auth: mock, input, accountAccess, refresh })).toBe(
  77. mock,
  78. );
  79. expect(refresh).not.toHaveBeenCalled();
  80. });
  81. });
  82. it("真实 runner 同一个闲时 Model 连续请求也向 owner 刷新,不只首次派发刷新", async () => {
  83. // 将测试依赖在文件加载阶段准备好,断言只测每次请求刷新,不包含冷加载耗时。
  84. const seen: string[] = [];
  85. const adapter = new TestAiSdkModelAdapter({
  86. registry: new TestProviderConfigFixture({
  87. providers: {
  88. idle: {
  89. kind: "anthropic",
  90. accountMode: "off-peak",
  91. baseURL: "https://zcode.z.ai/api/v1/off-peak/anthropic",
  92. },
  93. },
  94. }),
  95. runtime: {
  96. async generateText(options) {
  97. seen.push(new Headers(options.headers).get("X-Coding-Plan-Api-Key")!);
  98. expect(new Headers(options.headers).get("X-Off-Peak-Ticket-ID")).toBe("ticket");
  99. return {
  100. text: "ok",
  101. finishReason: "stop",
  102. usage: { inputTokens: 1, outputTokens: 1 },
  103. totalUsage: { inputTokens: 1, outputTokens: 1 },
  104. } as never;
  105. },
  106. streamText() {
  107. throw Error("unused");
  108. },
  109. },
  110. });
  111. const model = adapter.createModel({
  112. providerId: "idle",
  113. modelId: "glm",
  114. accountMode: "off-peak",
  115. requestDependencies: { requestAuth: { source: { resolve: async () => auth } } },
  116. });
  117. let count = 0;
  118. const refresh = vi.fn(async (request) => {
  119. expect(request.expectedAccountScope).toBe(scope);
  120. expect(request.accountAccess.mode).toBe("off-peak");
  121. return {
  122. headersApplied: true,
  123. requestAuth: { apiKey: `fresh-${++count}`, accountScope: scope },
  124. };
  125. });
  126. for (const _ of [1, 2]) {
  127. await runWithModelInvocationContext({ refreshRuntimeHeadersBeforeAttempt: refresh }, () =>
  128. model.generateText({ messages: [{ role: "user", content: "continue" }] }),
  129. );
  130. }
  131. expect(seen).toEqual(["fresh-1", "fresh-2"]);
  132. });