-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.nodeApiServer.spec.ts
479 lines (422 loc) · 14.7 KB
/
api.nodeApiServer.spec.ts
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
import {
afterAll,
beforeAll,
describe,
expect,
it,
} from '@windingtree/sdk-test-utils';
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { z } from 'zod';
import { createPublicClient, createWalletClient, Hash, http } from 'viem';
import { mnemonicToAccount } from 'viem/accounts';
import superjson from 'superjson';
import { generateMnemonic, supplierId as spId } from '@windingtree/sdk-utils';
import { UserInputType } from '@windingtree/sdk-db';
import {
authAdminProcedure,
authProcedure,
NodeApiServer,
NodeApiServerOptions,
router,
} from '../src/server.js';
import { adminRouter, dealsRouter, userRouter } from '../src/router/index.js';
import { memoryStorage } from '@windingtree/sdk-storage';
import {
ACCESS_TOKEN_NAME,
accessTokenLink,
createAdminSignature,
} from '../src/client.js';
import { HashSchema } from '../dist/router.js';
import { ProtocolContracts } from '@windingtree/sdk-contracts-manager';
import { contractsConfig } from 'wtmp-examples-shared-files';
import { hardhat, polygonZkEvmTestnet } from 'viem/chains';
import { PaginationOptions } from '@windingtree/sdk-types';
import { randomSalt } from '@windingtree/contracts';
import { serviceRouter } from '../src/router/service.js';
import { buildRandomDeal } from '@windingtree/sdk-messages';
const testRouter = router({
admin: adminRouter,
user: userRouter,
deals: dealsRouter,
service: serviceRouter,
testAuth: authProcedure.output(z.boolean()).mutation(() => {
return true;
}),
testAdminAuth: authAdminProcedure.output(z.boolean()).mutation(() => {
return true;
}),
});
const chain = process.env.LOCAL_NODE === 'true' ? hardhat : polygonZkEvmTestnet;
describe('NodeApiServer', () => {
const user: UserInputType = {
login: 'testUser',
password: 'password',
};
const owner = mnemonicToAccount(generateMnemonic());
let options: NodeApiServerOptions;
let server: NodeApiServer;
let clientUser: ReturnType<typeof createTRPCProxyClient<typeof testRouter>>;
let clientAdmin: ReturnType<typeof createTRPCProxyClient<typeof testRouter>>;
let accessTokenUser: string | undefined;
let accessTokenAdmin: string | undefined;
beforeAll(async () => {
const contractsManager = new ProtocolContracts({
contracts: contractsConfig,
publicClient: createPublicClient({
chain,
transport: http(),
}),
walletClient: createWalletClient({
chain,
transport: http(),
account: owner.address,
}),
});
options = {
storage: {
users: await memoryStorage.createInitializer({
scope: 'users',
})(),
deals: await memoryStorage.createInitializer({
scope: 'deals',
})(),
},
prefix: 'test',
port: 3456,
secret: 'secret',
ownerAccount: owner.address,
protocolContracts: contractsManager,
cors: ['*'],
};
server = new NodeApiServer(options);
server.start(testRouter);
clientUser = createTRPCProxyClient<typeof testRouter>({
transformer: superjson,
links: [
accessTokenLink(ACCESS_TOKEN_NAME, (token) => {
accessTokenUser = token;
}),
httpBatchLink({
url: `http://localhost:${options.port}`,
headers: () => ({
authorization: accessTokenUser ? `Bearer ${accessTokenUser}` : '',
}),
}),
],
});
clientAdmin = createTRPCProxyClient<typeof testRouter>({
transformer: superjson,
links: [
accessTokenLink(ACCESS_TOKEN_NAME, (token) => {
accessTokenAdmin = token;
}),
httpBatchLink({
url: `http://localhost:${options.port}`,
headers: () => ({
authorization: accessTokenAdmin ? `Bearer ${accessTokenAdmin}` : '',
}),
}),
],
});
});
afterAll(async () => {
await server.stop();
});
describe('user.register', () => {
let admin: UserInputType;
beforeAll(async () => {
admin = {
login: 'admin',
password: await createAdminSignature(owner),
};
await clientAdmin.admin.register.mutate(admin);
await clientAdmin.admin.login.mutate(admin);
});
afterAll(async () => {
await clientAdmin.user.delete.mutate();
});
it('should throw if accessed by a not an admin', async () => {
await expect(clientUser.user.register.mutate(user)).rejects.toThrow(
'UNAUTHORIZED',
);
});
it('should register a new user (by admin)', async () => {
const result = await clientAdmin.user.register.mutate(user);
expect(result).to.be.eq(undefined);
});
it('should throw an error when trying to register an existing user', async () => {
await expect(clientAdmin.user.register.mutate(user)).rejects.toThrow(
`User ${user.login} already exists`,
);
});
});
describe('user.login', () => {
it('should throw if accessed by non authenticated user', async () => {
await expect(clientUser.testAuth.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
it('should log in a registered user and return an access token', async () => {
const result = await clientUser.user.login.mutate(user);
expect(result).to.be.eq(undefined);
expect(accessTokenUser).toBeDefined();
});
it('should throw an error when trying to log in with incorrect password', async () => {
await expect(
clientUser.user.login.mutate({
...user,
password: 'invalid-password',
}),
).rejects.toThrow('Invalid login or password');
});
it('should access route using authorized client', async () => {
await expect(clientUser.testAuth.mutate()).resolves.toEqual(true);
});
it('should access route (admin only) using authorized client', async () => {
await expect(clientUser.testAdminAuth.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
});
describe('user.update', () => {
const newPassword = 'new-password';
it('should log in a registered user and return an access token', async () => {
const result = await clientUser.user.update.mutate({
...user,
password: newPassword,
});
expect(result).to.be.eq(undefined);
expect(accessTokenUser).toBeDefined();
});
it('should log in a registered user and return an access token', async () => {
const result = await clientUser.user.login.mutate({
...user,
password: newPassword,
});
expect(result).to.be.eq(undefined);
expect(accessTokenUser).toBeDefined();
});
});
describe('user.logout', () => {
it('should logout a logged in user', async () => {
const result = await clientUser.user.logout.mutate();
expect(result).to.be.eq(undefined);
expect(accessTokenUser).toBeDefined();
});
it('should throw an error when trying to access authenticated route', async () => {
await expect(clientUser.testAuth.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
});
describe('user.delete', () => {
let newUser: UserInputType;
let admin: UserInputType;
beforeAll(async () => {
newUser = {
...user,
login: 'new-user',
};
admin = {
login: 'admin',
password: await createAdminSignature(owner),
};
await clientAdmin.admin.register.mutate(admin);
await clientAdmin.admin.login.mutate(admin);
});
afterAll(async () => {
await clientAdmin.user.delete.mutate();
});
it('should throw if called by non authorized user', async () => {
await expect(clientUser.user.delete.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
it('should delete existed user', async () => {
await clientAdmin.user.register.mutate(newUser);
await clientUser.user.login.mutate(newUser);
const result = await clientUser.user.delete.mutate();
expect(result).to.be.eq(undefined);
accessTokenUser = undefined;
});
it('should throw on try to login with deleted user ', async () => {
await expect(clientUser.user.login.mutate(newUser)).rejects.toThrow(
'User new-user not found',
);
});
});
describe('Admin route', () => {
const name = 'admin;';
describe('admin.register', () => {
it('should register a new admin', async () => {
const signature = await createAdminSignature(owner);
const result = await clientAdmin.admin.register.mutate({
login: name,
password: signature,
});
expect(result).to.be.eq(undefined);
});
it('should throw an error when trying to register an existing admin', async () => {
const signature = await createAdminSignature(owner);
const user = {
login: name,
password: signature,
};
await expect(clientAdmin.admin.register.mutate(user)).rejects.toThrow(
`User ${user.login} already exists`,
);
});
});
describe('admin.login', () => {
beforeAll(async () => {
await clientAdmin.user.logout.mutate();
});
it('should throw if accessed by non authenticated admin', async () => {
await expect(clientAdmin.testAdminAuth.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
it('should log in an admin and return an access token', async () => {
const signature = await createAdminSignature(owner);
const user = {
login: name,
password: signature,
};
const result = await clientAdmin.admin.login.mutate(user);
expect(result).to.be.eq(undefined);
expect(accessTokenAdmin).toBeDefined();
});
it('should throw an error when trying to log in with incorrect signature', async () => {
const invalidOwner = mnemonicToAccount(generateMnemonic());
const signature = await createAdminSignature(invalidOwner);
const user = {
login: name,
password: signature,
};
await expect(clientAdmin.admin.login.mutate(user)).rejects.toThrow(
'Invalid signature',
);
});
it('should access route (normal) using authorized client', async () => {
await expect(clientAdmin.testAuth.mutate()).resolves.toEqual(true);
});
it('should access route (admin only) using authorized client', async () => {
await expect(clientAdmin.testAdminAuth.mutate()).resolves.toEqual(true);
});
});
describe('user.logout (by admin)', () => {
it('should logout a logged in admin', async () => {
const result = await clientAdmin.user.logout.mutate();
expect(result).to.be.eq(undefined);
expect(accessTokenAdmin).toBeDefined();
});
it('should throw an error when trying to access authenticated route (normal)', async () => {
await expect(clientAdmin.testAuth.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
it('should throw an error when trying to access authenticated route (admin only)', async () => {
await expect(clientAdmin.testAdminAuth.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
});
describe('user.delete (by admin)', () => {
let signature: Hash;
let newUser: UserInputType;
beforeAll(async () => {
signature = await createAdminSignature(owner);
newUser = {
login: `new-${name}`,
password: signature,
};
});
it('should throw if called by non authorized user', async () => {
await expect(clientAdmin.user.delete.mutate()).rejects.toThrow(
'UNAUTHORIZED',
);
});
it('should delete existed admin', async () => {
await clientAdmin.admin.register.mutate(newUser);
await clientAdmin.admin.login.mutate(newUser);
const result = await clientAdmin.user.delete.mutate();
expect(result).to.be.eq(undefined);
accessTokenAdmin = undefined;
});
it('should throw on try to login with deleted user ', async () => {
const signature = await createAdminSignature(owner);
const newUser = {
login: `new-${name}`,
password: signature,
};
await expect(clientAdmin.admin.login.mutate(newUser)).rejects.toThrow(
`User new-${name} not found`,
);
});
});
});
describe('Deal route', () => {
let admin: UserInputType;
let id: `0x${string}`;
let deal;
beforeAll(async () => {
admin = {
login: 'admin',
password: await createAdminSignature(owner),
};
await clientAdmin.admin.register.mutate(admin);
await clientAdmin.admin.login.mutate(admin);
const signer = mnemonicToAccount(generateMnemonic());
const supplierId = spId(signer.address, randomSalt());
deal = await buildRandomDeal(signer, supplierId);
id = deal.offer.id;
await server.deals?.set(deal);
});
afterAll(async () => {
await clientAdmin.user.delete.mutate();
});
it('should throw if accessed by a not an admin 1', () => {
expect(HashSchema).to.be.string;
});
it.skip('should throw if accessed by a not an admin 2', async () => {
const randomId = randomSalt();
expect(
(await clientAdmin.deals.seek.mutate({ id: randomId })).offer.id,
).toEqual(randomId);
expect(
(await clientAdmin.deals.get.query({ id: randomId })).offer.id,
).toEqual(randomId);
expect((await clientAdmin.service.ping.query()).message).toEqual('pong');
});
it('should throw if accessed by a not an admin 3', async () => {
const salt = randomSalt();
await expect(
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
clientAdmin.deals.get.query({ id: salt }),
).rejects.toThrow(`Deal ${salt} not found`);
});
it.skip('should throw if accessed by a not an admin 4', async () => {
expect((await clientAdmin.deals.seek.mutate({ id })).offer.id).toEqual(
id,
);
});
it('should throw if accessed by a not an admin 8', async () => {
const salt = randomSalt();
await expect(
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
clientAdmin.deals.get.query({ id: salt }),
).rejects.toThrow(`Deal ${salt} not found`);
});
it('should throw if accessed by a not an admin 9', async () => {
await clientAdmin.deals.getAll.query({});
});
it('should throw if accessed by a not an admin 10', async () => {
await expect(
clientAdmin.deals.getAll.query({
start: 'string',
skip: 10,
} as unknown as PaginationOptions),
).rejects.toThrow('Expected number, received string');
});
});
});