Skip to content

Commit c47df08

Browse files
committed
fix(gateway): preserve typed rate-limit failures
1 parent 2d087f0 commit c47df08

10 files changed

Lines changed: 359 additions & 6 deletions

File tree

‎packages/gateway-client/src/client.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,8 @@ export class GatewayClient {
875875
assembled: AssembledConnect,
876876
) {
877877
const role = this.opts.role ?? "operator";
878+
const detailCode =
879+
error instanceof GatewayClientRequestError ? readConnectErrorDetailCode(error.details) : null;
878880
const shouldRetryWithDeviceToken = shouldRetryGatewayWithDeviceToken({
879881
retryBudgetUsed: this.deviceTokenRetryBudgetUsed,
880882
currentDeviceToken: assembled.resolvedDeviceToken,
@@ -886,9 +888,7 @@ export class GatewayClient {
886888
if (
887889
this.opts.deviceIdentity &&
888890
assembled.usingStoredDeviceToken &&
889-
error instanceof GatewayClientRequestError &&
890-
readConnectErrorDetailCode(error.details) ===
891-
ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH
891+
detailCode === ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH
892892
) {
893893
const deviceId = this.opts.deviceIdentity.deviceId;
894894
try {
@@ -942,7 +942,11 @@ export class GatewayClient {
942942
}
943943
this.notifyConnectError(error);
944944
const message = `gateway connect failed: ${formatGatewayClientErrorForLog(error)}`;
945-
if (this.opts.mode === GATEWAY_CLIENT_MODES.PROBE || isGatewayClientStoppedError(error)) {
945+
if (
946+
this.opts.mode === GATEWAY_CLIENT_MODES.PROBE ||
947+
isGatewayClientStoppedError(error) ||
948+
detailCode === ConnectErrorDetailCodes.AUTH_RATE_LIMITED
949+
) {
946950
this.logDebug(message);
947951
} else {
948952
this.logError(message);

‎src/cli/gateway-backed-exit.process.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,43 @@ async function startCronListGateway(token: string): Promise<{ url: string }> {
7878
return { url: `ws://127.0.0.1:${address.port}` };
7979
}
8080

81+
async function startRateLimitedGateway(): Promise<{ url: string }> {
82+
const wss = new WebSocketServer({ host: "127.0.0.1", port: 0 });
83+
activeServers.add(wss);
84+
wss.on("connection", (ws) => {
85+
sendMinimalGatewayConnectChallenge(ws);
86+
ws.on("message", (data) => {
87+
const frame = parseMinimalGatewayRequestFrame(data);
88+
if (frame.type !== "req" || !frame.id || frame.method !== "connect") {
89+
return;
90+
}
91+
const message = "unauthorized: too many failed authentication attempts (retry later)";
92+
ws.send(
93+
JSON.stringify({
94+
type: "res",
95+
id: frame.id,
96+
ok: false,
97+
error: {
98+
code: "INVALID_REQUEST",
99+
message,
100+
retryable: true,
101+
retryAfterMs: 60_000,
102+
details: {
103+
code: "AUTH_RATE_LIMITED",
104+
authReason: "rate_limited",
105+
recommendedNextStep: "wait_then_retry",
106+
},
107+
},
108+
}),
109+
() => ws.close(1008, message),
110+
);
111+
});
112+
});
113+
await once(wss, "listening");
114+
const address = wss.address() as AddressInfo;
115+
return { url: `ws://127.0.0.1:${address.port}` };
116+
}
117+
81118
async function runIsolatedGatewayCli(params: {
82119
args: string[];
83120
root: string;
@@ -298,4 +335,44 @@ describe("gateway-backed CLI process exit", () => {
298335
gateway: { url: `ws://127.0.0.1:${port}` },
299336
});
300337
}, 30_000);
338+
339+
it("preserves pre-hello rate-limit details through the real health entry point", async () => {
340+
const root = tempDirs.make("openclaw-gateway-rate-limit-json-");
341+
const stateDir = path.join(root, "state");
342+
const configPath = path.join(stateDir, "openclaw.json");
343+
const gateway = await startRateLimitedGateway();
344+
await fs.mkdir(stateDir, { recursive: true });
345+
await fs.writeFile(
346+
configPath,
347+
JSON.stringify({
348+
gateway: {
349+
mode: "remote",
350+
remote: { url: gateway.url, token: "test-token" },
351+
},
352+
}),
353+
);
354+
355+
const result = await runIsolatedGatewayCli({
356+
args: ["health", "--json", "--timeout", "2000"],
357+
root,
358+
stateDir,
359+
configPath,
360+
});
361+
362+
expect(result, result.stderr).toMatchObject({ code: 1, signal: null, stderr: "" });
363+
expect(JSON.parse(result.stdout)).toEqual({
364+
ok: false,
365+
error: {
366+
type: "gateway_request_error",
367+
code: "AUTH_RATE_LIMITED",
368+
message:
369+
"Gateway authentication is temporarily rate-limited. Wait for the temporary lockout to expire, then retry.",
370+
retryable: true,
371+
retryAfterMs: 60_000,
372+
},
373+
gateway: { reachable: true },
374+
});
375+
expect(result.stdout).not.toContain("gateway.remote.token");
376+
expect(result.stdout).not.toContain("devices rotate");
377+
}, 30_000);
301378
});

‎src/commands/doctor-gateway-health.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Doctor gateway health tests cover gateway probe failures, auth requirements, and repair messages.
22
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import { GatewayClientRequestError } from "../../packages/gateway-client/src/index.js";
34
import type { OpenClawConfig } from "../config/config.js";
45
import {
56
GATEWAY_HEALTH_CREDENTIALS_REQUIRED_MESSAGE,
@@ -365,6 +366,34 @@ describe("checkGatewayHealth", () => {
365366
expect(output).not.toContain("devices rotate");
366367
});
367368

369+
it("handles the real typed rate-limit error without forcing the credentials predicate", async () => {
370+
const error = new GatewayClientRequestError({
371+
code: "INVALID_REQUEST",
372+
message: "unauthorized: too many failed authentication attempts (retry later)",
373+
details: {
374+
code: "AUTH_RATE_LIMITED",
375+
authReason: "rate_limited",
376+
recommendedNextStep: "wait_then_retry",
377+
},
378+
retryable: true,
379+
retryAfterMs: 60_000,
380+
});
381+
callGateway.mockRejectedValueOnce(error);
382+
const runtime = { log: vi.fn(), error: vi.fn(), exit: vi.fn() };
383+
384+
await expect(
385+
checkGatewayHealth({ runtime: runtime as never, cfg, timeoutMs: 3000 }),
386+
).resolves.toEqual({ authenticated: false, healthOk: true });
387+
388+
expect(isGatewayCredentialsRequiredError).not.toHaveBeenCalled();
389+
expect(probeGatewayStatus).not.toHaveBeenCalled();
390+
expect(runtime.error).not.toHaveBeenCalled();
391+
expect(note).toHaveBeenCalledWith(
392+
GATEWAY_HEALTH_RATE_LIMITED_MESSAGE,
393+
GATEWAY_HEALTH_RATE_LIMITED_TITLE,
394+
);
395+
});
396+
368397
it("reports credentials-required when status RPC auth SecretRefs are unavailable", async () => {
369398
const error = new Error("gateway.auth.password unavailable");
370399
callGateway.mockRejectedValueOnce(error);

‎src/commands/doctor-gateway-health.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
GATEWAY_HEALTH_CREDENTIALS_REQUIRED_TITLE,
2727
GATEWAY_HEALTH_RATE_LIMITED_MESSAGE,
2828
GATEWAY_HEALTH_RATE_LIMITED_TITLE,
29+
gatewayConnectErrorWasRateLimited,
2930
gatewayProbeResultSawGateway,
3031
gatewayProbeResultWasRateLimited,
3132
} from "./gateway-health-auth-diagnostic.js";
@@ -162,6 +163,10 @@ export async function checkGatewayHealth(params: {
162163
}
163164
return { healthOk, authenticated: true, status };
164165
} catch (err) {
166+
if (gatewayConnectErrorWasRateLimited(err)) {
167+
note(GATEWAY_HEALTH_RATE_LIMITED_MESSAGE, GATEWAY_HEALTH_RATE_LIMITED_TITLE);
168+
return { healthOk: true, authenticated: false };
169+
}
165170
if (isGatewayHealthAuthUnavailableError(err)) {
166171
const probeDetails = await buildGatewayProbeConnectionDetails({ config: params.cfg });
167172
const probe = await probeGatewayStatus({

‎src/commands/gateway-health-auth-diagnostic.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,19 @@ export function gatewayProbeResultWasRateLimited(
2828
return gatewayProbeFailureKind(status) === "rate-limited";
2929
}
3030

31+
/** Detects a structured or legacy rate-limit connect error before close projection. */
32+
export function gatewayConnectErrorWasRateLimited(error: unknown): boolean {
33+
if (!(error instanceof Error)) {
34+
return false;
35+
}
36+
return (
37+
classifyGatewayConnectFailure({
38+
details: (error as Error & { details?: unknown }).details,
39+
message: error.message,
40+
}).kind === "rate-limited"
41+
);
42+
}
43+
3144
/**
3245
* Detects when a daemon probe reached the gateway even if read-scope auth failed.
3346
*/
@@ -66,14 +79,23 @@ export function buildCredentialsRequiredHealthDiagnostic() {
6679
}
6780

6881
/** Builds the health diagnostic emitted for a temporary Gateway authentication lockout. */
69-
export function buildRateLimitedHealthDiagnostic() {
82+
export function buildRateLimitedHealthDiagnostic(error?: unknown) {
83+
const retryAfterCandidate =
84+
error instanceof Error ? (error as Error & { retryAfterMs?: unknown }).retryAfterMs : undefined;
85+
const retryAfterMs =
86+
typeof retryAfterCandidate === "number" &&
87+
Number.isSafeInteger(retryAfterCandidate) &&
88+
retryAfterCandidate >= 0
89+
? retryAfterCandidate
90+
: undefined;
7091
return {
7192
ok: false,
7293
error: {
7394
type: "gateway_request_error",
7495
code: ConnectErrorDetailCodes.AUTH_RATE_LIMITED,
7596
message: GATEWAY_HEALTH_RATE_LIMITED_MESSAGE,
7697
retryable: true,
98+
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
7799
},
78100
gateway: {
79101
reachable: true,

‎src/commands/health.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,44 @@ describe("healthCommand", () => {
511511
},
512512
);
513513

514+
it.each([
515+
{ json: true, expectedLogs: 1 },
516+
{ json: undefined, expectedLogs: 2 },
517+
])(
518+
"preserves a typed pre-hello authentication lockout through health output",
519+
async ({ json, expectedLogs }) => {
520+
const error = new GatewayClientRequestError({
521+
code: "INVALID_REQUEST",
522+
message: "unauthorized: too many failed authentication attempts (retry later)",
523+
details: {
524+
code: "AUTH_RATE_LIMITED",
525+
authReason: "rate_limited",
526+
recommendedNextStep: "wait_then_retry",
527+
},
528+
retryable: true,
529+
retryAfterMs: 60_000,
530+
});
531+
callGatewayMock.mockRejectedValueOnce(error);
532+
533+
await healthCommand({ json, timeoutMs: 5000, config: {} }, runtime as never);
534+
535+
expect(isGatewayCredentialsRequiredErrorMock).not.toHaveBeenCalled();
536+
expect(probeGatewayStatusMock).not.toHaveBeenCalled();
537+
expect(runtime.exit).toHaveBeenCalledWith(1);
538+
expect(runtime.log).toHaveBeenCalledTimes(expectedLogs);
539+
if (json) {
540+
expect(JSON.parse(requireFirstRuntimeLog())).toEqual(
541+
buildRateLimitedHealthDiagnostic(error),
542+
);
543+
} else {
544+
expect(runtime.log.mock.calls).toEqual([
545+
[GATEWAY_HEALTH_REACHABLE_LINE],
546+
[GATEWAY_HEALTH_RATE_LIMITED_MESSAGE],
547+
]);
548+
}
549+
},
550+
);
551+
514552
it.each([
515553
{ json: true, expectedLogs: 1 },
516554
{ json: undefined, expectedLogs: 2 },

‎src/commands/health.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
3838
import {
3939
buildCredentialsRequiredHealthDiagnostic,
4040
buildRateLimitedHealthDiagnostic,
41+
gatewayConnectErrorWasRateLimited,
4142
GATEWAY_HEALTH_REACHABLE_LINE,
4243
gatewayProbeResultSawGateway,
4344
gatewayProbeResultWasRateLimited,
@@ -74,9 +75,21 @@ export async function emitReachableGatewayAuthDiagnostic(params: {
7475
localPortOverride?: number;
7576
json?: boolean;
7677
}): Promise<boolean> {
77-
if (!isGatewayHealthAuthUnavailableError(params.error)) {
78+
const directRateLimit = gatewayConnectErrorWasRateLimited(params.error);
79+
if (!directRateLimit && !isGatewayHealthAuthUnavailableError(params.error)) {
7880
return false;
7981
}
82+
if (directRateLimit) {
83+
const diagnostic = buildRateLimitedHealthDiagnostic(params.error);
84+
if (params.json) {
85+
writeRuntimeJson(params.runtime, diagnostic);
86+
} else {
87+
params.runtime.log(GATEWAY_HEALTH_REACHABLE_LINE);
88+
params.runtime.log(diagnostic.error.message);
89+
}
90+
params.runtime.exit(1);
91+
return true;
92+
}
8093
const details = await buildGatewayProbeConnectionDetails({
8194
config: params.config,
8295
token: params.token,

0 commit comments

Comments
 (0)