|
| 1 | +/** |
| 2 | + * Tests for the two resilience behaviors added after the PR #34 review: |
| 3 | + * |
| 4 | + * 1. In-body captcha challenge detection: a start-plan upstream response with |
| 5 | + * HTTP 400 + {"code":3007,...} in the JSON body (no captcha header) must |
| 6 | + * be treated as a captcha challenge and retried with a fresh token. |
| 7 | + * 2. Connect-retry freshness: after a connect-level failure, the retried |
| 8 | + * dispatch must receive a FRESH Request (body not marked used). A mock |
| 9 | + * fetch that throws-then-succeeds does NOT catch the bug (mocks don't |
| 10 | + * enforce bodyUsed), so the mock asserts `req.bodyUsed === false` on |
| 11 | + * every call per the review's test note. |
| 12 | + * |
| 13 | + * Both tests use the start-plan path with an injected captcha module via |
| 14 | + * `mock.module("./captcha.js")` (same technique as captcha-pool.test.ts). |
| 15 | + */ |
| 16 | +import { describe, it, expect, mock } from "bun:test"; |
| 17 | +import { proxyRequest } from "./handler.js"; |
| 18 | +import type { ProxyConfig, ProxyIdentity } from "../config/types.js"; |
| 19 | +import { AuthManager } from "../auth/manager.js"; |
| 20 | + |
| 21 | +const IDENTITY: ProxyIdentity = { |
| 22 | + appVersion: "test-1.0.0", |
| 23 | + sourceTitle: "cli", |
| 24 | + refererOrigin: "https://zcode.z.ai", |
| 25 | +}; |
| 26 | + |
| 27 | +const TEST_CONFIG: ProxyConfig = { |
| 28 | + server: { port: 8080, host: "0.0.0.0" }, |
| 29 | + auth: { mode: "apikey", apiKey: "testk...ret" }, |
| 30 | + provider: "zai", |
| 31 | + plan: "start-plan", |
| 32 | + providers: { |
| 33 | + zai: { anthropicBase: "https://api.z.ai/api/anthropic", openaiBase: "https://api.z.ai/api/coding/paas/v4" }, |
| 34 | + bigmodel: { anthropicBase: "https://open.bigmodel.cn/api/anthropic", openaiBase: "https://open.bigmodel.cn/api/coding/paas/v4" }, |
| 35 | + }, |
| 36 | + defaultModel: "glm-4.6", |
| 37 | + models: ["glm-4.6"], |
| 38 | + identity: IDENTITY, |
| 39 | + clientIdentity: { mode: "observe", ttlSeconds: 900, maxSessions: 1024 }, |
| 40 | + responses: { enabled: true, storeMaxEntries: 1000, storeTtlMs: 86400000 }, |
| 41 | + endpointRouting: { enabled: false, origin: "https://zcode.z.ai" }, |
| 42 | + clientSigning: { enabled: false, origin: "https://zcode.z.ai" }, |
| 43 | + mcp: { enabled: true, webSearch: true, webReader: false, zread: false }, |
| 44 | + async: { enabled: false, origin: "https://zcode.z.ai", pollIntervalMs: 5000, keepAliveIntervalMs: 3000, maxWaitMs: 0, maxRetries: 3, settleTimeoutMs: 8000, controlTimeoutMs: 15000, defaultModel: "" }, |
| 45 | + claim: { enabled: false, auto: true, origin: "https://zcode.z.ai", pollIntervalMs: 300000, cooldownMs: 600000, planId: "" }, |
| 46 | + logging: { level: "info" }, |
| 47 | +}; |
| 48 | + |
| 49 | +const GATEWAY_URL = "https://zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages"; |
| 50 | + |
| 51 | +const ANTHROPIC_OK = JSON.stringify({ |
| 52 | + id: "msg_resilience", |
| 53 | + type: "message", |
| 54 | + role: "assistant", |
| 55 | + model: "glm-4.6", |
| 56 | + content: [{ type: "text", text: "resilience reply" }], |
| 57 | + stop_reason: "end_turn", |
| 58 | + stop_sequence: null, |
| 59 | + usage: { input_tokens: 5, output_tokens: 3 }, |
| 60 | +}); |
| 61 | + |
| 62 | +describe("proxyRequest — start-plan resilience (PR #34 review P1/P3)", () => { |
| 63 | + it("retries an in-body 3007 captcha challenge with a fresh token", async () => { |
| 64 | + // Mock the captcha module: config enabled, token take returns distinct |
| 65 | + // tokens per call so we can assert the retry used a FRESH token. |
| 66 | + let tokenSeq = 0; |
| 67 | + mock.module("./captcha.js", () => ({ |
| 68 | + detectCaptchaChallenge: (resp: Response): string | null => { |
| 69 | + const v = resp.headers.get("x-aliyun-captcha-verify-param"); |
| 70 | + return v && v.trim().length > 0 ? v.trim() : null; |
| 71 | + }, |
| 72 | + getCaptchaToken: async (_appVersion: string) => { |
| 73 | + tokenSeq += 1; |
| 74 | + return { verifyParam: `tok-${tokenSeq}`, region: "sgp" }; |
| 75 | + }, |
| 76 | + RETRY_HEADERS: { PARAM: "x-aliyun-captcha-verify-param", REGION: "x-aliyun-captcha-verify-region" }, |
| 77 | + })); |
| 78 | + |
| 79 | + // Upstream: first call = HTTP 400 with {"code":3007} in the body (no |
| 80 | + // captcha header), second call = success. The mock also records the |
| 81 | + // captcha header of each call so we can assert the retry used a FRESH |
| 82 | + // token (tok-2, not the consumed tok-1). |
| 83 | + const seenCaptchaHeaders: (string | null)[] = []; |
| 84 | + let calls = 0; |
| 85 | + const fetchMock = mock(async (req: Request): Promise<Response> => { |
| 86 | + if (req.url.includes("/client/configs")) { |
| 87 | + return new Response(JSON.stringify({ data: { configs: { captcha: { enabled: true } } } }), { |
| 88 | + status: 200, headers: { "content-type": "application/json" }, |
| 89 | + }); |
| 90 | + } |
| 91 | + calls += 1; |
| 92 | + seenCaptchaHeaders.push(req.headers.get("x-aliyun-captcha-verify-param")); |
| 93 | + if (calls === 1) { |
| 94 | + return new Response(JSON.stringify({ code: 3007, msg: "captcha verify failed" }), { |
| 95 | + status: 400, headers: { "content-type": "application/json" }, |
| 96 | + }); |
| 97 | + } |
| 98 | + return new Response(ANTHROPIC_OK, { status: 200, headers: { "content-type": "application/json" } }); |
| 99 | + }); |
| 100 | + |
| 101 | + const auth = new AuthManager({ mode: "oauth", provider: "zai" }); |
| 102 | + auth.setOAuthCredential({ apiKey: "key-mock", provider: "zai", jwt: "jwt-mock" }); |
| 103 | + const clientReq = new Request("http://localhost:8080/v1/chat/completions", { |
| 104 | + method: "POST", |
| 105 | + headers: { "content-type": "application/json" }, |
| 106 | + body: '{"model":"glm-4.6","messages":[{"role":"user","content":"hi"}]}', |
| 107 | + }); |
| 108 | + |
| 109 | + const resp = await proxyRequest(clientReq, "openai", { config: TEST_CONFIG, auth, fetchImpl: fetchMock as any }); |
| 110 | + |
| 111 | + // The in-body 3007 challenge was detected and retried with a fresh token. |
| 112 | + expect(calls).toBe(2); |
| 113 | + expect(seenCaptchaHeaders[0]).toBe("tok-1"); |
| 114 | + expect(seenCaptchaHeaders[1]).toBe("tok-2"); |
| 115 | + expect(resp.status).toBe(200); |
| 116 | + const body = await resp.json(); |
| 117 | + expect(body.choices[0].message.content).toBe("resilience reply"); |
| 118 | + }); |
| 119 | + |
| 120 | + it("retries a connect failure with a FRESH Request (body not marked used)", async () => { |
| 121 | + // Upstream: first call = connect-level failure (the bug shape), second |
| 122 | + // call = success. The mock asserts req.bodyUsed === false on EVERY call |
| 123 | + // per the review's test note: mocks don't enforce bodyUsed the way real |
| 124 | + // fetch does, so the freshness assertion must be explicit. |
| 125 | + let calls = 0; |
| 126 | + const fetchMock = mock(async (req: Request): Promise<Response> => { |
| 127 | + calls += 1; |
| 128 | + // The freshness assertion: if the handler re-dispatched the SAME |
| 129 | + // Request object, this would be true on the second call. |
| 130 | + expect(req.bodyUsed).toBe(false); |
| 131 | + if (calls === 1) { |
| 132 | + throw new Error("Unable to connect. Is the computer able to access the url?"); |
| 133 | + } |
| 134 | + return new Response(ANTHROPIC_OK, { status: 200, headers: { "content-type": "application/json" } }); |
| 135 | + }); |
| 136 | + |
| 137 | + const auth = new AuthManager({ mode: "oauth", provider: "zai" }); |
| 138 | + auth.setOAuthCredential({ apiKey: "key-mock", provider: "zai", jwt: "jwt-mock" }); |
| 139 | + const clientReq = new Request("http://localhost:8080/v1/chat/completions", { |
| 140 | + method: "POST", |
| 141 | + headers: { "content-type": "application/json" }, |
| 142 | + body: '{"model":"glm-4.6","messages":[{"role":"user","content":"hi"}]}', |
| 143 | + }); |
| 144 | + |
| 145 | + const resp = await proxyRequest(clientReq, "openai", { config: TEST_CONFIG, auth, fetchImpl: fetchMock as any }); |
| 146 | + |
| 147 | + // The connect failure was retried with a FRESH Request (bodyUsed false |
| 148 | + // on the second call — the freshness assertion inside the mock passed). |
| 149 | + expect(calls).toBe(2); |
| 150 | + expect(resp.status).toBe(200); |
| 151 | + const body = await resp.json(); |
| 152 | + expect(body.choices[0].message.content).toBe("resilience reply"); |
| 153 | + }); |
| 154 | +}); |
0 commit comments