provider-endpoint-routing-fetch.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ProviderEndpointRoutingPort } from "@zcode/contracts";
  3. import { createProviderEndpointRoutingFetch } from "../src/model/provider-endpoint-routing-fetch.js";
  4. import { createProviderBusinessErrorFetch } from "../src/model/model-execution.js";
  5. const SOURCE_ZAI = "https://api.z.ai/api/anthropic/v1/messages";
  6. const TARGET = "https://zcode.z.ai/api/v1/proxy/anthropic/v1/messages";
  7. describe("provider endpoint routing fetch", () => {
  8. it("preserves request semantics and the streaming response while recalculating Host", async () => {
  9. const controller = new AbortController();
  10. const routingPort = {
  11. resolve: vi.fn<ProviderEndpointRoutingPort["resolve"]>(async () => ({
  12. routed: true,
  13. url: `${TARGET}?original=query`,
  14. })),
  15. };
  16. let captured: Request | undefined;
  17. const sseResponse = new Response("data: first\n\ndata: second\n\n", {
  18. headers: { "content-type": "text/event-stream" },
  19. });
  20. const fetch = createProviderEndpointRoutingFetch({
  21. fetch: vi.fn<typeof globalThis.fetch>(async (input, init) => {
  22. captured = new Request(input, init);
  23. return sseResponse;
  24. }),
  25. routingPort,
  26. apiKeyId: "real-key-id",
  27. });
  28. const input = new Request(`${SOURCE_ZAI}?original=query`, {
  29. body: JSON.stringify({ stream: true }),
  30. headers: {
  31. Authorization: "Bearer secret",
  32. Host: "api.z.ai",
  33. "x-api-key": "provider-key",
  34. "X-ZCode-Trace-Id": "trace-1",
  35. },
  36. method: "POST",
  37. signal: controller.signal,
  38. });
  39. const response = await fetch(input);
  40. expect(response).toBe(sseResponse);
  41. expect(routingPort.resolve).toHaveBeenCalledWith(`${SOURCE_ZAI}?original=query`, {
  42. apiKeyId: "real-key-id",
  43. signal: input.signal,
  44. trace: { traceId: "trace-1" },
  45. });
  46. expect(captured?.url).toBe(`${TARGET}?original=query`);
  47. expect(captured?.method).toBe("POST");
  48. expect(captured?.headers.get("authorization")).toBe("Bearer secret");
  49. expect(captured?.headers.get("x-api-key")).toBe("provider-key");
  50. expect(captured?.headers.has("host")).toBe(false);
  51. await expect(captured?.text()).resolves.toBe(JSON.stringify({ stream: true }));
  52. controller.abort();
  53. expect(captured?.signal.aborted).toBe(true);
  54. await expect(response.text()).resolves.toBe("data: first\n\ndata: second\n\n");
  55. });
  56. it("does not derive x-api-key from Authorization", async () => {
  57. const routingPort = {
  58. resolve: vi.fn<ProviderEndpointRoutingPort["resolve"]>(async (url) => ({
  59. routed: false,
  60. url,
  61. })),
  62. };
  63. const fetch = createProviderEndpointRoutingFetch({
  64. fetch: vi.fn<typeof globalThis.fetch>(async () => new Response(null, { status: 204 })),
  65. routingPort,
  66. });
  67. await fetch(SOURCE_ZAI, {
  68. headers: {
  69. Authorization: "Bearer provider-key",
  70. "X-ZCode-Trace-Id": "trace-authorization-only",
  71. },
  72. });
  73. expect(routingPort.resolve).toHaveBeenCalledWith(SOURCE_ZAI, {
  74. signal: undefined,
  75. trace: { traceId: "trace-authorization-only" },
  76. });
  77. });
  78. it("does not forward manual x-api-key from either Request or RequestInit", async () => {
  79. const routingPort = {
  80. resolve: vi.fn<ProviderEndpointRoutingPort["resolve"]>(async (url) => ({
  81. routed: false,
  82. url,
  83. })),
  84. };
  85. const fetch = createProviderEndpointRoutingFetch({
  86. fetch: vi.fn<typeof globalThis.fetch>(async () => new Response(null, { status: 204 })),
  87. routingPort,
  88. });
  89. const input = new Request(SOURCE_ZAI, {
  90. headers: { "x-api-key": "request-key" },
  91. });
  92. await fetch(input, {
  93. headers: { "X-API-Key": "init-key" },
  94. });
  95. expect(routingPort.resolve).toHaveBeenCalledWith(SOURCE_ZAI, {
  96. signal: input.signal,
  97. trace: undefined,
  98. });
  99. });
  100. it("rewrites before proxy and no-proxy selection", async () => {
  101. let capturedUrl: string | undefined;
  102. const fetch = createProviderBusinessErrorFetch({
  103. endpointRoutingPort: {
  104. async resolve() {
  105. return {
  106. routed: true,
  107. url: "https://direct.example.test/v1/messages",
  108. };
  109. },
  110. },
  111. fetch: async (input) => {
  112. capturedUrl = input instanceof Request ? input.url : String(input);
  113. return new Response(null, { status: 204 });
  114. },
  115. httpProxy: "http://127.0.0.1:1",
  116. noProxy: "direct.example.test",
  117. providerId: "zai",
  118. providerKind: "anthropic",
  119. });
  120. await expect(fetch(SOURCE_ZAI)).resolves.toMatchObject({ status: 204 });
  121. expect(capturedUrl).toBe("https://direct.example.test/v1/messages");
  122. });
  123. it.each([
  124. ["Request", () => new Request(SOURCE_ZAI)],
  125. ["URL", () => new URL(SOURCE_ZAI)],
  126. ["string", () => SOURCE_ZAI],
  127. ])("applies decision headers to a %s input without RequestInit headers", async (_name, input) => {
  128. let captured: Request | undefined;
  129. const fetch = createProviderEndpointRoutingFetch({
  130. fetch: vi.fn<typeof globalThis.fetch>(async (nextInput, nextInit) => {
  131. captured = new Request(nextInput, nextInit);
  132. return new Response(null, { status: 204 });
  133. }),
  134. routingPort: {
  135. async resolve() {
  136. return {
  137. headers: { "X-ZCode-Authorization": "Bearer current-jwt" },
  138. routed: true,
  139. url: TARGET,
  140. };
  141. },
  142. },
  143. });
  144. await fetch(input());
  145. expect(captured?.headers.get("x-zcode-authorization")).toBe("Bearer current-jwt");
  146. });
  147. });