-
Notifications
You must be signed in to change notification settings - Fork 5k
/
createRPCMethodTrackingMiddleware.js
490 lines (442 loc) · 17.6 KB
/
createRPCMethodTrackingMiddleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import { ApprovalType, detectSIWE } from '@metamask/controller-utils';
import { errorCodes } from '@metamask/rpc-errors';
import { isValidAddress } from 'ethereumjs-util';
import { MESSAGE_TYPE, ORIGIN_METAMASK } from '../../../shared/constants/app';
import {
MetaMetricsEventCategory,
MetaMetricsEventName,
MetaMetricsEventUiCustomization,
} from '../../../shared/constants/metametrics';
import { parseTypedDataMessage } from '../../../shared/modules/transaction.utils';
import {
BlockaidResultType,
BlockaidReason,
} from '../../../shared/constants/security-provider';
import {
PRIMARY_TYPES_ORDER,
PRIMARY_TYPES_PERMIT,
} from '../../../shared/constants/signatures';
import { SIGNING_METHODS } from '../../../shared/constants/transaction';
import { getErrorMessage } from '../../../shared/modules/error';
import {
generateSignatureUniqueId,
getBlockaidMetricsProps,
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
} from '../../../ui/helpers/utils/metrics';
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
import { REDESIGN_APPROVAL_TYPES } from '../../../ui/pages/confirmations/utils/confirm';
import { getSnapAndHardwareInfoForMetrics } from './snap-keyring/metrics';
/**
* These types determine how the method tracking middleware handles incoming
* requests based on the method name.
*/
const RATE_LIMIT_TYPES = {
TIMEOUT: 'timeout',
BLOCKED: 'blocked',
NON_RATE_LIMITED: 'non_rate_limited',
RANDOM_SAMPLE: 'random_sample',
};
/**
* This object maps a method name to a RATE_LIMIT_TYPE. If not in this map the
* default is RANDOM_SAMPLE
*/
const RATE_LIMIT_MAP = {
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V3]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V4]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.PERSONAL_SIGN]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.ETH_DECRYPT]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY]:
RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.ADD_ETHEREUM_CHAIN]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.SWITCH_ETHEREUM_CHAIN]: RATE_LIMIT_TYPES.NON_RATE_LIMITED,
[MESSAGE_TYPE.ETH_REQUEST_ACCOUNTS]: RATE_LIMIT_TYPES.TIMEOUT,
[MESSAGE_TYPE.WALLET_REQUEST_PERMISSIONS]: RATE_LIMIT_TYPES.TIMEOUT,
[MESSAGE_TYPE.SEND_METADATA]: RATE_LIMIT_TYPES.BLOCKED,
[MESSAGE_TYPE.ETH_CHAIN_ID]: RATE_LIMIT_TYPES.BLOCKED,
[MESSAGE_TYPE.ETH_ACCOUNTS]: RATE_LIMIT_TYPES.BLOCKED,
[MESSAGE_TYPE.LOG_WEB3_SHIM_USAGE]: RATE_LIMIT_TYPES.BLOCKED,
[MESSAGE_TYPE.GET_PROVIDER_STATE]: RATE_LIMIT_TYPES.BLOCKED,
};
const MESSAGE_TYPE_TO_APPROVAL_TYPE = {
[MESSAGE_TYPE.PERSONAL_SIGN]: ApprovalType.PersonalSign,
[MESSAGE_TYPE.SIGN]: ApprovalType.SignTransaction,
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA]: ApprovalType.EthSignTypedData,
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V1]: ApprovalType.EthSignTypedData,
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V3]: ApprovalType.EthSignTypedData,
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V4]: ApprovalType.EthSignTypedData,
};
/**
* For events with user interaction (approve / reject | cancel) this map will
* return an object with APPROVED, REJECTED, REQUESTED, and FAILED keys that map to the
* appropriate event names.
*/
const EVENT_NAME_MAP = {
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA]: {
APPROVED: MetaMetricsEventName.SignatureApproved,
REJECTED: MetaMetricsEventName.SignatureRejected,
REQUESTED: MetaMetricsEventName.SignatureRequested,
},
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V3]: {
APPROVED: MetaMetricsEventName.SignatureApproved,
REJECTED: MetaMetricsEventName.SignatureRejected,
REQUESTED: MetaMetricsEventName.SignatureRequested,
},
[MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V4]: {
APPROVED: MetaMetricsEventName.SignatureApproved,
REJECTED: MetaMetricsEventName.SignatureRejected,
REQUESTED: MetaMetricsEventName.SignatureRequested,
},
[MESSAGE_TYPE.PERSONAL_SIGN]: {
APPROVED: MetaMetricsEventName.SignatureApproved,
REJECTED: MetaMetricsEventName.SignatureRejected,
REQUESTED: MetaMetricsEventName.SignatureRequested,
},
[MESSAGE_TYPE.ETH_DECRYPT]: {
APPROVED: MetaMetricsEventName.DecryptionApproved,
REJECTED: MetaMetricsEventName.DecryptionRejected,
REQUESTED: MetaMetricsEventName.DecryptionRequested,
},
[MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY]: {
APPROVED: MetaMetricsEventName.EncryptionPublicKeyApproved,
REJECTED: MetaMetricsEventName.EncryptionPublicKeyRejected,
REQUESTED: MetaMetricsEventName.EncryptionPublicKeyRequested,
},
[MESSAGE_TYPE.ETH_REQUEST_ACCOUNTS]: {
APPROVED: MetaMetricsEventName.PermissionsApproved,
REJECTED: MetaMetricsEventName.PermissionsRejected,
REQUESTED: MetaMetricsEventName.PermissionsRequested,
},
[MESSAGE_TYPE.WALLET_REQUEST_PERMISSIONS]: {
APPROVED: MetaMetricsEventName.PermissionsApproved,
REJECTED: MetaMetricsEventName.PermissionsRejected,
REQUESTED: MetaMetricsEventName.PermissionsRequested,
},
};
/**
* This object maps a method name to a function that accept the method params and
* returns a non-sensitive version that can be included in tracked events.
* The default is to return undefined.
*/
const TRANSFORM_PARAMS_MAP = {
[MESSAGE_TYPE.WATCH_ASSET]: ({ type }) => ({ type }),
[MESSAGE_TYPE.ADD_ETHEREUM_CHAIN]: ([{ chainId }]) => ({ chainId }),
[MESSAGE_TYPE.SWITCH_ETHEREUM_CHAIN]: ([{ chainId }]) => ({ chainId }),
};
const rateLimitTimeoutsByMethod = {};
let globalRateLimitCount = 0;
/**
* Create signature request event fragment with an assigned unique identifier
*
* @param {MetaMetricsController} metaMetricsController
* @param {OriginalRequest} req
* @param {Partial<MetaMetricsEventFragment>} fragmentPayload
*/
function createSignatureFragment(metaMetricsController, req, fragmentPayload) {
metaMetricsController.createEventFragment({
category: MetaMetricsEventCategory.InpageProvider,
initialEvent: MetaMetricsEventName.SignatureRequested,
successEvent: MetaMetricsEventName.SignatureApproved,
failureEvent: MetaMetricsEventName.SignatureRejected,
uniqueIdentifier: generateSignatureUniqueId(req.id),
persist: true,
referrer: {
url: req.origin,
},
...fragmentPayload,
});
}
/**
* Updates and finalizes event fragment for signature requests
*
* @param {MetaMetricsController} metaMetricsController
* @param {OriginalRequest} req
* @param {MetaMetricsFinalizeEventFragmentOptions} finalizeEventOptions
* @param {Partial<MetaMetricsEventFragment>} fragmentPayload
*/
function finalizeSignatureFragment(
metaMetricsController,
req,
finalizeEventOptions,
fragmentPayload,
) {
const signatureUniqueId = generateSignatureUniqueId(req.id);
metaMetricsController.updateEventFragment(signatureUniqueId, fragmentPayload);
metaMetricsController.finalizeEventFragment(
signatureUniqueId,
finalizeEventOptions,
);
}
/**
* Returns a middleware that tracks inpage_provider usage using sampling for
* each type of event except those that require user interaction, such as
* signature requests
*
* @param {object} opts - options for the rpc method tracking middleware
* @param {number} [opts.rateLimitTimeout] - time, in milliseconds, to wait before
* allowing another set of events to be tracked for methods rate limited by timeout.
* @param {number} [opts.rateLimitSamplePercent] - percentage, in decimal, of events
* that should be tracked for methods rate limited by random sample.
* @param {Function} opts.getAccountType
* @param {Function} opts.getDeviceModel
* @param {Function} opts.isConfirmationRedesignEnabled
* @param {RestrictedControllerMessenger} opts.snapAndHardwareMessenger
* @param {number} [opts.globalRateLimitTimeout] - time, in milliseconds, of the sliding
* time window that should limit the number of method calls tracked to globalRateLimitMaxAmount.
* @param {number} [opts.globalRateLimitMaxAmount] - max number of method calls that should
* tracked within the globalRateLimitTimeout time window.
* @param {AppStateController} [opts.appStateController]
* @param {MetaMetricsController} [opts.metaMetricsController]
* @returns {Function}
*/
export default function createRPCMethodTrackingMiddleware({
rateLimitTimeout = 60 * 5 * 1000, // 5 minutes
rateLimitSamplePercent = 0.001, // 0.1%
globalRateLimitTimeout = 60 * 5 * 1000, // 5 minutes
globalRateLimitMaxAmount = 10, // max of events in the globalRateLimitTimeout window. pass 0 for no global rate limit
getAccountType,
getDeviceModel,
isConfirmationRedesignEnabled,
snapAndHardwareMessenger,
appStateController,
metaMetricsController,
}) {
return async function rpcMethodTrackingMiddleware(
/** @type {any} */ req,
/** @type {any} */ res,
/** @type {Function} */ next,
) {
const { origin, method, params } = req;
const rateLimitType = RATE_LIMIT_MAP[method];
let isRateLimited;
switch (rateLimitType) {
case RATE_LIMIT_TYPES.TIMEOUT:
isRateLimited =
typeof rateLimitTimeoutsByMethod[method] !== 'undefined';
break;
case RATE_LIMIT_TYPES.NON_RATE_LIMITED:
isRateLimited = false;
break;
case RATE_LIMIT_TYPES.BLOCKED:
isRateLimited = true;
break;
default:
case RATE_LIMIT_TYPES.RANDOM_SAMPLE:
isRateLimited = Math.random() >= rateLimitSamplePercent;
break;
}
const isGlobalRateLimited =
globalRateLimitMaxAmount > 0 &&
globalRateLimitCount >= globalRateLimitMaxAmount;
// Get the participateInMetaMetrics state to determine if we should track
// anything. This is extra redundancy because this value is checked in
// the metametrics controller's trackEvent method as well.
const userParticipatingInMetaMetrics =
metaMetricsController.state.participateInMetaMetrics === true;
// Get the event type, each of which has APPROVED, REJECTED and REQUESTED
// keys for the various events in the flow.
const eventType = EVENT_NAME_MAP[method];
const eventProperties = {};
let sensitiveEventProperties;
// Boolean variable that reduces code duplication and increases legibility
const shouldTrackEvent =
// Don't track if the request came from our own UI or background
origin !== ORIGIN_METAMASK &&
// Don't track if the rate limit has been hit
!isRateLimited &&
// Don't track if the global rate limit has been hit
!isGlobalRateLimited &&
// Don't track if the user isn't participating in metametrics
userParticipatingInMetaMetrics === true;
if (shouldTrackEvent) {
// We track an initial "requested" event as soon as the dapp calls the
// provider method. For the events not special cased this is the only
// event that will be fired and the event name will be
// 'Provider Method Called'.
const event = eventType
? eventType.REQUESTED
: MetaMetricsEventName.ProviderMethodCalled;
if (event === MetaMetricsEventName.SignatureRequested) {
eventProperties.signature_type = method;
// In personal messages the first param is data while in typed messages second param is data
// if condition below is added to ensure that the right params are captured as data and address.
let data;
if (isValidAddress(req?.params?.[1])) {
data = req?.params?.[0];
} else {
data = req?.params?.[1];
}
if (req.securityAlertResponse?.providerRequestsCount) {
Object.keys(req.securityAlertResponse.providerRequestsCount).forEach(
(key) => {
const metricKey = `ppom_${key}_count`;
eventProperties[metricKey] =
req.securityAlertResponse.providerRequestsCount[key];
},
);
}
eventProperties.security_alert_response =
req.securityAlertResponse?.result_type ??
BlockaidResultType.NotApplicable;
eventProperties.security_alert_reason =
req.securityAlertResponse?.reason ?? BlockaidReason.notApplicable;
if (req.securityAlertResponse?.description) {
eventProperties.security_alert_description =
req.securityAlertResponse.description;
}
const isConfirmationRedesign =
isConfirmationRedesignEnabled() &&
REDESIGN_APPROVAL_TYPES.find(
(type) => type === MESSAGE_TYPE_TO_APPROVAL_TYPE[method],
);
if (isConfirmationRedesign) {
eventProperties.ui_customizations = [
...(eventProperties.ui_customizations || []),
MetaMetricsEventUiCustomization.RedesignedConfirmation,
];
}
const snapAndHardwareInfo = await getSnapAndHardwareInfoForMetrics(
getAccountType,
getDeviceModel,
snapAndHardwareMessenger,
);
// merge the snapAndHardwareInfo into eventProperties
Object.assign(eventProperties, snapAndHardwareInfo);
try {
if (method === MESSAGE_TYPE.PERSONAL_SIGN) {
const { isSIWEMessage } = detectSIWE({ data });
if (isSIWEMessage) {
eventProperties.ui_customizations = [
...(eventProperties.ui_customizations || []),
MetaMetricsEventUiCustomization.Siwe,
];
}
} else if (method === MESSAGE_TYPE.ETH_SIGN_TYPED_DATA_V4) {
const parsedMessageData = parseTypedDataMessage(data);
sensitiveEventProperties = {};
eventProperties.eip712_primary_type = parsedMessageData.primaryType;
sensitiveEventProperties.eip712_verifyingContract =
parsedMessageData.domain.verifyingContract;
sensitiveEventProperties.eip712_domain_version =
parsedMessageData.domain.version;
sensitiveEventProperties.eip712_domain_name =
parsedMessageData.domain.name;
if (PRIMARY_TYPES_PERMIT.includes(parsedMessageData.primaryType)) {
eventProperties.ui_customizations = [
...(eventProperties.ui_customizations || []),
MetaMetricsEventUiCustomization.Permit,
];
} else if (
PRIMARY_TYPES_ORDER.includes(parsedMessageData.primaryType)
) {
eventProperties.ui_customizations = [
...(eventProperties.ui_customizations || []),
MetaMetricsEventUiCustomization.Order,
];
}
}
} catch (e) {
console.warn(`createRPCMethodTrackingMiddleware: Errored - ${e}`);
}
} else {
eventProperties.method = method;
}
const transformParams = TRANSFORM_PARAMS_MAP[method];
if (transformParams) {
eventProperties.params = transformParams(params);
}
if (event === MetaMetricsEventName.SignatureRequested) {
const fragmentPayload = {
properties: eventProperties,
sensitiveProperties: sensitiveEventProperties,
};
createSignatureFragment(metaMetricsController, req, fragmentPayload);
} else {
metaMetricsController.trackEvent({
event,
category: MetaMetricsEventCategory.InpageProvider,
referrer: {
url: origin,
},
properties: eventProperties,
});
}
if (rateLimitType === RATE_LIMIT_TYPES.TIMEOUT) {
rateLimitTimeoutsByMethod[method] = setTimeout(() => {
delete rateLimitTimeoutsByMethod[method];
}, rateLimitTimeout);
}
globalRateLimitCount += 1;
setTimeout(() => {
globalRateLimitCount -= 1;
}, globalRateLimitTimeout);
}
next(async (callback) => {
if (shouldTrackEvent === false || typeof eventType === 'undefined') {
return callback();
}
const location = res.error?.data?.location;
let event;
const errorMessage = getErrorMessage(res.error);
if (res.error?.code === errorCodes.provider.userRejectedRequest) {
event = eventType.REJECTED;
} else if (
res.error?.code === errorCodes.rpc.internal &&
[errorMessage, res.error.message].includes(
'Request rejected by user or snap.',
)
) {
// The signature was approved in MetaMask but rejected in the snap
event = eventType.REJECTED;
eventProperties.status = errorMessage;
} else {
event = eventType.APPROVED;
}
let blockaidMetricProps = {};
if (SIGNING_METHODS.includes(method)) {
const securityAlertResponse =
appStateController.getSignatureSecurityAlertResponse(
req.securityAlertResponse?.securityAlertId,
);
blockaidMetricProps = getBlockaidMetricsProps({
securityAlertResponse,
});
}
const properties = {
...eventProperties,
...blockaidMetricProps,
location,
};
if (
event === MetaMetricsEventName.SignatureRejected ||
event === MetaMetricsEventName.SignatureApproved
) {
const finalizeOptions = {
abandoned: event === eventType.REJECTED,
};
const fragmentPayload = {
properties,
sensitiveProperties: sensitiveEventProperties,
};
finalizeSignatureFragment(
metaMetricsController,
req,
finalizeOptions,
fragmentPayload,
);
} else {
metaMetricsController.trackEvent({
event,
category: MetaMetricsEventCategory.InpageProvider,
referrer: {
url: origin,
},
properties,
});
}
return callback();
});
};
}