This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instances.js
630 lines (577 loc) · 21.1 KB
/
instances.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
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
/*!
* Copyright (c) 2019-2020 Digital Bazaar, Inc. All rights reserved.
*/
import {EdvDocument} from 'edv-client';
import {decodeList, getCredentialStatus} from 'vc-revocation-list';
import vc from '@digitalbazaar/vc';
import {AsymmetricKey} from '@digitalbazaar/webkms-client';
import {InstanceService} from './InstanceService.js';
import {Ed25519Signature2018} from '@digitalbazaar/ed25519-signature-2018';
// TODO: need a common place for this
const JWE_ALG = 'ECDH-ES+A256KW';
export async function create(
{profileManager, profileContent, profileAgentContent}) {
// create the instance as a profile
const {id: profileId} = await profileManager.createProfile();
let instance = {id: profileId};
// request capabilities for the instance, including for the `user` EDV
const presentation = await requestCapabilities({instance});
if(!presentation) {
throw new Error('User aborted instance provisioning.');
}
// TODO: validate presentation (ensure it matches request and has the
// zcaps with the appropriate reference IDs, etc.)
// TODO: verify presentation via backend call
// get zcaps from presentation based on reference ID
const {capability: capabilities} = presentation;
const capability = _findZcap(
{capabilities, referenceId: 'user-edv-documents'});
const revocationCapability = _findZcap(
{capabilities, referenceId: 'user-edv-revocations'});
profileContent = {edvs: {}, ...profileContent};
const profileZcaps = {...profileContent.zcaps};
for(const zcap of capabilities) {
profileZcaps[zcap.referenceId] = zcap;
}
profileContent.issuer = presentation.holder;
profileContent.zcaps = profileZcaps;
// create keys for accessing `user` EDV
const {hmac, keyAgreementKey} = await profileManager.createEdvRecipientKeys(
{profileId});
// initialize access management
const {profile, profileAgent} = await profileManager
.initializeAccessManagement({
profileId,
profileContent,
profileAgentContent,
hmac,
keyAgreementKey,
capability,
revocationCapability,
indexes: [
{attribute: 'content.name'},
{attribute: 'content.email'}
]
});
instance = profile;
let user = profileAgent;
const accessManager = await profileManager.getAccessManager({profileId});
const {invocationSigner} = await profileManager.getProfileSigner(
{profileId});
// TODO: these zcaps for full access to these EDVs by the profileAgent
// should really only be created on demand -- where the function call to
// get them (+lazy delegation) requires an optional param that is the
// profileAgent's powerful zcap to use the profile's zcap key
// get zcaps for each EDV and the profile's keys (hmac/KAK) as a recipient
const edvs = ['credential'];
for(const edv of edvs) {
// get zcaps from presentation based on reference ID
const edvZcapId = `${edv}-edv-documents`;
const revokeZcapId = `${edv}-edv-revocations`;
const {capability: capabilities} = presentation;
const parentCapabilities = {
edv: _findZcap({capabilities, referenceId: edvZcapId}),
edvRevocations: _findZcap({capabilities, referenceId: revokeZcapId})
};
// create keys for accessing user and credential EDVs
const {hmac, keyAgreementKey} = await profileManager.createEdvRecipientKeys(
{profileId});
// TODO: there should be an API in profile manager that can be used
// to generate this information -- and the `accessManagement` part of
// a profile user doc should be removed and moved to `edvs` just like
// any other edv, its name `user` would be understood to be special
profile.edvs[edv] = {
hmac: {id: hmac.id, type: hmac.type},
keyAgreementKey: {id: keyAgreementKey.id, type: keyAgreementKey.type},
indexes: [
{attribute: 'content.id', unique: true},
{attribute: 'content.type'}
],
zcaps: {
write: edvZcapId,
revoke: revokeZcapId
}
};
await accessManager.updateUser({user: profile});
// delegate zcaps to enable profile agent to access EDV
const {zcaps} = await profileManager.delegateEdvCapabilities({
hmac,
keyAgreementKey,
parentCapabilities,
invocationSigner,
profileAgentId: profileAgent.id,
referenceIdPrefix: edv
});
// capablities to enable the profile agent to use the profile's user EDV
for(const capability of zcaps) {
user.zcaps[capability.referenceId] = capability;
}
}
// set default "capabilities" for user
// TODO: do this here or elsewhere?
user.capabilities = ['Admin', 'Read', 'Revoke', 'Issue'];
// update profile agent user with content and new zcaps
user = await accessManager.updateUser({user});
return {user, instance};
}
export async function delegateCapabilities({profileManager, instance, user}) {
user = {...user};
const {zcaps} = await _createZcapDelegations(
{profileManager, instance, user});
for(const capability of zcaps) {
user.zcaps[capability.referenceId] = capability;
}
return user;
}
export async function revokeCapabilities(
{profileManager, instance, user, capabilitiesToRevoke}) {
user = {...user};
const revokedZcaps = await _revokeZcaps(
{profileManager, instance, user, capabilitiesToRevoke});
for(const capability of revokedZcaps) {
delete user.zcaps[capability.referenceId];
}
return user;
}
export async function requestCapabilities({instance}) {
console.log('request credential issuance capabilities...');
try {
const webCredential = await navigator.credentials.get({
web: {
VerifiablePresentation: {
query: {
// TODO: need to add a mechanism to this query language to
// indicate whether an existing or new EDVs/keys should be
// created before being given these zcaps ... perhaps a
// layer where "provision X+give me a zcap for it" query is needed
type: 'OcapLdQuery',
capabilityQuery: [{
referenceId: 'user-edv-documents',
revocationReferenceId: 'user-edv-revocations',
allowedAction: ['read', 'write'],
invoker: instance.id,
delegator: instance.id,
invocationTarget: {
type: 'urn:edv:documents'
}
}, {
referenceId: `credential-edv-documents`,
revocationReferenceId: `credential-edv-revocations`,
allowedAction: ['read', 'write'],
invoker: instance.id,
delegator: instance.id,
invocationTarget: {
type: 'urn:edv:documents'
}
}, {
referenceId: `key-assertionMethod`,
revocationReferenceId: `key-assertionMethod-revocations`,
// string should match KMS ops
allowedAction: 'sign',
invoker: instance.id,
delegator: instance.id,
invocationTarget: {
type: 'Ed25519VerificationKey2018',
proofPurpose: 'assertionMethod'
}
}]
}
}
}
});
if(!webCredential) {
// no response from user
console.log('credential request canceled/denied');
return null;
}
// destructure to get presentation
const {data: presentation} = webCredential;
console.log('presentation', presentation);
return presentation;
} catch(e) {
console.error(e);
}
}
export async function revokeCredential(
{profileManager, instance, credentialId, documentLoader}) {
if(!(credentialId && typeof credentialId === 'string')) {
throw new TypeError('"credentialId" must be a non-empty string.');
}
// get interfaces for issuing/revoking VCs
const {profileAgent, suite, credentialsCollection} =
await _getIssuingInterfaces({profileManager, instance});
const {edvClient, capability, invocationSigner} = credentialsCollection;
// get credential document
const {documents: credentialDocuments} = await edvClient.find({
equals: {'content.id': credentialId},
capability,
invocationSigner
});
if(credentialDocuments.length === 0) {
throw new Error(`Credential "${credentialId}" not found.`);
}
let [credentialDoc] = credentialDocuments;
const {content: credential} = credentialDoc;
const credentialEdvDoc = await _getEdvDocument(
{id: credentialDoc.id, edvClient, capability, invocationSigner});
// TODO: support other revocation methods
// get RLC document
const credentialStatus = getCredentialStatus({credential});
const revocationListIndex = parseInt(
credentialStatus.revocationListIndex, 10);
const {revocationListCredential} = credentialStatus;
const {documents: rlcDocuments} = await edvClient.find({
equals: {'content.id': revocationListCredential},
capability,
invocationSigner
});
if(rlcDocuments.length === 0) {
throw new Error(
`RevocationListCredential "${revocationListCredential}" not found.`);
}
// FIXME: add timeout
let [rlcDoc] = rlcDocuments;
let rlcId;
const rlcEdvDoc = await _getEdvDocument(
{id: rlcDoc.id, edvClient, capability, invocationSigner});
let rlcUpdated = false;
while(!rlcUpdated) {
try {
// check if `credential` is already revoked, if so, done
const rlcCredential = rlcDoc.content;
const {credentialSubject: {encodedList}} = rlcCredential;
rlcId = rlcCredential.id;
const list = await decodeList({encodedList});
if(list.isRevoked(revocationListIndex)) {
rlcUpdated = true;
break;
}
// update index as revoked and reissue VC
list.setRevoked(revocationListIndex, true);
rlcCredential.credentialSubject.encodedList = await list.encode();
// express date without milliseconds
const now = (new Date()).toJSON();
rlcCredential.issuanceDate = `${now.substr(0, now.length - 5)}Z`;
// TODO: we want to be using `issued`, right?
//rlcCredential.issued = issuanceDate;
// clear existing proof and resign VC
delete rlcCredential.proof;
rlcDoc.content = await vc.issue(
{credential: rlcCredential, documentLoader, suite});
// update RLC doc
await rlcEdvDoc.write({doc: rlcDoc});
rlcUpdated = true;
} catch(e) {
if(e.name !== 'InvalidStateError') {
throw e;
}
// ignore conflict, read and try again
rlcDoc = await rlcEdvDoc.read();
}
}
// publish latest version of RLC for non-authz consumption
const instanceService = new InstanceService();
await instanceService.publishRlc({id: rlcId, profileAgent: profileAgent.id});
// mark credential as revoked in its meta
// FIXME: add timeout
let credentialUpdated = credentialDoc.meta.revoked;
while(!credentialUpdated) {
try {
credentialDoc.meta.revoked = true;
await credentialEdvDoc.write({doc: credentialDoc});
credentialUpdated = true;
} catch(e) {
if(e.name !== 'InvalidStateError') {
throw e;
}
// ignore conflict, read and try again
credentialDoc = await credentialEdvDoc.read();
credentialUpdated = credentialDoc.meta.revoked;
}
}
}
async function _getIssuingInterfaces({profileManager, instance}) {
const {id: profileId} = instance;
const profileAgent = await profileManager.getAgent({profileId});
const {zcaps: {
['key-assertionMethod']: assertionMethodZcap,
['credential-edv-documents']: credentialsEdvZcap,
['credential-edv-hmac']: credentialsEdvHmacZcap,
['credential-edv-kak']: credentialsEdvKakZcap,
}} = profileAgent;
if(!(assertionMethodZcap && credentialsEdvZcap && credentialsEdvHmacZcap &&
credentialsEdvKakZcap)) {
throw new Error('Permission denied.');
}
const {edvClient, capability, invocationSigner} =
await profileManager.getProfileEdvAccess(
{profileId, referenceIdPrefix: 'credential'});
const issuerKey = new AsymmetricKey({
capability: assertionMethodZcap,
invocationSigner
});
const suite = new Ed25519Signature2018({
signer: issuerKey
});
edvClient.ensureIndex({attribute: 'content.id', unique: true});
edvClient.ensureIndex({attribute: 'content.type'});
edvClient.ensureIndex({attribute: 'meta.revoked'});
return {
profileAgent,
suite,
// TODO: expose latter as a `Collection` instance
credentialsCollection: {edvClient, capability, invocationSigner}
};
}
async function _getEdvDocument(
{id, edvClient, capability, invocationSigner} = {}) {
const {keyResolver, keyAgreementKey, hmac} = edvClient;
const recipients = [{
header: {kid: keyAgreementKey.id, alg: JWE_ALG}
}];
return new EdvDocument({
id, recipients, keyResolver, keyAgreementKey, hmac,
capability, invocationSigner, client: edvClient
});
}
async function _createZcapDelegations({profileManager, instance, user}) {
const {capabilities} = user;
const controller = user.id;
const zcapRequests = [];
// TODO: fix data model for these: ["Read", "Issue", "Revoke", "Admin"]
// map what are essentially roles to the appropriate capabilities
if(capabilities.includes('Admin')) {
const profileInvocationZcapKeyRequest =
await _createProfileInvocationZcapKeyRequest(
{controller, profileManager, instanceId: instance.id});
const userEdvRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['user-edv-documents'],
allowedAction: ['read', 'write']
});
const userEdvHmacRequest = await _createZcapRequestFromKey({
key: instance.accessManagement.hmac,
referenceId: 'user-edv-hmac',
controller,
allowedAction: 'sign'
});
const userEdvKakRequest = await _createZcapRequestFromKey({
key: instance.accessManagement.keyAgreementKey,
referenceId: 'user-edv-kak',
controller,
allowedAction: ['deriveSecret', 'sign']
});
const userEdvRevocationsRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['user-edv-revocations'],
allowedAction: ['read', 'write']
});
const credentialEdvRevocationsRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['credential-edv-revocations'],
allowedAction: ['read', 'write']
});
const issuanceRevocationsRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['key-assertionMethod-revocations'],
allowedAction: ['read', 'write']
});
const adminZcapRequests = [
profileInvocationZcapKeyRequest,
userEdvRequest,
userEdvHmacRequest,
userEdvKakRequest,
userEdvRevocationsRequest,
credentialEdvRevocationsRequest,
issuanceRevocationsRequest
];
zcapRequests.push(...adminZcapRequests);
}
if(capabilities.includes('Issue')) {
const issuanceRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['key-assertionMethod'],
allowedAction: 'sign'
});
const credentialEdvRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['credential-edv-documents'],
allowedAction: ['read', 'write']
});
const credentialEdvHmacRequest = await _createZcapRequestFromKey({
key: instance.edvs.credential.hmac,
referenceId: 'credential-edv-hmac',
controller,
allowedAction: 'sign'
});
const credentialEdvKakRequest = await _createZcapRequestFromKey({
key: instance.edvs.credential.keyAgreementKey,
referenceId: 'credential-edv-kak',
controller,
allowedAction: ['deriveSecret', 'sign']
});
const issuanceZcapRequests = [
issuanceRequest,
credentialEdvRequest,
credentialEdvHmacRequest,
credentialEdvKakRequest
];
zcapRequests.push(...issuanceZcapRequests);
} else if(capabilities.includes('Revoke')) {
const credentialEdvRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['credential-edv-documents'],
allowedAction: ['read', 'write']
});
const credentialEdvHmacRequest = await _createZcapRequestFromKey({
key: instance.edvs.credential.hmac,
referenceId: 'credential-edv-hmac',
controller,
allowedAction: 'sign'
});
const credentialEdvKakRequest = await _createZcapRequestFromKey({
key: instance.edvs.credential.keyAgreementKey,
referenceId: 'credential-edv-kak',
controller,
allowedAction: ['deriveSecret', 'sign']
});
const revokeZcapRequests = [
credentialEdvRequest,
credentialEdvHmacRequest,
credentialEdvKakRequest
];
zcapRequests.push(...revokeZcapRequests);
} else if(capabilities.includes('Read')) {
const credentialEdvRequest = await _createZcapRequestFromParent({
controller,
parentZcap: instance.zcaps['credential-edv-documents'],
allowedAction: 'read'
});
const credentialEdvHmacRequest = await _createZcapRequestFromKey({
key: instance.edvs.credential.hmac,
referenceId: 'credential-edv-hmac',
controller,
allowedAction: 'sign'
});
const credentialEdvKakRequest = await _createZcapRequestFromKey({
key: instance.edvs.credential.keyAgreementKey,
referenceId: 'credential-edv-kak',
controller,
allowedAction: ['deriveSecret', 'sign']
});
const readZcapRequests = [
credentialEdvRequest,
credentialEdvHmacRequest,
credentialEdvKakRequest
];
zcapRequests.push(...readZcapRequests);
}
const promises = zcapRequests.map(async request =>
profileManager.delegateCapability({profileId: instance.id, request}));
// TODO: Use promise-fun lib to limit concurrency
const zcaps = await Promise.all(promises);
return {zcaps};
}
async function _revokeZcaps(
{profileManager, instance, capabilitiesToRevoke, user}) {
const zcapsToRevoke = [];
// map what are essentially roles to the appropriate capabilities
if(capabilitiesToRevoke.includes('Admin')) {
// FIXME: Remove this after profile zcap key is renamed
const adminAgent = await profileManager.getAgent({profileId: instance.id});
const {zcaps} = adminAgent;
const zcapReferenceId = await _getProfileInvocationZcapKeyReferenceId(
{instanceId: instance.id, zcaps});
const adminZcaps = [
user.zcaps[zcapReferenceId],
user.zcaps['user-edv-documents'],
user.zcaps['user-edv-hmac'],
user.zcaps['user-edv-kak'],
user.zcaps['user-edv-revocations'],
user.zcaps['credential-edv-revocations'],
user.zcaps['key-assertionMethod-revocations']
];
zcapsToRevoke.push(...adminZcaps);
}
if(capabilitiesToRevoke.includes('Issue')) {
const issueZcaps = [
user.zcaps['key-assertionMethod'],
user.zcaps['credential-edv-documents'],
user.zcaps['credential-edv-hmac'],
user.zcaps['credential-edv-kak']
];
zcapsToRevoke.push(...issueZcaps);
} else if(capabilitiesToRevoke.includes('Revoke') ||
capabilitiesToRevoke.includes('Read')) {
const zcaps = [
user.zcaps['credential-edv-documents'],
user.zcaps['credential-edv-hmac'],
user.zcaps['credential-edv-kak']
];
zcapsToRevoke.push(...zcaps);
}
const {invocationSigner: signer} = await profileManager.getProfileSigner(
{profileId: instance.id});
const promises = zcapsToRevoke.map(async zcap => _revokeZcap({signer, zcap}));
// TODO: Use promise-fun lib to limit concurrency
await Promise.all(promises);
return zcapsToRevoke;
}
// eslint-disable-next-line no-unused-vars
async function _revokeZcap({signer, zcap}) {
// FIXME: Implement revocation of zcaps
return true;
}
// FIXME: this assumes the `profileManager` is an Admin
async function _createProfileInvocationZcapKeyRequest(
{controller, profileManager, instanceId}) {
const adminAgent = await profileManager.getAgent({profileId: instanceId});
const {zcaps} = adminAgent;
const zcapReferenceId = await _getProfileInvocationZcapKeyReferenceId(
{instanceId, zcaps});
const {invocationTarget, allowedAction, referenceId} = zcaps[zcapReferenceId];
return {
allowedAction,
controller,
invocationTarget,
referenceId
};
}
async function _getProfileInvocationZcapKeyReferenceId(
{instanceId, zcaps}) {
// FIXME: simplify reference ID for this; force only one reference ID
// for using the agent's profile's capability invocation key using the
// literal reference ID: 'profile-capability-invocation-key'
return Object.keys(zcaps).find(referenceId => {
const capabilityInvokeKeyReference = '-key-capabilityInvocation';
return referenceId.startsWith(instanceId) &&
referenceId.endsWith(capabilityInvokeKeyReference);
});
}
async function _createZcapRequestFromParent(
{parentZcap, controller, allowedAction}) {
return {
allowedAction,
controller,
parentCapability: parentZcap,
invocationTarget: {...parentZcap.invocationTarget},
referenceId: parentZcap.referenceId,
};
}
async function _createZcapRequestFromKey(
{key, referenceId, controller, allowedAction}) {
return {
allowedAction,
controller,
referenceId,
invocationTarget: {
id: key.id,
type: key.type,
publicAlias: key.id
},
parentCapability: key.id
};
}
function _findZcap({capabilities, referenceId}) {
return capabilities.find(({referenceId: id}) => id === referenceId);
}