Skip to content

Commit

Permalink
fix: moved validation logic to getRequestResult()
Browse files Browse the repository at this point in the history
Signed-off-by: Logan Nguyen <[email protected]>
  • Loading branch information
quiet-node committed May 13, 2024
1 parent 3d56a56 commit 6d5da4e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 26 deletions.
18 changes: 15 additions & 3 deletions packages/ws-server/src/controllers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
*
*/

import { resolveParams } from '../utils/utils';
import { WS_CONSTANTS } from '../utils/constants';
import WsMetricRegistry from '../metrics/wsMetricRegistry';
import ConnectionLimiter from '../metrics/connectionLimiter';
Expand All @@ -27,6 +26,8 @@ import { Validator } from '@hashgraph/json-rpc-server/dist/validator';
import { handleEthSubsribe, handleEthUnsubscribe } from './eth_subscribe';
import { MirrorNodeClient } from '@hashgraph/json-rpc-relay/dist/lib/clients';
import jsonResp from '@hashgraph/json-rpc-server/dist/koaJsonRpc/lib/RpcResponse';
import { resolveParams, validateJsonRpcRequest, verifySupportedMethod } from '../utils/utils';
import { InvalidRequest, MethodNotFound } from '@hashgraph/json-rpc-server/dist/koaJsonRpc/lib/RpcError';

/**
* Handles sending requests to a Relay by calling a specified method with given parameters.
Expand Down Expand Up @@ -102,6 +103,17 @@ export const getRequestResult = async (
wsMetricRegistry.getCounter('methodsCounter').labels(method).inc();
wsMetricRegistry.getCounter('methodsCounterByIp').labels(ctx.request.ip, method).inc();

// validate request's jsonrpc object
if (!validateJsonRpcRequest(request, logger, requestIdPrefix, connectionIdPrefix)) {
return jsonResp(request.id || null, new InvalidRequest(), undefined);
}

// verify supported method
if (!verifySupportedMethod(request.method)) {
logger.warn(`${connectionIdPrefix} ${requestIdPrefix}: Method not supported: ${request.method}`);
return jsonResp(request.id || null, new MethodNotFound(request.method), undefined);
}

// Validate request's params
try {
const methodValidations = Validator.METHODS[method];
Expand All @@ -110,7 +122,7 @@ export const getRequestResult = async (
Validator.validateParams(params, methodValidations);
}
} catch (error) {
logger.error(
logger.warn(
error,
`${connectionIdPrefix} ${requestIdPrefix} Error in parameter validation. Method: ${method}, params: ${JSON.stringify(
params,
Expand Down Expand Up @@ -152,7 +164,7 @@ export const getRequestResult = async (
response = await handleSendingRequestsToRelay({ ...sharedParams });
}
} catch (error) {
logger.error(
logger.warn(
error,
`${connectionIdPrefix} ${requestIdPrefix} Encountered error on connectionID: ${
ctx.websocket.id
Expand Down
4 changes: 2 additions & 2 deletions packages/ws-server/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export const validateJsonRpcRequest = (
!hasOwnProperty(request, 'id')
) {
logger.warn(
`${connectionIdPrefix} ${requestIdPrefix} Invalid request, body.jsonrpc: ${request.jsonrpc}, body[method]: ${request.method}, body[id]: ${request.id}, ctx.request.method: ${request.method}`,
`${connectionIdPrefix} ${requestIdPrefix} Invalid request, request.jsonrpc: ${request.jsonrpc}, request.method: ${request.method}, request.id: ${request.id}, request.method: ${request.method}`,
);
return false;
} else {
Expand Down Expand Up @@ -148,7 +148,7 @@ export const getMultipleAddressesEnabled = (): boolean => {
* @returns {boolean} A boolean indicating whether WebSocket batch requests are enabled.
*/
export const getWsBatchRequestsEnabled = (): boolean => {
return process.env.WS_BATCH_REQUESTS_ENABLED === 'true' || true;
return process.env.WS_BATCH_REQUESTS_ENABLED ? process.env.WS_BATCH_REQUESTS_ENABLED === 'true' : true;
};

/**
Expand Down
22 changes: 1 addition & 21 deletions packages/ws-server/src/webSocketServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,7 @@ dotenv.config({ path: path.resolve(__dirname, '../../../.env') });
import KoaJsonRpc from '@hashgraph/json-rpc-server/dist/koaJsonRpc';
import jsonResp from '@hashgraph/json-rpc-server/dist/koaJsonRpc/lib/RpcResponse';
import { type Relay, RelayImpl, predefined, JsonRpcError } from '@hashgraph/json-rpc-relay';
import { InvalidRequest, MethodNotFound } from '@hashgraph/json-rpc-server/dist/koaJsonRpc/lib/RpcError';
import {
sendToClient,
handleConnectionClose,
verifySupportedMethod,
validateJsonRpcRequest,
getBatchRequestsMaxSize,
getWsBatchRequestsEnabled,
} from './utils/utils';
import { sendToClient, handleConnectionClose, getBatchRequestsMaxSize, getWsBatchRequestsEnabled } from './utils/utils';

const mainLogger = pino({
name: 'hedera-json-rpc-relay',
Expand Down Expand Up @@ -120,18 +112,6 @@ app.ws.use(async (ctx) => {
return;
}

// validate request's jsonrpc object
if (!validateJsonRpcRequest(request, logger, requestIdPrefix, connectionIdPrefix)) {
ctx.websocket.send(JSON.stringify(jsonResp(request.id || null, new InvalidRequest(), undefined)));
return;
}

// verify supported method
if (!verifySupportedMethod(request.method)) {
ctx.websocket.send(JSON.stringify(jsonResp(request.id || null, new MethodNotFound(request.method), undefined)));
logger.warn(`${connectionIdPrefix} ${requestIdPrefix}: Method not found: ${request.method}`);
return;
}
// check if request is a batch request (array) or a signle request (JSON)
if (Array.isArray(request)) {
logger.trace(`${connectionIdPrefix} ${requestIdPrefix}: Receive batch request=${JSON.stringify(request)}`);
Expand Down

0 comments on commit 6d5da4e

Please sign in to comment.