-
-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathauthenticated-user-storage.test.ts
More file actions
649 lines (523 loc) · 20.5 KB
/
Copy pathauthenticated-user-storage.test.ts
File metadata and controls
649 lines (523 loc) · 20.5 KB
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import { Messenger, MOCK_ANY_NAMESPACE } from '@metamask/messenger';
import type {
MockAnyNamespace,
MessengerActions,
MessengerEvents,
} from '@metamask/messenger';
import nock from 'nock';
import {
handleMockListDelegations,
handleMockCreateDelegation,
handleMockRevokeDelegation,
handleMockGetNotificationPreferences,
handleMockPutNotificationPreferences,
handleMockGetAssetsWatchlist,
handleMockSetAssetsWatchlist,
} from '../tests/fixtures/authenticated-userstorage';
import {
MOCK_DELEGATION_RESPONSE,
MOCK_DELEGATION_SUBMISSION,
MOCK_INVALID_ASSETS_WATCHLIST_BLOB,
MOCK_LEGACY_NOTIFICATION_PREFERENCES,
MOCK_NOTIFICATION_PREFERENCES,
MOCK_ASSETS_WATCHLIST_BLOB,
MOCK_ASSETS_WATCHLIST_URL,
} from '../tests/mocks/authenticated-userstorage';
import type { AuthenticatedUserStorageMessenger } from './authenticated-user-storage';
import {
getAuthenticatedStorageUrl,
AuthenticatedUserStorageService,
} from './authenticated-user-storage';
import type { Environment } from './env';
import { getUserStorageApiUrl } from './env';
import {
ASSETS_WATCHLIST_MAX_ASSETS,
DEFAULT_AGENTIC_CLI_PREFERENCES,
} from './validators';
const MOCK_ACCESS_TOKEN = 'mock-access-token';
describe('getUserStorageApiUrl()', () => {
it('returns the API URL for a valid environment', () => {
const result = getUserStorageApiUrl('prod');
expect(result).toBe('https://user-storage.api.cx.metamask.io');
});
it('throws for an invalid environment', () => {
expect(() => getUserStorageApiUrl('invalid' as Environment)).toThrow(
'Invalid environment: invalid',
);
});
});
describe('getAuthenticatedStorageUrl()', () => {
it('generates the base URL for a given environment', () => {
const result = getAuthenticatedStorageUrl('prod');
expect(result).toBe('https://user-storage.api.cx.metamask.io/api/v1');
});
});
describe('AuthenticatedUserStorageService', () => {
afterEach(() => {
nock.cleanAll(); // eslint-disable-line import-x/no-named-as-default-member
});
describe('AuthenticatedUserStorageService:listDelegations', () => {
it('returns delegation records via the messenger', async () => {
handleMockListDelegations();
const { rootMessenger } = createService();
const result = await rootMessenger.call(
'AuthenticatedUserStorageService:listDelegations',
);
expect(result).toStrictEqual([MOCK_DELEGATION_RESPONSE]);
});
});
describe('listDelegations', () => {
it('returns delegation records from the API', async () => {
const mock = handleMockListDelegations();
const { service } = createService();
const result = await service.listDelegations();
expect(mock.isDone()).toBe(true);
expect(result).toStrictEqual([MOCK_DELEGATION_RESPONSE]);
});
it('throws when the API returns a non-200 status', async () => {
handleMockListDelegations({ status: 500 });
const { service } = createService();
await expect(service.listDelegations()).rejects.toThrow(
'Failed to list delegations: 500',
);
});
});
describe('createDelegation', () => {
it('submits a delegation to the API', async () => {
const mock = handleMockCreateDelegation();
const { service } = createService();
await service.createDelegation(MOCK_DELEGATION_SUBMISSION);
expect(mock.isDone()).toBe(true);
});
it('includes X-Client-Type header when clientType is provided', async () => {
const mock = handleMockCreateDelegation();
const { service } = createService();
await service.createDelegation(MOCK_DELEGATION_SUBMISSION, 'extension');
expect(mock.isDone()).toBe(true);
});
it('throws when the API returns a 409 conflict', async () => {
handleMockCreateDelegation({ status: 409 });
const { service } = createService();
await expect(
service.createDelegation(MOCK_DELEGATION_SUBMISSION),
).rejects.toThrow('Failed to create delegation: 409');
});
it('throws when the API returns a non-200 status', async () => {
handleMockCreateDelegation({ status: 400 });
const { service } = createService();
await expect(
service.createDelegation(MOCK_DELEGATION_SUBMISSION),
).rejects.toThrow('Failed to create delegation: 400');
});
it('sends the correct request body', async () => {
handleMockCreateDelegation(undefined, async (_, requestBody) => {
expect(requestBody).toStrictEqual(MOCK_DELEGATION_SUBMISSION);
});
const { service } = createService();
await service.createDelegation(MOCK_DELEGATION_SUBMISSION);
});
});
describe('revokeDelegation', () => {
it('revokes a delegation via the API', async () => {
const mock = handleMockRevokeDelegation();
const { service } = createService();
await service.revokeDelegation(
MOCK_DELEGATION_SUBMISSION.metadata.delegationHash,
);
expect(mock.isDone()).toBe(true);
});
it('throws when the API returns a 404', async () => {
handleMockRevokeDelegation({ status: 404 });
const { service } = createService();
await expect(service.revokeDelegation('0xdeadbeef')).rejects.toThrow(
'Failed to revoke delegation: 404',
);
});
it('throws when the API returns a non-200 status', async () => {
handleMockRevokeDelegation({ status: 500 });
const { service } = createService();
await expect(service.revokeDelegation('0xdeadbeef')).rejects.toThrow(
'Failed to revoke delegation: 500',
);
});
});
describe('getNotificationPreferences', () => {
it('returns notification preferences from the API', async () => {
const mock = handleMockGetNotificationPreferences();
const { service } = createService();
const result = await service.getNotificationPreferences();
expect(mock.isDone()).toBe(true);
expect(result).toStrictEqual(MOCK_NOTIFICATION_PREFERENCES);
});
it('returns null when preferences are not found', async () => {
handleMockGetNotificationPreferences({ status: 404 });
const { service } = createService();
const result = await service.getNotificationPreferences();
expect(result).toBeNull();
});
it('throws when the API returns a non-200/404 status', async () => {
handleMockGetNotificationPreferences({ status: 500 });
const { service } = createService();
await expect(service.getNotificationPreferences()).rejects.toThrow(
'Failed to get notification preferences: 500',
);
});
it('coerces legacy payloads that omit agenticCli', async () => {
handleMockGetNotificationPreferences({
status: 200,
body: MOCK_LEGACY_NOTIFICATION_PREFERENCES,
});
const { service } = createService();
const result = await service.getNotificationPreferences();
expect(result).toStrictEqual({
...MOCK_LEGACY_NOTIFICATION_PREFERENCES,
agenticCli: DEFAULT_AGENTIC_CLI_PREFERENCES,
});
});
it('does not mutate DEFAULT_AGENTIC_CLI_PREFERENCES when coercing legacy payloads', async () => {
handleMockGetNotificationPreferences({
status: 200,
body: MOCK_LEGACY_NOTIFICATION_PREFERENCES,
});
const { service } = createService();
const result = await service.getNotificationPreferences();
expect(result).not.toBeNull();
if (!result) {
throw new Error('Result is null');
}
result.agenticCli.inAppNotificationsEnabled = false;
expect(DEFAULT_AGENTIC_CLI_PREFERENCES.inAppNotificationsEnabled).toBe(
true,
);
});
});
describe('putNotificationPreferences', () => {
it('submits notification preferences to the API', async () => {
const mock = handleMockPutNotificationPreferences();
const { service } = createService();
await service.putNotificationPreferences(MOCK_NOTIFICATION_PREFERENCES);
expect(mock.isDone()).toBe(true);
});
it('includes X-Client-Type header when clientType is provided', async () => {
const mock = handleMockPutNotificationPreferences();
const { service } = createService();
await service.putNotificationPreferences(
MOCK_NOTIFICATION_PREFERENCES,
'mobile',
);
expect(mock.isDone()).toBe(true);
});
it('sends the correct request body', async () => {
handleMockPutNotificationPreferences(
undefined,
async (_, requestBody) => {
expect(requestBody).toStrictEqual(MOCK_NOTIFICATION_PREFERENCES);
},
);
const { service } = createService();
await service.putNotificationPreferences(MOCK_NOTIFICATION_PREFERENCES);
});
it('throws when the API returns a non-200 status', async () => {
handleMockPutNotificationPreferences({ status: 400 });
const { service } = createService();
await expect(
service.putNotificationPreferences(MOCK_NOTIFICATION_PREFERENCES),
).rejects.toThrow('Failed to put notification preferences: 400');
});
});
describe('AuthenticatedUserStorageService:getAssetsWatchlist', () => {
it('returns the assets-watchlist via the messenger', async () => {
handleMockGetAssetsWatchlist();
const { rootMessenger } = createService();
const result = await rootMessenger.call(
'AuthenticatedUserStorageService:getAssetsWatchlist',
);
expect(result).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
});
});
describe('AuthenticatedUserStorageService:setAssetsWatchlist', () => {
it('sets the assets-watchlist via the messenger', async () => {
const mock = handleMockSetAssetsWatchlist();
const { rootMessenger } = createService();
await rootMessenger.call(
'AuthenticatedUserStorageService:setAssetsWatchlist',
MOCK_ASSETS_WATCHLIST_BLOB,
);
expect(mock.isDone()).toBe(true);
});
});
describe('getAssetsWatchlist', () => {
it('returns the assets-watchlist from the API', async () => {
const mock = handleMockGetAssetsWatchlist();
const { service } = createService();
const result = await service.getAssetsWatchlist();
expect(mock.isDone()).toBe(true);
expect(result).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
});
it('sends the Authorization header', async () => {
const scope = nock(MOCK_ASSETS_WATCHLIST_URL, {
reqheaders: {
authorization: 'Bearer mock-access-token',
},
})
.get('')
.reply(200, MOCK_ASSETS_WATCHLIST_BLOB);
const { service } = createService();
const result = await service.getAssetsWatchlist();
expect(scope.isDone()).toBe(true);
expect(result).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
});
it('returns null when the assets-watchlist is not found', async () => {
handleMockGetAssetsWatchlist({ status: 404 });
const { service } = createService();
const result = await service.getAssetsWatchlist();
expect(result).toBeNull();
});
it('throws when the API returns a non-200/404 status', async () => {
handleMockGetAssetsWatchlist({ status: 500 });
const { service } = createService();
await expect(service.getAssetsWatchlist()).rejects.toThrow(
'Failed to get assets watchlist: 500',
);
});
it('throws when the API returns a 401', async () => {
handleMockGetAssetsWatchlist({ status: 401 });
const { service } = createService();
await expect(service.getAssetsWatchlist()).rejects.toThrow(
'Failed to get assets watchlist: 401',
);
});
it('throws when the response body is malformed', async () => {
handleMockGetAssetsWatchlist({
status: 200,
body: MOCK_INVALID_ASSETS_WATCHLIST_BLOB,
});
const { service } = createService();
await expect(service.getAssetsWatchlist()).rejects.toThrow(
/Expected.*but received/u,
);
});
it('caches the result so a second call within staleTime does not re-fetch', async () => {
const scope = nock(MOCK_ASSETS_WATCHLIST_URL)
.get('')
.once()
.reply(200, MOCK_ASSETS_WATCHLIST_BLOB);
const { service } = createService();
const first = await service.getAssetsWatchlist();
const second = await service.getAssetsWatchlist();
expect(scope.isDone()).toBe(true);
expect(first).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
expect(second).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
});
});
describe('setAssetsWatchlist', () => {
it('submits the assets-watchlist to the API', async () => {
const mock = handleMockSetAssetsWatchlist();
const { service } = createService();
await service.setAssetsWatchlist(MOCK_ASSETS_WATCHLIST_BLOB);
expect(mock.isDone()).toBe(true);
});
it('sends the correct request body', async () => {
handleMockSetAssetsWatchlist(undefined, async (_, requestBody) => {
expect(requestBody).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
});
const { service } = createService();
await service.setAssetsWatchlist(MOCK_ASSETS_WATCHLIST_BLOB);
});
it('sends Content-Type and Authorization headers but no X-Client-Type when clientType is omitted', async () => {
const scope = nock(MOCK_ASSETS_WATCHLIST_URL, {
reqheaders: {
'content-type': 'application/json',
authorization: 'Bearer mock-access-token',
},
badheaders: ['x-client-type'],
})
.put('')
.reply(200);
const { service } = createService();
await service.setAssetsWatchlist(MOCK_ASSETS_WATCHLIST_BLOB);
expect(scope.isDone()).toBe(true);
});
it('includes X-Client-Type header when clientType is provided', async () => {
const scope = nock(MOCK_ASSETS_WATCHLIST_URL, {
reqheaders: {
'x-client-type': 'extension',
},
})
.put('')
.reply(200);
const { service } = createService();
await service.setAssetsWatchlist(MOCK_ASSETS_WATCHLIST_BLOB, 'extension');
expect(scope.isDone()).toBe(true);
});
it('throws when the API returns a non-200 status', async () => {
handleMockSetAssetsWatchlist({ status: 400 });
const { service } = createService();
await expect(
service.setAssetsWatchlist(MOCK_ASSETS_WATCHLIST_BLOB),
).rejects.toThrow('Failed to put assets watchlist: 400');
});
it(`throws synchronously when the blob exceeds ${ASSETS_WATCHLIST_MAX_ASSETS} assets`, async () => {
const { service } = createService();
const oversized = {
version: 1 as const,
assets: Array.from(
{ length: ASSETS_WATCHLIST_MAX_ASSETS + 1 },
(_, index) =>
`eip155:1/erc20:0x${index.toString(16).padStart(40, '0')}`,
),
};
await expect(service.setAssetsWatchlist(oversized)).rejects.toThrow(
new RegExp(
`At path: assets -- Expected a array with a length between \`0\` and \`${ASSETS_WATCHLIST_MAX_ASSETS}\` but received one with a length of \`${ASSETS_WATCHLIST_MAX_ASSETS + 1}\``,
'u',
),
);
});
it('throws a structural error before sending the request when the blob is malformed', async () => {
const { service } = createService();
const malformed = {
version: 2,
assets: ['eip155:1/slip44:60'],
} as unknown as Parameters<typeof service.setAssetsWatchlist>[0];
await expect(service.setAssetsWatchlist(malformed)).rejects.toThrow(
/At path: version -- Expected the literal/u,
);
});
it(`accepts a blob with exactly ${ASSETS_WATCHLIST_MAX_ASSETS} assets`, async () => {
const mock = handleMockSetAssetsWatchlist();
const { service } = createService();
const maxBlob = {
version: 1 as const,
assets: Array.from(
{ length: ASSETS_WATCHLIST_MAX_ASSETS },
(_, index) =>
`eip155:1/erc20:0x${index.toString(16).padStart(40, '0')}`,
),
};
await service.setAssetsWatchlist(maxBlob);
expect(mock.isDone()).toBe(true);
});
});
describe('cache invalidation', () => {
it('invalidates listDelegations cache after createDelegation', async () => {
handleMockCreateDelegation();
handleMockListDelegations();
const { service } = createService();
const invalidateSpy = jest.spyOn(service, 'invalidateQueries');
await service.createDelegation(MOCK_DELEGATION_SUBMISSION);
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: ['AuthenticatedUserStorageService:listDelegations'],
});
});
it('invalidates listDelegations cache after revokeDelegation', async () => {
handleMockRevokeDelegation();
handleMockListDelegations();
const { service } = createService();
const invalidateSpy = jest.spyOn(service, 'invalidateQueries');
await service.revokeDelegation(
MOCK_DELEGATION_SUBMISSION.metadata.delegationHash,
);
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: ['AuthenticatedUserStorageService:listDelegations'],
});
});
it('invalidates getNotificationPreferences cache after putNotificationPreferences', async () => {
handleMockPutNotificationPreferences();
handleMockGetNotificationPreferences();
const { service } = createService();
const invalidateSpy = jest.spyOn(service, 'invalidateQueries');
await service.putNotificationPreferences(MOCK_NOTIFICATION_PREFERENCES);
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: [
'AuthenticatedUserStorageService:getNotificationPreferences',
],
});
});
it('invalidates getAssetsWatchlist cache after setAssetsWatchlist', async () => {
handleMockSetAssetsWatchlist();
handleMockGetAssetsWatchlist();
const { service } = createService();
const invalidateSpy = jest.spyOn(service, 'invalidateQueries');
await service.setAssetsWatchlist(MOCK_ASSETS_WATCHLIST_BLOB);
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: ['AuthenticatedUserStorageService:getAssetsWatchlist'],
});
});
it('causes a subsequent getAssetsWatchlist to refetch after setAssetsWatchlist', async () => {
const updatedBlob = {
version: 1 as const,
assets: ['eip155:137/slip44:966'],
};
const getScope = nock(MOCK_ASSETS_WATCHLIST_URL)
.get('')
.reply(200, MOCK_ASSETS_WATCHLIST_BLOB)
.put('')
.reply(200)
.get('')
.reply(200, updatedBlob);
const { service } = createService();
const first = await service.getAssetsWatchlist();
await service.setAssetsWatchlist(updatedBlob);
const second = await service.getAssetsWatchlist();
expect(getScope.isDone()).toBe(true);
expect(first).toStrictEqual(MOCK_ASSETS_WATCHLIST_BLOB);
expect(second).toStrictEqual(updatedBlob);
});
});
describe('authorization', () => {
it('passes the access token as a Bearer header', async () => {
handleMockListDelegations();
const { service, mockGetBearerToken } = createService();
await service.listDelegations();
expect(mockGetBearerToken).toHaveBeenCalledTimes(1);
});
});
});
// === Test helpers ===
type RootMessenger = Messenger<
MockAnyNamespace,
MessengerActions<AuthenticatedUserStorageMessenger>,
MessengerEvents<AuthenticatedUserStorageMessenger>
>;
function createRootMessenger(): RootMessenger {
return new Messenger({ namespace: MOCK_ANY_NAMESPACE });
}
function createServiceMessenger(
rootMessenger: RootMessenger,
): AuthenticatedUserStorageMessenger {
return new Messenger({
namespace: 'AuthenticatedUserStorageService',
parent: rootMessenger,
});
}
function createService({
options = {},
}: {
options?: Partial<
ConstructorParameters<typeof AuthenticatedUserStorageService>[0]
>;
} = {}): {
service: AuthenticatedUserStorageService;
rootMessenger: RootMessenger;
messenger: AuthenticatedUserStorageMessenger;
mockGetBearerToken: jest.Mock;
} {
const rootMessenger = createRootMessenger();
const mockGetBearerToken = jest.fn().mockResolvedValue(MOCK_ACCESS_TOKEN);
rootMessenger.registerActionHandler(
'AuthenticationController:getBearerToken',
mockGetBearerToken,
);
const messenger = createServiceMessenger(rootMessenger);
rootMessenger.delegate({
messenger,
actions: ['AuthenticationController:getBearerToken'],
});
const service = new AuthenticatedUserStorageService({
messenger,
environment: 'prod',
...options,
});
return { service, rootMessenger, messenger, mockGetBearerToken };
}