mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-08 10:11:24 +00:00
feat(gateway): add auth rate-limiting & brute-force protection (#15035)
* feat(gateway): add auth rate-limiting & brute-force protection Add a per-IP sliding-window rate limiter to Gateway authentication endpoints (HTTP, WebSocket upgrade, and WS message-level auth). When gateway.auth.rateLimit is configured, failed auth attempts are tracked per client IP. Once the threshold is exceeded within the sliding window, further attempts are blocked with HTTP 429 + Retry-After until the lockout period expires. Loopback addresses are exempt by default so local CLI sessions are never locked out. The limiter is only created when explicitly configured (undefined otherwise), keeping the feature fully opt-in and backward-compatible. * fix(gateway): isolate auth rate-limit scopes and normalize 429 responses --------- Co-authored-by: buerbaumer <buerbaumer@users.noreply.github.com> Co-authored-by: Peter Steinberger <steipete@gmail.com>
This commit is contained in:
committed by
GitHub
parent
9131b22a28
commit
30b6eccae5
@@ -9,6 +9,7 @@ import {
|
||||
import { createServer as createHttpsServer } from "node:https";
|
||||
import type { CanvasHostHandler } from "../canvas-host/server.js";
|
||||
import type { createSubsystemLogger } from "../logging/subsystem.js";
|
||||
import type { AuthRateLimiter } from "./auth-rate-limit.js";
|
||||
import type { GatewayWsClient } from "./server/ws-types.js";
|
||||
import { resolveAgentAvatar } from "../agents/identity-avatar.js";
|
||||
import {
|
||||
@@ -20,7 +21,12 @@ import {
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import { safeEqualSecret } from "../security/secret-equal.js";
|
||||
import { handleSlackHttpRequest } from "../slack/http/index.js";
|
||||
import { authorizeGatewayConnect, isLocalDirectRequest, type ResolvedGatewayAuth } from "./auth.js";
|
||||
import {
|
||||
authorizeGatewayConnect,
|
||||
isLocalDirectRequest,
|
||||
type GatewayAuthResult,
|
||||
type ResolvedGatewayAuth,
|
||||
} from "./auth.js";
|
||||
import {
|
||||
handleControlUiAvatarRequest,
|
||||
handleControlUiHttpRequest,
|
||||
@@ -43,7 +49,7 @@ import {
|
||||
resolveHookChannel,
|
||||
resolveHookDeliver,
|
||||
} from "./hooks.js";
|
||||
import { sendUnauthorized } from "./http-common.js";
|
||||
import { sendGatewayAuthFailure } from "./http-common.js";
|
||||
import { getBearerToken, getHeader } from "./http-utils.js";
|
||||
import { resolveGatewayClientIp } from "./net.js";
|
||||
import { handleOpenAiHttpRequest } from "./openai-http.js";
|
||||
@@ -105,12 +111,14 @@ async function authorizeCanvasRequest(params: {
|
||||
auth: ResolvedGatewayAuth;
|
||||
trustedProxies: string[];
|
||||
clients: Set<GatewayWsClient>;
|
||||
}): Promise<boolean> {
|
||||
const { req, auth, trustedProxies, clients } = params;
|
||||
rateLimiter?: AuthRateLimiter;
|
||||
}): Promise<GatewayAuthResult> {
|
||||
const { req, auth, trustedProxies, clients, rateLimiter } = params;
|
||||
if (isLocalDirectRequest(req, trustedProxies)) {
|
||||
return true;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
let lastAuthFailure: GatewayAuthResult | null = null;
|
||||
const token = getBearerToken(req);
|
||||
if (token) {
|
||||
const authResult = await authorizeGatewayConnect({
|
||||
@@ -118,10 +126,12 @@ async function authorizeCanvasRequest(params: {
|
||||
connectAuth: { token, password: token },
|
||||
req,
|
||||
trustedProxies,
|
||||
rateLimiter,
|
||||
});
|
||||
if (authResult.ok) {
|
||||
return true;
|
||||
return authResult;
|
||||
}
|
||||
lastAuthFailure = authResult;
|
||||
}
|
||||
|
||||
const clientIp = resolveGatewayClientIp({
|
||||
@@ -131,9 +141,41 @@ async function authorizeCanvasRequest(params: {
|
||||
trustedProxies,
|
||||
});
|
||||
if (!clientIp) {
|
||||
return false;
|
||||
return lastAuthFailure ?? { ok: false, reason: "unauthorized" };
|
||||
}
|
||||
return hasAuthorizedWsClientForIp(clients, clientIp);
|
||||
if (hasAuthorizedWsClientForIp(clients, clientIp)) {
|
||||
return { ok: true };
|
||||
}
|
||||
return lastAuthFailure ?? { ok: false, reason: "unauthorized" };
|
||||
}
|
||||
|
||||
function writeUpgradeAuthFailure(
|
||||
socket: { write: (chunk: string) => void },
|
||||
auth: GatewayAuthResult,
|
||||
) {
|
||||
if (auth.rateLimited) {
|
||||
const retryAfterSeconds =
|
||||
auth.retryAfterMs && auth.retryAfterMs > 0 ? Math.ceil(auth.retryAfterMs / 1000) : undefined;
|
||||
socket.write(
|
||||
[
|
||||
"HTTP/1.1 429 Too Many Requests",
|
||||
retryAfterSeconds ? `Retry-After: ${retryAfterSeconds}` : undefined,
|
||||
"Content-Type: application/json; charset=utf-8",
|
||||
"Connection: close",
|
||||
"",
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message: "Too many failed authentication attempts. Please try again later.",
|
||||
type: "rate_limited",
|
||||
},
|
||||
}),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\r\n"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
||||
}
|
||||
|
||||
export type HooksRequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
|
||||
@@ -372,6 +414,8 @@ export function createGatewayHttpServer(opts: {
|
||||
handleHooksRequest: HooksRequestHandler;
|
||||
handlePluginRequest?: HooksRequestHandler;
|
||||
resolvedAuth: ResolvedGatewayAuth;
|
||||
/** Optional rate limiter for auth brute-force protection. */
|
||||
rateLimiter?: AuthRateLimiter;
|
||||
tlsOptions?: TlsOptions;
|
||||
}): HttpServer {
|
||||
const {
|
||||
@@ -386,6 +430,7 @@ export function createGatewayHttpServer(opts: {
|
||||
handleHooksRequest,
|
||||
handlePluginRequest,
|
||||
resolvedAuth,
|
||||
rateLimiter,
|
||||
} = opts;
|
||||
const httpServer: HttpServer = opts.tlsOptions
|
||||
? createHttpsServer(opts.tlsOptions, (req, res) => {
|
||||
@@ -412,6 +457,7 @@ export function createGatewayHttpServer(opts: {
|
||||
await handleToolsInvokeHttpRequest(req, res, {
|
||||
auth: resolvedAuth,
|
||||
trustedProxies,
|
||||
rateLimiter,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
@@ -430,9 +476,10 @@ export function createGatewayHttpServer(opts: {
|
||||
connectAuth: token ? { token, password: token } : null,
|
||||
req,
|
||||
trustedProxies,
|
||||
rateLimiter,
|
||||
});
|
||||
if (!authResult.ok) {
|
||||
sendUnauthorized(res);
|
||||
sendGatewayAuthFailure(res, authResult);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -446,6 +493,7 @@ export function createGatewayHttpServer(opts: {
|
||||
auth: resolvedAuth,
|
||||
config: openResponsesConfig,
|
||||
trustedProxies,
|
||||
rateLimiter,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
@@ -456,6 +504,7 @@ export function createGatewayHttpServer(opts: {
|
||||
await handleOpenAiHttpRequest(req, res, {
|
||||
auth: resolvedAuth,
|
||||
trustedProxies,
|
||||
rateLimiter,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
@@ -468,9 +517,10 @@ export function createGatewayHttpServer(opts: {
|
||||
auth: resolvedAuth,
|
||||
trustedProxies,
|
||||
clients,
|
||||
rateLimiter,
|
||||
});
|
||||
if (!ok) {
|
||||
sendUnauthorized(res);
|
||||
if (!ok.ok) {
|
||||
sendGatewayAuthFailure(res, ok);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -520,8 +570,10 @@ export function attachGatewayUpgradeHandler(opts: {
|
||||
canvasHost: CanvasHostHandler | null;
|
||||
clients: Set<GatewayWsClient>;
|
||||
resolvedAuth: ResolvedGatewayAuth;
|
||||
/** Optional rate limiter for auth brute-force protection. */
|
||||
rateLimiter?: AuthRateLimiter;
|
||||
}) {
|
||||
const { httpServer, wss, canvasHost, clients, resolvedAuth } = opts;
|
||||
const { httpServer, wss, canvasHost, clients, resolvedAuth, rateLimiter } = opts;
|
||||
httpServer.on("upgrade", (req, socket, head) => {
|
||||
void (async () => {
|
||||
if (canvasHost) {
|
||||
@@ -534,9 +586,10 @@ export function attachGatewayUpgradeHandler(opts: {
|
||||
auth: resolvedAuth,
|
||||
trustedProxies,
|
||||
clients,
|
||||
rateLimiter,
|
||||
});
|
||||
if (!ok) {
|
||||
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
||||
if (!ok.ok) {
|
||||
writeUpgradeAuthFailure(socket, ok);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user