Skip to content

Commit 4036f87

Browse files
ScottN-PVclaude
andauthored
fix(server): a Limits hub failure names its TLS, HTTP, or timeout cause (pingdotgg#18168)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 599d210 commit 4036f87

2 files changed

Lines changed: 154 additions & 5 deletions

File tree

‎apps/server/src/usage/cliproxyApi.test.ts‎

Lines changed: 110 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import { describe, expect, it } from "@effect/vitest";
33
import * as Effect from "effect/Effect";
4+
import * as Fiber from "effect/Fiber";
45
import * as Schema from "effect/Schema";
56
import * as TestClock from "effect/testing/TestClock";
6-
import { HttpClient, HttpClientResponse } from "effect/http";
7+
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
78

89
import { makeCliproxyApi } from "./cliproxyApi.ts";
910

@@ -114,6 +115,114 @@ function fixture(
114115
};
115116
}
116117

118+
/** A hub API whose every request fails the way `fail` says. */
119+
const unreachableHub = (
120+
fail: (
121+
request: Parameters<Parameters<typeof HttpClient.make>[0]>[0],
122+
) => HttpClientError.HttpClientError,
123+
) =>
124+
makeCliproxyApi.pipe(
125+
Effect.provideService(
126+
HttpClient.HttpClient,
127+
HttpClient.make((request) => Effect.fail(fail(request))),
128+
),
129+
Effect.provide(NodeCrypto.layer),
130+
);
131+
132+
describe("CLIProxyAPI hub failures", () => {
133+
it.effect("names the TLS code when the hub's certificate is not trusted", () =>
134+
Effect.gen(function* () {
135+
const api = yield* unreachableHub(
136+
(request) =>
137+
new HttpClientError.HttpClientError({
138+
reason: new HttpClientError.TransportError({
139+
request,
140+
// Node's fetch wraps the TLS error, which carries the code, in a generic TypeError.
141+
cause: new TypeError("fetch failed", {
142+
cause: Object.assign(new Error("unable to get local issuer certificate"), {
143+
code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
144+
}),
145+
}),
146+
}),
147+
}),
148+
);
149+
const error = yield* Effect.flip(api.readAccounts(config));
150+
expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
151+
expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
152+
}),
153+
);
154+
155+
it.effect("ignores a transport code that is not a short Node error code", () =>
156+
Effect.gen(function* () {
157+
const api = yield* unreachableHub(
158+
(request) =>
159+
new HttpClientError.HttpClientError({
160+
reason: new HttpClientError.TransportError({
161+
request,
162+
cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }),
163+
}),
164+
}),
165+
);
166+
const error = yield* Effect.flip(api.readAccounts(config));
167+
expect(error.detail).toBe("The hub management request failed.");
168+
}),
169+
);
170+
171+
it.effect("names the status, not the body, when the hub rejects the request", () =>
172+
Effect.gen(function* () {
173+
const test = HttpClient.make((request) =>
174+
Effect.succeed(
175+
HttpClientResponse.fromWeb(
176+
request,
177+
Response.json({ error: "management-secret is wrong" }, { status: 401 }),
178+
),
179+
),
180+
);
181+
const api = yield* makeCliproxyApi.pipe(
182+
Effect.provideService(HttpClient.HttpClient, test),
183+
Effect.provide(NodeCrypto.layer),
184+
);
185+
const error = yield* Effect.flip(api.readAccounts(config));
186+
expect(error.detail).toContain("401");
187+
expect(error.detail).not.toContain("management-secret");
188+
}),
189+
);
190+
191+
it.effect("says when the hub does not answer in time", () =>
192+
Effect.gen(function* () {
193+
const api = yield* makeCliproxyApi.pipe(
194+
Effect.provideService(
195+
HttpClient.HttpClient,
196+
HttpClient.make(() => Effect.never),
197+
),
198+
Effect.provide(NodeCrypto.layer),
199+
);
200+
const pending = yield* Effect.flip(api.readAccounts(config)).pipe(
201+
Effect.forkChild({ startImmediately: true }),
202+
);
203+
yield* TestClock.adjust("15 seconds");
204+
const error = yield* Fiber.join(pending);
205+
expect(error.detail).toContain("did not answer within 15 seconds");
206+
}),
207+
);
208+
209+
it.effect("keeps a malformed account list generic", () =>
210+
Effect.gen(function* () {
211+
const test = HttpClient.make((request) =>
212+
Effect.succeed(
213+
HttpClientResponse.fromWeb(request, Response.json({ nope: "hub-internal" })),
214+
),
215+
);
216+
const api = yield* makeCliproxyApi.pipe(
217+
Effect.provideService(HttpClient.HttpClient, test),
218+
Effect.provide(NodeCrypto.layer),
219+
);
220+
const error = yield* Effect.flip(api.readAccounts(config));
221+
expect(error.detail).toBe("The hub could not list accounts.");
222+
}),
223+
);
224+
});
225+
117226
describe("CLIProxyAPI built-in management API", () => {
118227
it.effect(
119228
"reads both accounts and their earliest unexpired credits without plugin endpoints",

‎apps/server/src/usage/cliproxyApi.ts‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import {
55
type UsageLimitSourceAccount,
66
type UsageLimitSourceConfig,
77
} from "@t3tools/contracts";
8+
import * as Cause from "effect/Cause";
89
import * as Crypto from "effect/Crypto";
910
import * as DateTime from "effect/DateTime";
1011
import * as Effect from "effect/Effect";
1112
import * as Hex from "effect/encoding/Hex";
1213
import * as Schema from "effect/Schema";
13-
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14+
import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
1415

1516
import { codexPlanLabel } from "../provider/CodexProvider.ts";
1617
import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
@@ -88,6 +89,43 @@ const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(Credit
8889
const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
8990
const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
9091
const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
92+
93+
// Codes that mean the certificate chain is not trusted, which an extra CA can fix. Expired or
94+
// mismatched certificates are reported by code only.
95+
const UNTRUSTED_CERTIFICATE_CODES = new Set([
96+
"DEPTH_ZERO_SELF_SIGNED_CERT",
97+
"SELF_SIGNED_CERT_IN_CHAIN",
98+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
99+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
100+
]);
101+
102+
/** The Node error code under a failed fetch, which wraps it in a generic `TypeError`. */
103+
const nodeErrorCode = (cause: unknown) => {
104+
for (let error = cause, depth = 0; error instanceof Error && depth < 3; depth += 1) {
105+
const code = (error as { readonly code?: unknown }).code;
106+
if (typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code)) return code;
107+
error = error.cause;
108+
}
109+
return undefined;
110+
};
111+
112+
// Hub responses and nested error messages can carry keys or tokens, so only the failure's kind,
113+
// HTTP status, or Node error code reaches the client.
114+
const describeManagementFailure = (error: unknown) => {
115+
if (Cause.isTimeoutError(error)) return "The hub did not answer within 15 seconds.";
116+
if (HttpClientError.isHttpClientError(error)) {
117+
const reason = error.reason;
118+
if (reason._tag === "StatusCodeError") {
119+
return `The hub answered with HTTP ${reason.response.status}.`;
120+
}
121+
const code = reason._tag === "TransportError" ? nodeErrorCode(reason.cause) : undefined;
122+
if (code !== undefined && UNTRUSTED_CERTIFICATE_CODES.has(code)) {
123+
return `The hub's TLS certificate is not trusted (${code}). If it comes from a private CA, add that CA to NODE_EXTRA_CA_CERTS.`;
124+
}
125+
if (code !== undefined) return `The hub request failed (${code}).`;
126+
}
127+
return "The hub management request failed.";
128+
};
91129
const decodeConsumeResponse = Schema.decodeUnknownEffect(
92130
Schema.fromJsonString(
93131
Schema.Struct({
@@ -147,7 +185,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
147185
Effect.flatMap((response) => response.json),
148186
Effect.timeout("15 seconds"),
149187
Effect.mapError(
150-
() => new UsageLimitSourceError({ detail: "The hub management request failed." }),
188+
(error) => new UsageLimitSourceError({ detail: describeManagementFailure(error) }),
151189
),
152190
);
153191
return response;
@@ -311,8 +349,10 @@ export const makeCliproxyApi = Effect.gen(function* () {
311349
config: UsageLimitSourceConfig,
312350
): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
313351
const accounts = yield* authFiles(config).pipe(
314-
Effect.mapError(
315-
() => new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
352+
Effect.mapError((error) =>
353+
isUsageLimitSourceError(error)
354+
? error
355+
: new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
316356
),
317357
);
318358
return yield* Effect.forEach(

0 commit comments

Comments
 (0)