Spaces:
Paused
Paused
File size: 9,591 Bytes
488aedf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | /**
* Tests for the `debug` flag on `ProxyHandlerOptions`. Verifies that when
* `debug: true` the handler emits per-request diagnostic lines, and that
* the flag defaults to off (no extra output).
*/
import { describe, it, expect } from "bun:test";
import { proxyRequest } from "./handler.js";
import type { ProxyConfig, ProxyIdentity } from "../config/types.js";
import { AuthManager } from "../auth/manager.js";
/** AuthManager with a preset oauth credential (replaces the removed apikey mode). */
function oauthAuth(key = "testkey.testsecret"): AuthManager {
const [apiKey, secret] = key.split(".");
const auth = new AuthManager();
auth.setOAuthCredential(secret ? { apiKey, secret, provider: "zai" } : { apiKey, provider: "zai" });
return auth;
}
const IDENTITY: ProxyIdentity = {
appVersion: "test-1.0.0",
sourceTitle: "cli",
refererOrigin: "https://zcode.z.ai",
};
const TEST_CONFIG: ProxyConfig = {
server: { port: 8080, host: "0.0.0.0" },
auth: {},
provider: "zai",
plan: "coding-plan",
providers: {
zai: { anthropicBase: "https://api.z.ai/api/anthropic", openaiBase: "https://api.z.ai/api/coding/paas/v4" },
bigmodel: { anthropicBase: "https://open.bigmodel.cn/api/anthropic", openaiBase: "https://open.bigmodel.cn/api/coding/paas/v4" },
},
defaultModel: "glm-4.6",
models: ["glm-4.6"],
identity: IDENTITY,
clientIdentity: { mode: "observe", ttlSeconds: 900, maxSessions: 1024 },
responses: { enabled: true, storeMaxEntries: 1000, storeTtlMs: 86400000 },
endpointRouting: { enabled: false, origin: "https://zcode.z.ai" },
clientSigning: { enabled: false }, highspeed: { enabled: false, origin: "https://zcode.z.ai", models: [] },
mcp: { enabled: true, webSearch: true, webReader: false, zread: false, gateway: { enabled: true, upstreamOrigin: "https://zcode.chatglm.site" } },
async: { enabled: false, origin: "https://zcode.z.ai", pollIntervalMs: 5000, keepAliveIntervalMs: 3000, maxWaitMs: 0, maxRetries: 3, settleTimeoutMs: 8000, controlTimeoutMs: 15000, defaultModel: "" },
claim: { enabled: false, auto: true, origin: "https://zcode.z.ai", pollIntervalMs: 300000, cooldownMs: 600000, planId: "" },
logging: { level: "info" },
};
function makeClientReq(body: string): Request {
return new Request("http://localhost:8080/v1/messages", {
method: "POST",
headers: { "content-type": "application/json" },
body,
});
}
function mockFetch(impl: (req: Request) => Promise<Response>): typeof fetch {
return Object.assign(impl, { preconnect: () => {} }) as typeof fetch;
}
async function captureConsoleLog(fn: () => Promise<void>): Promise<string[]> {
const lines: string[] = [];
const orig = console.log;
console.log = (...args: unknown[]) => { lines.push(args.join(" ")); };
try {
await fn();
} finally {
console.log = orig;
}
return lines;
}
function openaiOk(): Response {
return new Response(
JSON.stringify({
id: "chatcmpl_debug",
object: "chat.completion",
model: "glm-4.6",
choices: [
{
index: 0,
message: { role: "assistant", content: "Hi" },
finish_reason: "stop",
},
],
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
function anthropicOk(): Response {
return new Response(
JSON.stringify({
id: "msg_debug",
type: "message",
role: "assistant",
model: "glm-4.6",
content: [{ type: "text", text: "Hi" }],
stop_reason: "end_turn",
stop_sequence: null,
usage: { input_tokens: 10, output_tokens: 5 },
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
describe("proxyRequest debug mode", () => {
it("emits debug lines when debug=true (upstream URL, headers, response status)", async () => {
const auth = oauthAuth();
const clientReq = makeClientReq('{"model":"glm-4.6","messages":[{"role":"user","content":"Hi"}]}');
const lines = await captureConsoleLog(async () => {
const resp = await proxyRequest(clientReq, "anthropic", {
config: TEST_CONFIG,
auth,
debug: true,
fetchImpl: mockFetch(async () => anthropicOk()),
});
expect(resp.status).toBe(200);
});
const debugLines = lines.filter((l) => l.includes(" debug: "));
expect(debugLines.length).toBeGreaterThan(0);
expect(debugLines.some((l) => l.includes("→ POST https://api.z.ai/api/anthropic/v1/messages"))).toBe(true);
expect(debugLines.some((l) => l.includes("← 200"))).toBe(true);
});
it("redacts sensitive request headers (x-api-key) in debug output", async () => {
const auth = oauthAuth();
const clientReq = makeClientReq('{"model":"glm-4.6","messages":[]}');
const lines = await captureConsoleLog(async () => {
await proxyRequest(clientReq, "anthropic", {
config: TEST_CONFIG,
auth,
debug: true,
fetchImpl: mockFetch(async () => anthropicOk()),
});
});
const headerLine = lines.find((l) => l.includes("debug:") && l.includes("x-api-key="));
expect(headerLine).toBeDefined();
expect(headerLine!).not.toContain("testkey.testsecret");
});
it("does not emit debug lines when debug is omitted (default off)", async () => {
const auth = oauthAuth();
const clientReq = makeClientReq('{"model":"glm-4.6","messages":[]}');
const lines = await captureConsoleLog(async () => {
await proxyRequest(clientReq, "anthropic", {
config: TEST_CONFIG,
auth,
fetchImpl: mockFetch(async () => openaiOk()),
});
});
const debugLines = lines.filter((l) => l.includes(" debug: "));
expect(debugLines.length).toBe(0);
});
it("emits ERROR debug line on upstream failure", async () => {
const auth = oauthAuth();
const clientReq = makeClientReq('{"model":"glm-4.6","messages":[]}');
const lines = await captureConsoleLog(async () => {
const resp = await proxyRequest(clientReq, "anthropic", {
config: TEST_CONFIG,
auth,
debug: true,
fetchImpl: mockFetch(async () => { throw new Error("ECONNREFUSED"); }),
});
expect(resp.status).toBe(502);
});
expect(lines.some((l) => l.includes("debug: ERROR upstream_unreachable: ECONNREFUSED"))).toBe(true);
});
it("emits an OpenAI→Anthropic translation note for OpenAI clients on coding-plan", async () => {
const auth = oauthAuth();
const clientReq = new Request("http://localhost:8080/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "glm-4.6",
messages: [{ role: "user", content: "Hi" }],
}),
});
const lines = await captureConsoleLog(async () => {
await proxyRequest(clientReq, "openai", {
config: TEST_CONFIG,
auth,
debug: true,
fetchImpl: mockFetch(async () => anthropicOk()),
});
});
expect(lines.some((l) => l.includes("translated OpenAI→Anthropic"))).toBe(true);
expect(lines.some((l) => l.includes("→ POST https://api.z.ai/api/anthropic/v1/messages"))).toBe(true);
});
it("emits observe-only client identity inference without stabilizing x-session-id", async () => {
const auth = oauthAuth();
const body = '{"model":"glm-4.6","messages":[{"role":"user","content":"Hi"}]}';
const seenSessions: string[] = [];
const lines = await captureConsoleLog(async () => {
for (let i = 0; i < 2; i++) {
const resp = await proxyRequest(makeClientReq(body), "anthropic", {
config: TEST_CONFIG,
auth,
debug: true,
fetchImpl: mockFetch(async (req) => {
seenSessions.push(req.headers.get("x-session-id") ?? "");
return openaiOk();
}),
});
expect(resp.status).toBe(200);
}
});
expect(lines.some((l) => l.includes("clientIdentity source=lineage action=observe"))).toBe(true);
expect(seenSessions[0]).toBeTruthy();
expect(seenSessions[1]).toBeTruthy();
expect(seenSessions[0]).not.toBe(seenSessions[1]);
});
it("stabilizes x-session-id in enforce mode for the same inferred session", async () => {
const auth = oauthAuth();
const body = '{"model":"glm-4.6","messages":[{"role":"user","content":"Hi"}]}';
const seenSessions: string[] = [];
const config: ProxyConfig = { ...TEST_CONFIG, clientIdentity: { mode: "enforce", ttlSeconds: 900, maxSessions: 1024 } };
for (let i = 0; i < 2; i++) {
const resp = await proxyRequest(makeClientReq(body), "anthropic", {
config,
auth,
fetchImpl: mockFetch(async (req) => {
seenSessions.push(req.headers.get("x-session-id") ?? "");
return openaiOk();
}),
});
expect(resp.status).toBe(200);
}
expect(seenSessions[0]).toBeTruthy();
expect(seenSessions[1]).toBe(seenSessions[0]);
});
it("emits client identity debug line even when no session can be inferred", async () => {
const auth = oauthAuth();
const lines = await captureConsoleLog(async () => {
await proxyRequest(makeClientReq('{"model":"glm-4.6","messages":[]}'), "anthropic", {
config: TEST_CONFIG,
auth,
debug: true,
fetchImpl: mockFetch(async () => openaiOk()),
});
});
expect(lines.some((l) => l.includes("clientIdentity source=none action=observe confidence=0.00 session=-"))).toBe(true);
});
});
|