This repository has been archived by the owner on Apr 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
829 lines (679 loc) · 22.6 KB
/
client.go
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package vault
import (
"bytes"
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/google/uuid"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/orb"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/sidetree/doc"
ariescrypto "github.com/hyperledger/aries-framework-go/pkg/crypto"
"github.com/hyperledger/aries-framework-go/pkg/crypto/tinkcrypto"
webcrypto "github.com/hyperledger/aries-framework-go/pkg/crypto/webkms"
ariesdid "github.com/hyperledger/aries-framework-go/pkg/doc/did"
"github.com/hyperledger/aries-framework-go/pkg/doc/jose"
"github.com/hyperledger/aries-framework-go/pkg/doc/jose/jwk/jwksupport"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/jsonld"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/suite"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/suite/ed25519signature2018"
"github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr"
"github.com/hyperledger/aries-framework-go/pkg/kms"
"github.com/hyperledger/aries-framework-go/pkg/kms/webkms"
ariesvdr "github.com/hyperledger/aries-framework-go/pkg/vdr"
"github.com/hyperledger/aries-framework-go/pkg/vdr/fingerprint"
vdrkey "github.com/hyperledger/aries-framework-go/pkg/vdr/key"
"github.com/hyperledger/aries-framework-go/spi/storage"
"github.com/igor-pavlenko/httpsignatures-go"
"github.com/piprate/json-gold/ld"
"github.com/trustbloc/edge-core/pkg/zcapld"
edv "github.com/trustbloc/edv/pkg/client"
"github.com/trustbloc/edv/pkg/edvutils"
"github.com/trustbloc/edv/pkg/restapi/messages"
"github.com/trustbloc/edv/pkg/restapi/models"
"github.com/trustbloc/ace/pkg/doc/vc/crypto"
"github.com/trustbloc/ace/pkg/internal/zcapldutil"
)
const (
storeName = "vault"
authorizationFormat = "authorization_%s_%s"
metaDocInfoFormat = "meta_doc_info_%s_%s"
infoFormat = "info_%s"
)
// Vault defines vault client interface.
type Vault interface {
CreateVault() (*CreatedVault, error)
SaveDoc(vaultID, id string, content []byte) (*DocumentMetadata, error)
GetDocMetadata(vaultID, docID string) (*DocumentMetadata, error)
CreateAuthorization(vaultID, requestingParty string, scope *AuthorizationsScope) (*CreatedAuthorization, error)
GetAuthorization(vaultID, id string) (*CreatedAuthorization, error)
}
// KeyManager KMS alias.
type KeyManager kms.KeyManager
// HTTPClient interface for the http client.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// CreatedVault represents success response of CreateVault function.
type CreatedVault struct {
ID string `json:"id"`
*Authorization
}
// CreatedAuthorization represents success response of CreateAuthorization function.
type CreatedAuthorization struct {
ID string `json:"id"`
Scope *AuthorizationsScope `json:"scope"`
RequestingParty string `json:"requestingParty"`
Tokens *Tokens `json:"authTokens"`
}
// Tokens zcap tokens.
type Tokens struct {
EDV string `json:"edv"`
KMS string `json:"kms"`
}
// AuthorizationsScope represents authorization request.
type AuthorizationsScope struct {
Target string `json:"target,omitempty"`
TargetAttr string `json:"targetAttr,omitempty"`
Actions []string `json:"actions,omitempty"`
Caveats []Caveat `json:"caveats,omitempty"`
}
// Caveat for the AuthorizationsScope request.
type Caveat struct {
Type string `json:"type,omitempty"`
Duration uint64 `json:"duration,omitempty"`
}
// Authorization consists of info needed for the authorization.
type Authorization struct {
EDV *Location `json:"edv"`
KMS *Location `json:"kms"`
}
// Location consists of URI and zcap capability.
type Location struct {
URI string `json:"uri"`
AuthToken string `json:"authToken"`
}
// DocumentMetadata represents document`s metadata.
type DocumentMetadata struct {
ID string `json:"docID"`
URI string `json:"edvDocURI"`
EncKeyURI string `json:"encKeyURI"`
}
// Client vault`s client.
type Client struct {
remoteKMSURL string
edvHost string
edvScheme string
didMethod string
didDomain string
didAnchorOrigin string
kms KeyManager
crypto ariescrypto.Crypto
edvClient *edv.Client
httpClient HTTPClient
store storage.Store
registry vdr.Registry
documentLoader ld.DocumentLoader
}
// Opt represents Client`s option.
type Opt func(*Client)
// WithHTTPClient allows providing HTTP client.
func WithHTTPClient(client HTTPClient) Opt {
return func(vault *Client) {
vault.httpClient = client
}
}
// WithDidMethod allows providing did method.
func WithDidMethod(method string) Opt {
return func(vault *Client) {
vault.didMethod = method
}
}
// WithDidDomain allows providing did domain.
func WithDidDomain(domain string) Opt {
return func(vault *Client) {
vault.didDomain = domain
}
}
// WithDidAnchorOrigin allows providing did anchor origin.
func WithDidAnchorOrigin(anchorOrigin string) Opt {
return func(vault *Client) {
vault.didAnchorOrigin = anchorOrigin
}
}
// WithRegistry allows providing registry.
func WithRegistry(registry vdr.Registry) Opt {
return func(vault *Client) {
vault.registry = registry
}
}
// NewClient creates a new vault client.
func NewClient(kmsURL, edvURL string, kmsClient kms.KeyManager, db storage.Provider, loader ld.DocumentLoader,
opts ...Opt,
) (*Client, error) {
cryptoService, err := tinkcrypto.New()
if err != nil {
return nil, fmt.Errorf("tinkcrypto new: %w", err)
}
u, err := url.Parse(edvURL)
if err != nil {
return nil, fmt.Errorf("url parse: %w", err)
}
store, err := db.OpenStore(storeName)
if err != nil {
return nil, fmt.Errorf("open store: %w", err)
}
client := &Client{
remoteKMSURL: kmsURL,
edvHost: u.Host,
edvScheme: u.Scheme,
kms: kmsClient,
crypto: cryptoService,
store: store,
httpClient: &http.Client{
Timeout: time.Minute,
},
didMethod: "key",
registry: ariesvdr.New(
ariesvdr.WithVDR(vdrkey.New()),
),
documentLoader: loader,
}
for _, fn := range opts {
fn(client)
}
client.edvClient = edv.New(edvURL, edv.WithHTTPClient(client.httpClient))
return client, nil
}
// CreateVault creates a new vault and KMS store bases on generated DIDKey.
func (c *Client) CreateVault() (*CreatedVault, error) {
didKey, didURL, kid, err := c.createDIDKey(c.didMethod)
if err != nil {
return nil, fmt.Errorf("create DID key: %w", err)
}
// TODO: Implement support for GNAP authorization (https://github.com/trustbloc/ace/issues/50)
kmsURI, kmsZCAP, err := webkms.CreateKeyStore(c.httpClient, c.remoteKMSURL, didURL, "", nil,
webkms.WithHeaders(func(req *http.Request) (*http.Header, error) {
h := req.Header.Clone()
h.Set("Authorization", "Bearer fake-token")
return &h, nil
}),
)
if err != nil {
return nil, fmt.Errorf("create key store: %w", err)
}
edvLoc, err := c.createDataVault(didURL)
if err != nil {
return nil, fmt.Errorf("create data vault: %w", err)
}
edvLoc.URI = buildEDVURI(c.edvScheme, c.edvHost, lastElm(edvLoc.URI, "/"))
auth := &Authorization{
KMS: &Location{
URI: c.buildKMSURL(kmsURI),
AuthToken: base64.URLEncoding.EncodeToString(kmsZCAP),
},
EDV: edvLoc,
}
err = c.saveVaultInfo(didKey, &vaultInfo{Auth: auth, KID: kid, DidURL: didURL})
if err != nil {
return nil, fmt.Errorf("save vault info: %w", err)
}
return &CreatedVault{
ID: didKey,
Authorization: auth,
}, nil
}
// CreateAuthorization creates a new authorization.
// nolint: funlen
func (c *Client) CreateAuthorization(vaultID, requestingParty string, scope *AuthorizationsScope,
) (*CreatedAuthorization, error) {
info, err := c.getVaultInfo(vaultID)
if err != nil {
return nil, fmt.Errorf("get vault info: %w", err)
}
kh, err := c.kms.Get(info.KID)
if err != nil {
return nil, fmt.Errorf("kms get: %w", err)
}
kmsCapability, err := zcapld.DecompressZCAP(info.Auth.KMS.AuthToken)
if err != nil {
return nil, fmt.Errorf("kms uncompressZCAP: %w", err)
}
kmsNewCapability, err := zcapld.NewCapability(&zcapld.Signer{
SignatureSuite: ed25519signature2018.New(suite.WithSigner(newSigner(c.crypto, kh))),
SuiteType: ed25519signature2018.SignatureType,
VerificationMethod: info.DidURL,
ProcessorOpts: []jsonld.ProcessorOpts{jsonld.WithDocumentLoader(c.documentLoader)},
}, zcapld.WithParent(c.buildKMSURL(kmsCapability.ID)), zcapld.WithInvoker(requestingParty),
zcapld.WithAllowedActions("unwrap"),
zcapld.WithInvocationTarget(c.buildKMSURL(kmsCapability.InvocationTarget.ID), kmsCapability.InvocationTarget.Type),
zcapld.WithCaveats(toZCaveats(scope.Caveats)...),
zcapld.WithCapabilityChain(c.buildKMSURL(kmsCapability.ID)))
if err != nil {
return nil, fmt.Errorf("kms new capability: %w", err)
}
kmsCompressedCapability, err := zcapld.CompressZCAP(kmsNewCapability)
if err != nil {
return nil, fmt.Errorf("kms compressZCAP: %w", err)
}
edvCapability, err := zcapld.DecompressZCAP(info.Auth.EDV.AuthToken)
if err != nil {
return nil, fmt.Errorf("edv uncompressZCAP: %w", err)
}
edvNewCapability, err := zcapld.NewCapability(&zcapld.Signer{
SignatureSuite: ed25519signature2018.New(suite.WithSigner(newSigner(c.crypto, kh))),
SuiteType: ed25519signature2018.SignatureType,
VerificationMethod: info.DidURL,
ProcessorOpts: []jsonld.ProcessorOpts{jsonld.WithDocumentLoader(c.documentLoader)},
}, zcapld.WithParent(edvCapability.ID), zcapld.WithInvoker(requestingParty),
zcapld.WithAllowedActions(scope.Actions...),
zcapld.WithInvocationTarget(edvCapability.InvocationTarget.ID, edvCapability.InvocationTarget.Type),
zcapld.WithCaveats(toZCaveats(scope.Caveats)...),
zcapld.WithCapabilityChain(edvCapability.Parent, edvCapability.ID))
if err != nil {
return nil, fmt.Errorf("edv new capability: %w", err)
}
edvCompressedCapability, err := zcapld.CompressZCAP(edvNewCapability)
if err != nil {
return nil, fmt.Errorf("edv compressZCAP: %w", err)
}
res := &CreatedAuthorization{
ID: uuid.New().String(),
Scope: scope,
RequestingParty: requestingParty,
Tokens: &Tokens{
KMS: kmsCompressedCapability,
EDV: edvCompressedCapability,
},
}
err = c.saveAuthorization(vaultID, res)
if err != nil {
return nil, fmt.Errorf("save authorization: %w", err)
}
return res, nil
}
func toZCaveats(caveats []Caveat) []zcapld.Caveat {
zCaveats := make([]zcapld.Caveat, len(caveats))
for i, caveat := range caveats {
zCaveats[i] = zcapld.Caveat{
Type: caveat.Type,
Duration: caveat.Duration,
}
}
return zCaveats
}
// GetAuthorization returns an authorization by given id.
func (c *Client) GetAuthorization(vaultID, id string) (*CreatedAuthorization, error) {
return c.getAuthorization(vaultID, id)
}
func (c *Client) saveAuthorization(vID string, a *CreatedAuthorization) error {
src, err := json.Marshal(a)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
return c.store.Put(fmt.Sprintf(authorizationFormat, vID, a.ID), src)
}
func (c *Client) getAuthorization(vID, id string) (*CreatedAuthorization, error) {
src, err := c.store.Get(fmt.Sprintf(authorizationFormat, vID, id))
if err != nil {
return nil, fmt.Errorf("get: %w", err)
}
var res *CreatedAuthorization
err = json.Unmarshal(src, &res)
if err != nil {
return nil, fmt.Errorf("unmarshal: %w", err)
}
return res, nil
}
// GetDocMetadata returns document`s metadata.
func (c *Client) GetDocMetadata(vaultID, docID string) (*DocumentMetadata, error) {
info, err := c.getVaultInfo(vaultID)
if err != nil {
return nil, fmt.Errorf("get vault info: %w", err)
}
edvVaultID := lastElm(info.Auth.EDV.URI, "/")
dInfo, err := c.getMetaDocInfo(vaultID, docID)
if err != nil {
return nil, fmt.Errorf("get meta doc info: %w", err)
}
_, err = c.edvClient.ReadDocument(edvVaultID, dInfo.EdvID, edv.WithRequestHeader(
c.edvSign(info.DidURL, info.Auth.EDV)),
)
if err != nil {
return nil, fmt.Errorf("read document: %w", err)
}
return &DocumentMetadata{
ID: docID,
URI: buildEDVDocURI(c.edvScheme, c.edvHost, edvVaultID, dInfo.EdvID),
EncKeyURI: dInfo.KidURL,
}, nil
}
// SaveDoc saves a document by encrypting it and storing it in the vault.
func (c *Client) SaveDoc(vaultID, id string, content []byte) (*DocumentMetadata, error) { // nolint:funlen
info, err := c.getVaultInfo(vaultID)
if err != nil {
return nil, fmt.Errorf("get vault info: %w", err)
}
docID, err := edvutils.GenerateEDVCompatibleID()
if err != nil {
return nil, fmt.Errorf("failed to generate an EDV document ID: %w", err)
}
docContents := make(map[string]interface{})
err = json.NewDecoder(bytes.NewReader(content)).Decode(&docContents)
if err != nil {
return nil, fmt.Errorf("failed to decode content: %w", err)
}
kidURL, encContent, err := encryptContent(
c.webKMS(info.DidURL, info.Auth.KMS),
c.webCrypto(info.DidURL, info.Auth.KMS),
&models.StructuredDocument{
ID: docID,
Content: docContents,
},
)
if err != nil {
return nil, fmt.Errorf("encrypt key: %w", err)
}
dInfo, err := c.getMetaDocInfo(vaultID, id)
if err != nil && !errors.Is(err, storage.ErrDataNotFound) {
return nil, fmt.Errorf("get meta doc info: %w", err)
}
if errors.Is(err, storage.ErrDataNotFound) {
dInfo, err = c.createMetaDocInfo(vaultID, id, kidURL)
if err != nil {
return nil, fmt.Errorf("create meta doc info: %w", err)
}
}
edvVaultID := lastElm(info.Auth.EDV.URI, "/")
_, err = c.edvClient.CreateDocument(edvVaultID, &models.EncryptedDocument{
ID: dInfo.EdvID,
JWE: []byte(encContent),
}, edv.WithRequestHeader(c.edvSign(info.DidURL, info.Auth.EDV)))
if err == nil {
return &DocumentMetadata{
URI: buildEDVDocURI(c.edvScheme, c.edvHost, edvVaultID, dInfo.EdvID),
ID: id,
EncKeyURI: dInfo.KidURL,
}, nil
}
if !strings.HasSuffix(err.Error(), messages.ErrDuplicateDocument.Error()+".") {
return nil, fmt.Errorf("create document: %w", err)
}
err = c.edvClient.UpdateDocument(edvVaultID, dInfo.EdvID, &models.EncryptedDocument{
ID: dInfo.EdvID,
JWE: []byte(encContent),
}, edv.WithRequestHeader(c.edvSign(info.DidURL, info.Auth.EDV)))
if err != nil {
return nil, fmt.Errorf("update document: %w", err)
}
return &DocumentMetadata{
ID: id,
URI: buildEDVDocURI(c.edvScheme, c.edvHost, edvVaultID, dInfo.EdvID),
EncKeyURI: dInfo.KidURL,
}, nil
}
type vaultInfo struct {
KID string `json:"kid"`
DidURL string `json:"did_url"`
Auth *Authorization `json:"auth"`
}
func (c *Client) saveVaultInfo(id string, info *vaultInfo) error {
src, err := json.Marshal(info)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
return c.store.Put(fmt.Sprintf(infoFormat, id), src)
}
type metaDocInfo struct {
EdvID string `json:"edv_id"`
KidURL string `json:"kid_url"`
}
func (c *Client) createMetaDocInfo(vid, id, kid string) (*metaDocInfo, error) {
edvID, err := edvutils.GenerateEDVCompatibleID()
if err != nil {
return nil, fmt.Errorf("generate EDV compatible id: %w", err)
}
info := &metaDocInfo{EdvID: edvID, KidURL: c.buildKMSURL(kid)}
src, err := json.Marshal(info)
if err != nil {
return nil, fmt.Errorf("marshal: %w", err)
}
err = c.store.Put(fmt.Sprintf(metaDocInfoFormat, vid, id), src)
if err != nil {
return nil, fmt.Errorf("store put: %w", err)
}
return info, nil
}
func (c *Client) getMetaDocInfo(vid, id string) (*metaDocInfo, error) {
src, err := c.store.Get(fmt.Sprintf(metaDocInfoFormat, vid, id))
if err != nil {
return nil, fmt.Errorf("store get: %w", err)
}
var info *metaDocInfo
err = json.Unmarshal(src, &info)
if err != nil {
return nil, fmt.Errorf("store get: %w", err)
}
return info, nil
}
func (c *Client) getVaultInfo(id string) (*vaultInfo, error) {
src, err := c.store.Get(fmt.Sprintf(infoFormat, id))
if err != nil {
return nil, fmt.Errorf("get: %w", err)
}
var info *vaultInfo
err = json.Unmarshal(src, &info)
if err != nil {
return nil, fmt.Errorf("unmarshal: %w", err)
}
return info, nil
}
func (c *Client) webKMS(controller string, auth *Location) *webkms.RemoteKMS {
return webkms.New(
c.buildKMSURL(auth.URI),
c.httpClient,
webkms.WithHeaders(c.kmsSign(controller, auth)),
)
}
func (c *Client) buildKMSURL(uri string) string {
if strings.HasPrefix(uri, "/") {
return c.remoteKMSURL + uri
}
return uri
}
func (c *Client) webCrypto(controller string, auth *Location) *webcrypto.RemoteCrypto {
return webcrypto.New(
c.buildKMSURL(auth.URI),
c.httpClient,
webkms.WithHeaders(c.kmsSign(controller, auth)),
)
}
func (c *Client) createDIDKey(method string) (string, string, string, error) {
kid, didDoc, err := newDidDoc(c.kms, method)
if err != nil {
return "", "", "", err
}
_, recoverKey, err := newKey(c.kms)
if err != nil {
return "", "", "", err
}
_, updateKey, err := newKey(c.kms)
if err != nil {
return "", "", "", err
}
docResolution, err := c.registry.Create(c.didMethod, didDoc,
vdr.WithOption(orb.RecoveryPublicKeyOpt, recoverKey),
vdr.WithOption(orb.UpdatePublicKeyOpt, updateKey),
vdr.WithOption(orb.AnchorOriginOpt, c.didAnchorOrigin),
)
if err != nil {
return "", "", "", err
}
docID := docResolution.DIDDocument.ID
capabilityVMID := docResolution.DIDDocument.CapabilityDelegation[0].VerificationMethod.ID
return docID, capabilityVMID, kid, nil
}
func newDidDoc(k kms.KeyManager, method string) (string, *ariesdid.Doc, error) {
didDoc := &ariesdid.Doc{}
kid, publicKey, err := newKey(k)
if err != nil {
return "", nil, err
}
jwk, err := jwksupport.JWKFromKey(publicKey)
if err != nil {
return "", nil, err
}
keyID := uuid.New().String()
if method == "key" {
jwk.KeyID = kid
_, keyID = fingerprint.CreateDIDKey(publicKey)
var mainVM *ariesdid.VerificationMethod
mainVM, err = ariesdid.NewVerificationMethodFromJWK(keyID, doc.Ed25519VerificationKey2018, "", jwk)
if err != nil {
return "", nil, err
}
didDoc.VerificationMethod = append([]ariesdid.VerificationMethod{}, *mainVM)
}
vm, err := ariesdid.NewVerificationMethodFromJWK(keyID, crypto.JSONWebKey2020, "", jwk)
if err != nil {
return "", nil, err
}
didDoc.Authentication = append(didDoc.Authentication,
*ariesdid.NewReferencedVerification(vm, ariesdid.Authentication))
didDoc.AssertionMethod = append(didDoc.AssertionMethod,
*ariesdid.NewReferencedVerification(vm, ariesdid.AssertionMethod))
didDoc.CapabilityDelegation = append(didDoc.CapabilityDelegation,
*ariesdid.NewReferencedVerification(vm, ariesdid.CapabilityDelegation))
return kid, didDoc, nil
}
func newKey(k kms.KeyManager) (string, ed25519.PublicKey, error) {
keyID, bits, err := k.CreateAndExportPubKeyBytes(kms.ED25519Type)
if err != nil {
return "", nil, fmt.Errorf("failed to create key : %w", err)
}
return keyID, bits, nil
}
func (c *Client) createDataVault(didKey string) (*Location, error) {
vaultURI, rawCapability, err := c.edvClient.CreateDataVault(&models.DataVaultConfiguration{
Controller: didKey,
ReferenceID: uuid.New().String(),
KEK: models.IDTypePair{ID: uuid.New().URN(), Type: "AesKeyWrappingKey2019"},
HMAC: models.IDTypePair{ID: uuid.New().URN(), Type: "Sha256HmacKey2019"},
})
if err != nil {
return nil, fmt.Errorf("create data vault: %w", err)
}
capability, err := zcapld.ParseCapability(rawCapability)
if err != nil {
return nil, fmt.Errorf("parse capability: %w", err)
}
compressedZcap, err := zcapld.CompressZCAP(capability)
if err != nil {
return nil, fmt.Errorf("compress zcap: %w", err)
}
return &Location{URI: vaultURI, AuthToken: compressedZcap}, nil
}
func (c *Client) edvSign(controller string, auth *Location) func(req *http.Request) (*http.Header, error) {
return func(req *http.Request) (*http.Header, error) {
action := "write"
if req.Method == http.MethodGet {
action = "read"
}
return c.sign(req, controller, action, auth.AuthToken)
}
}
func (c *Client) kmsSign(controller string, auth *Location) func(req *http.Request) (*http.Header, error) {
return func(req *http.Request) (*http.Header, error) {
action, err := zcapldutil.CapabilityInvocationAction(req)
if err != nil {
return nil, fmt.Errorf("capability invocation action: %w", err)
}
return c.sign(req, controller, action, auth.AuthToken)
}
}
func (c *Client) sign(req *http.Request, controller, action, zcap string) (*http.Header, error) {
req.Header.Set(
zcapld.CapabilityInvocationHTTPHeader,
fmt.Sprintf(`zcap capability=%q,action=%q`, zcap, action),
)
hs := httpsignatures.NewHTTPSignatures(&zcapld.AriesDIDKeySecrets{})
hs.SetSignatureHashAlgorithm(&zcapld.AriesDIDKeySignatureHashAlgorithm{
Crypto: c.crypto,
KMS: c.kms,
Resolver: c.registry,
})
err := hs.Sign(controller, req)
if err != nil {
return nil, fmt.Errorf("failed to sign http request: %w", err)
}
return &req.Header, nil
}
func lastElm(s, sep string) string { // nolint: unparam
all := strings.Split(s, sep)
return all[len(all)-1]
}
func buildEDVDocURI(s, h, vid, did string) string {
return fmt.Sprintf("%s/documents/%s", buildEDVURI(s, h, vid), did)
}
func buildEDVURI(s, h, vid string) string {
return fmt.Sprintf("%s://%s/encrypted-data-vaults/%s", s, h, vid)
}
func encryptContent(wKMS KeyManager, wCrypto ariescrypto.Crypto, content interface{}) (string, string, error) {
src, err := json.Marshal(content)
if err != nil {
return "", "", fmt.Errorf("marshal: %w", err)
}
_, kidURL, err := wKMS.Create(kms.NISTP256ECDHKW)
if err != nil {
return "", "", fmt.Errorf("create: %w", err)
}
kidURLStr, ok := kidURL.(string)
if !ok {
return "", "", fmt.Errorf("kidURL is not a string")
}
pubKeyBytes, _, err := wKMS.ExportPubKeyBytes(lastElm(kidURLStr, "/"))
if err != nil {
return "", "", fmt.Errorf("export pubKey bytes: %w", err)
}
var ecPubKey *ariescrypto.PublicKey
err = json.Unmarshal(pubKeyBytes, &ecPubKey)
if err != nil {
return "", "", fmt.Errorf("unmarshal: %w", err)
}
encrypter, err := jose.NewJWEEncrypt(jose.A256GCM, jose.A256GCMALG, "", "", nil,
[]*ariescrypto.PublicKey{ecPubKey}, wCrypto)
if err != nil {
return "", "", fmt.Errorf("new JWE encrypt: %w", err)
}
jwe, err := encrypter.Encrypt(src)
if err != nil {
return "", "", fmt.Errorf("encrypt: %w", err)
}
eContent, err := jwe.FullSerialize(json.Marshal)
if err != nil {
return "", "", fmt.Errorf("full serialize: %w", err)
}
return kidURLStr, eContent, nil
}
type signer struct {
crypto ariescrypto.Crypto
kh interface{}
}
func newSigner(cr ariescrypto.Crypto, kh interface{}) *signer {
return &signer{crypto: cr, kh: kh}
}
func (s *signer) Sign(data []byte) ([]byte, error) {
return s.crypto.Sign(data, s.kh)
}
func (s *signer) Alg() string {
return ""
}