-
Notifications
You must be signed in to change notification settings - Fork 7
/
cache-client.service.ts
712 lines (646 loc) · 20 KB
/
cache-client.service.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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { stringify } from 'qs';
import { IRoleDefinition } from '@energyweb/credential-governance';
import { IDIDDocument } from '@ew-did-registry/did-resolver-interface';
import {
Credential,
StatusList2021Entry,
VerifiableCredential,
} from '@ew-did-registry/credentials-interface';
import promiseRetry from 'promise-retry';
import setCookie from 'set-cookie-parser';
import { IApp, IOrganization, IRole } from '../domains/domains.types';
import { AssetHistory } from '../assets/assets.types';
import {
Claim,
IClaimIssuance,
IClaimRejection,
IClaimRequest,
} from '../claims/claims.types';
import { Asset } from '../assets/assets.types';
import {
executionEnvironment,
ExecutionEnvironment,
} from '../../utils/detect-environment';
import { SignerService } from '../signer/signer.service';
import { IPubKeyAndIdentityToken } from '../signer/signer.types';
import { cacheConfigs } from '../../config/cache.config';
import { ICacheClient } from './cache-client.interface';
import {
AssetsFilter,
AuthTokens,
ClaimsFilter,
TEST_LOGIN_ENDPOINT,
} from './cache-client.types';
import { SearchType } from '.';
import { getLogger } from '../../config/logger.config';
import {
RoleCredentialSubject,
StatusList2021Credential,
StatusList2021UnsignedCredential,
} from '../verifiable-credentials';
export class CacheClient implements ICacheClient {
public pubKeyAndIdentityToken: IPubKeyAndIdentityToken | undefined;
private _httpClient: AxiosInstance;
private authenticatePromise: Promise<void>;
private isAuthenticating = false;
private authEnabled: boolean;
private isBrowser: boolean;
private refresh_token: string | undefined;
constructor(private _signerService: SignerService) {
this._signerService.onInit(this.init.bind(this));
}
async init() {
const { url, cacheServerSupportsAuth = false } =
cacheConfigs()[this._signerService.chainId];
this._httpClient = axios.create({
baseURL: url,
withCredentials: true,
});
this.authEnabled = cacheServerSupportsAuth;
this.isBrowser = executionEnvironment() === ExecutionEnvironment.BROWSER;
}
isAuthEnabled() {
return this.authEnabled;
}
/**
* @description Refreshes access token. If login still fails then signs new identity token and requests access token
* After authentication runs previously failed requests
*/
async authenticate() {
// First try to refresh access token
try {
await this.refreshToken();
} catch {
getLogger().warn('[CACHE CLIENT] failed to refresh tokens');
}
// If refresh token failed or access token is not valid, then sign new identity token
if (!(await this.isAuthenticated())) {
getLogger().info('[CACHE CLIENT] obtaining new tokens');
delete this._httpClient.defaults.headers.common['Authorization'];
const pubKeyAndIdentityToken =
await this._signerService.publicKeyAndIdentityToken(true);
const res = await this._httpClient.post<AuthTokens>('/login', {
identityToken: pubKeyAndIdentityToken.identityToken,
});
if (!this.isBrowser) {
this.setTokens(res);
}
this.pubKeyAndIdentityToken = pubKeyAndIdentityToken;
}
getLogger().info('[CACHE CLIENT] authenticated');
}
/**
* Verifies current session and establishes new one if needed
* https://energyweb.atlassian.net/wiki/spaces/MYEN/pages/2303295607/ICL-+ICS+Auth+Process
*/
async login() {
if (!(await this.isAuthenticated())) {
await this.authenticate();
}
}
get http() {
return this._httpClient;
}
async getRoleDefinition(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole>(`/role/${namespace}`);
return data?.definition;
});
}
async getRolesDefinition(namespaces: string[]) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole[]>(
`/role?namespaces=${namespaces.join(',')}`
);
const rolesWithDefinitions = data?.map((entry) => ({
definition: entry.definition,
role: entry.namespace,
}));
return rolesWithDefinitions.reduce((result, { role, definition }) => {
return { ...result, [role]: definition };
}, {} as Record<string, IRoleDefinition>);
});
}
async getOrgDefinition(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IOrganization>(
`/org/${namespace}`
);
return data?.definition;
});
}
async getAppDefinition(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IApp>(`/app/${namespace}`);
return data?.definition;
});
}
async getApplicationRoles(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole[]>(
`/app/${namespace}/roles`
);
return data;
});
}
async getOrganizationRoles(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole[]>(
`/org/${namespace}/roles`
);
return data;
});
}
async getOrganizationsByOwner(owner: string, withRelations = true) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IOrganization[]>(
`/org/owner/${owner}?withRelations=${withRelations}`
);
return data;
});
}
async getSubOrganizationsByOrganization(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IOrganization[]>(
`/org/${namespace}/suborgs`
);
return data;
});
}
async getOrgHierarchy(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IOrganization>(
`/org/${namespace}`
);
return data;
});
}
async getNamespaceBySearchPhrase(search: string, types?: SearchType[]) {
return await this.makeRetryRequest(async () => {
if (types && types.length > 0) {
const { data } = await this._httpClient.get<
(IOrganization | IApp | IRole)[]
>(`/search/${search}`, {
params: {
types,
},
paramsSerializer: (params) => {
return stringify(params, { arrayFormat: 'brackets' });
},
});
return data;
}
const { data } = await this._httpClient.get<
(IOrganization | IApp | IRole)[]
>(`/search/${search}`);
return data;
});
}
async getApplicationsByOwner(owner: string, withRelations = true) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IApp[]>(
`/app/owner/${owner}?withRelations=${withRelations}`
);
return data;
});
}
async getApplicationsByOrganization(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IApp[]>(
`/org/${namespace}/apps`
);
return data;
});
}
async getRolesByOwner(owner: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole[]>(
`/role/owner/${owner}`
);
return data;
});
}
async getClaimsBySubjects(subjects: string[]): Promise<Claim[]> {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Claim[]>(
'/claim/by/subjects',
{
params: { subjects: subjects.join(',') },
}
);
return data;
});
}
async getClaimsByIssuer(
issuer: string,
{ isAccepted, namespace }: ClaimsFilter = {}
) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Claim[]>(
`/claim/issuer/${issuer}`,
{
params: {
isAccepted,
namespace,
},
}
);
return data;
});
}
async getClaimsByRequester(
requester: string,
{ isAccepted, namespace }: ClaimsFilter = {}
) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Claim[]>(
`/claim/requester/${requester}`,
{
params: {
isAccepted,
namespace,
},
}
);
return data;
});
}
async getClaimsBySubject(
subject: string,
{ isAccepted, namespace }: ClaimsFilter = {}
) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Claim[]>(
`/claim/subject/${subject}`,
{
params: {
isAccepted,
namespace,
},
}
);
return data;
});
}
async getRolesByRevoker(revoker: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole[]>(
`/claim/revoker/roles/allowed/${revoker}`
);
return data;
});
}
async getClaimsByRevoker(revoker: string, { namespace }: ClaimsFilter = {}) {
const { data } = await this._httpClient.get<Claim[]>(
`/claim/revoker/${revoker}`,
{
params: {
namespace,
},
}
);
return data;
}
async getClaimById(claimId: string): Promise<Claim | undefined> {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Claim | undefined>(
`/claim/${claimId}`
);
return data;
});
}
async requestClaim(message: IClaimRequest) {
return await this.makeRetryRequest(async () => {
await this._httpClient.post<void>('/claim/request', message);
});
}
async issueClaim(issuer: string, message: IClaimIssuance) {
return await this.makeRetryRequest(async () => {
await this._httpClient.post<void>(`/claim/issue/${issuer}`, message);
});
}
async rejectClaim(issuer: string, message: IClaimRejection) {
return await this.makeRetryRequest(async () => {
await this._httpClient.post<void>(`/claim/reject/${issuer}`, message);
});
}
async deleteClaim(id: string) {
return await this.makeRetryRequest(async () => {
await this._httpClient.delete<void>(`/claim/${id}`);
});
}
async getDIDsForRole(namespace: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<string[]>(
`/claim/did/${namespace}?accepted=true`
);
return data;
});
}
async getDidDocument(did: string, includeClaims?: boolean) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IDIDDocument>(
`/DID/${did}?includeClaims=${includeClaims || false}`
);
return data;
});
}
async getAllowedRolesByIssuer(did: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<IRole[]>(
`/claim/issuer/roles/allowed/${did}`
);
return data;
});
}
async addDIDToWatchList(did: string) {
return await this.makeRetryRequest(async () => {
await this._httpClient.post(`/DID/${did}`);
});
}
async getOwnedAssets(did: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Asset[]>(
`/assets/owner/${did}`
);
return data;
});
}
async getOfferedAssets(did: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Asset[]>(
`/assets/offered_to/${did}`
);
return data;
});
}
async getAssetById(id: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Asset>(`/assets/${id}`);
return data;
});
}
async getPreviouslyOwnedAssets(owner: string) {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.get<Asset[]>(
`/assets/owner/history/${owner}`
);
return data;
});
}
async getAssetHistory(
id: string,
{ order, take, skip, type }: AssetsFilter = {}
) {
return await this.makeRetryRequest(async () => {
const query = stringify({ order, take, skip, type }, { skipNulls: true });
const { data } = await this._httpClient.get<AssetHistory[]>(
`/assets/history/${id}?${query}`
);
return data;
});
}
/**
* Sets location of the credential status
*
* @param credential unsigned credential
* @return credential with reference to status location
*/
async addStatusToCredential(
credential: Credential<RoleCredentialSubject>
): Promise<
Credential<RoleCredentialSubject> & {
credentialStatus: StatusList2021Entry;
}
> {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.post<
Credential<RoleCredentialSubject> & {
credentialStatus: StatusList2021Entry;
}
>('/status-list/entries', { options: {}, credential });
return data;
});
}
/**
* Get the StatusList2021Credential object to be signed
*
* @param verifiableCredential verifiable credential to be revoked
* @return unsigned status list credential
*/
async initiateCredentialStatusUpdate(
verifiableCredential: VerifiableCredential<RoleCredentialSubject>
): Promise<StatusList2021UnsignedCredential> {
return await this.makeRetryRequest(async () => {
const { data } =
await this._httpClient.post<StatusList2021UnsignedCredential>(
'/status-list/credentials/status/initiate',
{
options: {},
verifiableCredential,
}
);
return data;
});
}
/**
* Persist signed StatusList2021Credential object in storage.
*
* @param statusListCredential signed status list
* @return status list credential
*/
async persistCredentialStatusUpdate(
statusListCredential: StatusList2021Credential
): Promise<StatusList2021Credential> {
return await this.makeRetryRequest(async () => {
const { data } = await this._httpClient.post<StatusList2021Credential>(
'/status-list/credentials/status/finalize',
{
options: {},
statusListCredential,
}
);
return data;
});
}
/**
* Fetch the StatusList2021Credential object from storage.
*
* @param credential verifiable credential with status list 2021
* @return status list credential if found
*/
async getStatusListCredential(
credential: VerifiableCredential<RoleCredentialSubject>
): Promise<StatusList2021Credential | null> {
return await this.makeRetryRequest(async () => {
if (!credential.credentialStatus?.statusListCredential) {
throw new Error(
'Missing statusListCredential property in given credential status'
);
}
const response = await axios.get<StatusList2021Credential | null>(
credential.credentialStatus?.statusListCredential
);
return response.status === 200 ? response.data : null;
});
}
/**
* Checks that auth token has been created, has not expired and corresponds to signer.
* This is done by a request to the server because the auth token is stored in an HTTP-only cookie and
* so the Javascript has no way to check its validity
*
* @return true if cache client is authenticated server
*/
async isAuthenticated(): Promise<boolean> {
getLogger().info('[CACHE CLIENT] fetching authorization status');
try {
const { data } = await this._httpClient.get<{
user: string | null;
}>(`${TEST_LOGIN_ENDPOINT}`);
const isAuthenticated = data.user
? data.user === this._signerService.did
: false;
getLogger().info(
`[CACHE CLIENT] authorization status: ${
isAuthenticated ? 'OK' : 'FAIL'
}`
);
return isAuthenticated;
} catch (error) {
getLogger().info('[CACHE CLIENT] authorization status: FAIL');
if (error instanceof Error) {
getLogger().error(
`[CACHE CLIENT] error occurred while checking authorization status: ${error.message}`
);
}
return false;
}
}
/**
* Decides whether to retry the request or not based on the given axios error.
*
* @param error axios error
*
* @return true if request should be retried
*/
private async handleRequestError(error: Error): Promise<boolean> {
if (!axios.isAxiosError(error)) {
return false;
}
const errorDetails = {
message: error.message,
url: error.config.url,
method: error.config.method,
requestHeaders: {
...error.config.headers,
Authorization: error.config.headers?.Authorization ? '***' : undefined,
},
status: error.response?.status,
statusText: error.response?.statusText,
responseHeaders: error.response?.headers,
};
getLogger().debug(
`[CACHE CLIENT] axios error: ${JSON.stringify(errorDetails)}`
);
const { config, response } = error;
if (!response) {
// ECONNREFUSED error handling,
return true;
}
// Retry server errors
if (response.status >= 500) {
return true;
}
const clientErrorsToRetry = [401, 403, 407, 408, 411, 412, 425, 426];
const isAuthEndpoint =
config.url &&
(config.url.indexOf('/login') >= 0 ||
config.url.indexOf('/refresh_token') >= 0 ||
config.url.indexOf(TEST_LOGIN_ENDPOINT) >= 0);
if (isAuthEndpoint) {
return false;
}
// Retry some client errors
if (
response.status >= 400 &&
!clientErrorsToRetry.includes(response.status)
) {
return false;
}
const isAuthError = [401, 403, 407].includes(response.status);
if (!isAuthError) {
return true;
}
getLogger().debug(`[CACHE CLIENT] axios error unauthorized`);
if (!this.isAuthenticating) {
this.isAuthenticating = true;
this.authenticatePromise = this.authenticate();
}
try {
await this.authenticatePromise;
} finally {
this.isAuthenticating = false;
}
return true;
}
private async makeRetryRequest<T>(request: () => Promise<T>): Promise<T> {
return promiseRetry(
async (retry) => {
return request().catch(async (err) => {
try {
if (await this.handleRequestError(err)) {
retry(err);
}
} catch {
retry(err);
}
throw err;
});
},
{ retries: 5 }
);
}
private async refreshToken(): Promise<void> {
if (!this.isBrowser && !this.refresh_token) return undefined;
getLogger().info('[CACHE CLIENT] refreshing tokens');
const res = await this._httpClient.get<AuthTokens>(
`/refresh_token${
this.isBrowser ? '' : `?refresh_token=${this.refresh_token}`
}`
);
getLogger().debug('[CACHE CLIENT] refreshed tokens fetched');
if (!this.isBrowser) {
this.setTokens(res);
}
}
/**
* Saves access and refresh tokens
*
* @param res Response from login request
*/
private setTokens({ headers, data }: AxiosResponse) {
let token: AuthTokens['token'] | undefined;
let refreshToken: AuthTokens['refreshToken'] | undefined;
if (headers['set-cookie']) {
const cookies = setCookie.parse(headers['set-cookie'], {
decodeValues: false,
map: true,
});
const tokenCookie = cookies['token'];
const refreshTokenCookie = cookies['refreshToken'];
if (tokenCookie && refreshTokenCookie) {
token = tokenCookie.value;
refreshToken = refreshTokenCookie.value;
}
}
if (!token || !refreshToken) {
token = data.token;
refreshToken = data.refreshToken;
}
this.refresh_token = refreshToken;
this._httpClient.defaults.headers.common[
'Authorization'
] = `Bearer ${token}`;
}
}