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

fix: Confirmation bridge verify backend #25047

Merged
merged 27 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2ecd9a3
chore: write backend confirmation
ejwessel Jun 5, 2024
7f10142
chore: remove console.log
ejwessel Jun 5, 2024
667ecb9
chore: turn signature length into const
ejwessel Jun 5, 2024
b224935
Tx verification updates (#25084)
rekmarks Jun 5, 2024
6ae5b15
chore: substring to substr
ejwessel Jun 6, 2024
c176a5b
test: Add tx verification middleware validation tests (#25114)
rekmarks Jun 7, 2024
51017a1
chore: Fix lavamoat policies (#25135)
rekmarks Jun 7, 2024
6264178
Merge branch 'develop' into confirmation-bridge-verify-backend
rekmarks Jun 7, 2024
d275d4e
fix: LavaMoat policies
rekmarks Jun 7, 2024
6520ed6
Merge branch 'develop' into confirmation-bridge-verify-backend
ejwessel Jun 7, 2024
7eefc9b
Merge branch 'develop' into confirmation-bridge-verify-backend
ejwessel Jun 7, 2024
6ebfd00
chore: update key
ejwessel Jun 10, 2024
614d622
Merge branch 'develop' into confirmation-bridge-verify-backend
rekmarks Jun 10, 2024
1807943
chore: PR update requests
ejwessel Jun 11, 2024
041d911
Merge branch 'develop' into confirmation-bridge-verify-backend
ejwessel Jun 11, 2024
c765d30
chore move constants into dedicated file
ejwessel Jun 11, 2024
00d9f6e
remove 'bridge'
ejwessel Jun 11, 2024
1a1805e
update PR requests
ejwessel Jun 11, 2024
a7c0f4e
made variable names more unopinionated
ejwessel Jun 11, 2024
edd7cf2
refactor to further generalize
ejwessel Jun 11, 2024
a9095b5
chore: lint:fix
ejwessel Jun 11, 2024
065df3d
fix typo
ejwessel Jun 11, 2024
49cd35f
Merge branch 'develop' into confirmation-bridge-verify-backend
ejwessel Jun 11, 2024
eb60a60
chore: added new methods to MESSAGE_TYPE
ejwessel Jun 11, 2024
bc68e30
update linting
ejwessel Jun 12, 2024
2a8935f
PR comments
ejwessel Jun 12, 2024
06eaa70
Merge branch 'develop' into confirmation-bridge-verify-backend
rekmarks Jun 14, 2024
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
255 changes: 255 additions & 0 deletions app/scripts/lib/tx-verification/tx-verification-middleware.test.ts

Large diffs are not rendered by default.

122 changes: 122 additions & 0 deletions app/scripts/lib/tx-verification/tx-verification-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { hashMessage } from '@ethersproject/hash';
import { verifyMessage } from '@ethersproject/wallet';
import type { NetworkController } from '@metamask/network-controller';
import { rpcErrors } from '@metamask/rpc-errors';
import {
Json,
JsonRpcParams,
hasProperty,
isObject,
Hex,
} from '@metamask/utils';
import {
JsonRpcRequest,
JsonRpcResponse,
JsonRpcEngineEndCallback,
JsonRpcEngineNextCallback,
} from 'json-rpc-engine';
import {
EXPERIENCES_TO_VERIFY,
addrToExpMap,
TX_SIG_LEN,
TRUSTED_SIGNERS,
} from '../../../../shared/constants/verification';
import { EXPERIENCES_TYPE } from '../../../../shared/constants/first-party-contracts';
import { MESSAGE_TYPE } from '../../../../shared/constants/app';

export type TxParams = {
chainId?: `0x${string}`;
data: string;
from: string;
to: string;
value: string;
};

/**
* Creates a middleware function that verifies bridge transactions from the
* Portfolio.
*
* @param networkController - The network controller instance.
* @param trustedSigners
* @returns The middleware function.
*/
export function createTxVerificationMiddleware(
networkController: NetworkController,
trustedSigners = TRUSTED_SIGNERS,
) {
return function txVerificationMiddleware(
req: JsonRpcRequest<JsonRpcParams>,
_res: JsonRpcResponse<Json>,
next: JsonRpcEngineNextCallback,
end: JsonRpcEngineEndCallback,
) {
if (
req.method !== MESSAGE_TYPE.ETH_SEND_TRANSACTION ||
ejwessel marked this conversation as resolved.
Show resolved Hide resolved
!Array.isArray(req.params) ||
!isValidParams(req.params)
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
) {
return next();
}

// the tx object is the first element
const params = req.params[0];
const chainId =
typeof params.chainId === 'string'
? (params.chainId.toLowerCase() as Hex)
: networkController.state.providerConfig.chainId;
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved

const r = addrToExpMap[params.to.toLowerCase()];
// if undefined then no address matched
if (!r) {
return next();
}
const { experienceType, chainId: experienceChainId } = r;
// skip if chainId is different
if (experienceChainId !== chainId) {
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
return next();
}
// skip if experience is not one we want to verify against
if (!EXPERIENCES_TO_VERIFY.includes(experienceType as EXPERIENCES_TYPE)) {
return next();
}

const signature = `0x${params.data.slice(-TX_SIG_LEN)}`;
const addressToVerify = verifyMessage(hashedParams(params), signature);
if (addressToVerify !== trustedSigners[experienceType]) {
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
return end(rpcErrors.invalidParams('Invalid transaction signature.'));
}
return next();
};
}

function hashedParams(params: TxParams): string {
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
const paramsToVerify = {
to: hashMessage(params.to.toLowerCase()),
from: hashMessage(params.from.toLowerCase()),
data: hashMessage(
params.data.toLowerCase().slice(0, params.data.length - TX_SIG_LEN),
),
value: hashMessage(params.value.toLowerCase()),
};
return hashMessage(JSON.stringify(paramsToVerify));
}

/**
* Checks if the params of a JSON-RPC request are valid `eth_sendTransaction`
* params.
*
* @param params - The params to validate.
* @returns Whether the params are valid.
*/
function isValidParams(params: Json[]): params is [TxParams] {
return (
isObject(params[0]) &&
typeof params[0].data === 'string' &&
typeof params[0].from === 'string' &&
typeof params[0].to === 'string' &&
typeof params[0].value === 'string' &&
(!hasProperty(params[0], 'chainId') ||
(typeof params[0].chainId === 'string' &&
params[0].chainId.startsWith('0x')))
);
}
6 changes: 6 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ import {
getSmartTransactionsOptInStatus,
getCurrentChainSupportsSmartTransactions,
} from '../../shared/modules/selectors';
import { BaseUrl } from '../../shared/constants/urls';
import {
///: BEGIN:ONLY_INCLUDE_IF(build-mmi)
handleMMITransactionUpdate,
Expand Down Expand Up @@ -324,6 +325,7 @@ import AuthenticationController from './controllers/authentication/authenticatio
import UserStorageController from './controllers/user-storage/user-storage-controller';
import { PushPlatformNotificationsController } from './controllers/push-platform-notifications/push-platform-notifications';
import { MetamaskNotificationsController } from './controllers/metamask-notifications/metamask-notifications';
import { createTxVerificationMiddleware } from './lib/tx-verification/tx-verification-middleware';
import { updateSecurityAlertResponse } from './lib/ppom/ppom-util';

export const METAMASK_CONTROLLER_EVENTS = {
Expand Down Expand Up @@ -5083,6 +5085,10 @@ export default class MetamaskController extends EventEmitter {
engine.push(createLoggerMiddleware({ origin }));
engine.push(this.permissionLogController.createMiddleware());

if (origin === BaseUrl.Portfolio) {
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
engine.push(createTxVerificationMiddleware(this.networkController));
}

///: BEGIN:ONLY_INCLUDE_IF(blockaid)
engine.push(
createPPOMMiddleware(
Expand Down
Loading