Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SHARD-1234: use rate limiter for websocket messages #102

Merged
merged 2 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/middlewares/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async function handleRejection(res: Response, softReject: boolean): Promise<void
}
}

async function checkRequest(ip: string, request: RpcRequest): Promise<boolean> {
export async function checkRequest(ip: string, request: RpcRequest): Promise<boolean> {
return await requestersList.isRequestOkay(ip, request.method, request.params)
}

Expand Down
37 changes: 36 additions & 1 deletion src/websocket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { evmLogProvider_ConnectionStream } from './log_server'
import { SubscriptionDetails } from './clients'
import { nestedCountersInstance } from '../utils/nestedCounters'
import { IncomingMessage } from 'http'
import {checkRequest, requestersList} from "../middlewares/rateLimit";

interface Params {
address?: string | string[]
Expand Down Expand Up @@ -62,6 +63,13 @@ export const onConnection = async (socket: WebSocket.WebSocket, req: IncomingMes
)
return
}
if (requestersList.isIpBanned(ip)) {
socket.close(
1008,
'Connection closed: IP banned from opening new connections.'
)
return
}

const currentIPConnections = connectionsByIP.get(ip) || new Set()

Expand Down Expand Up @@ -92,7 +100,34 @@ export const onConnection = async (socket: WebSocket.WebSocket, req: IncomingMes

const eth_methods = Object.freeze(wrappedMethods)

socket.on('message', (message: string) => {
socket.on('message', async (message: string) => {
if (CONFIG.rateLimit) {
let request
try {
request = JSON.parse(message)
} catch (e) {
socket.send('Invalid message format')
return
}

try {
const isRequestOkay = await checkRequest(ip, request)

if (!isRequestOkay) {
socket.close(
1008,
JSON.stringify({ jsonrpc: '2.0', error: { code: -1, message: 'Rate limit exceeded' } })
)
return
}

} catch (error) {
console.error('Rate limiting error:', error)
socket.close(1008, 'Internal server error')
return
}
}

// Update last activity time on message received
socketActivityMap.set(socket, Date.now())

Expand Down
Loading