This repository has been archived by the owner on Mar 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 160
/
doc.go
1605 lines (1284 loc) · 43.9 KB
/
doc.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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package did
import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"time"
"github.com/btcsuite/btcutil/base58"
"github.com/multiformats/go-multibase"
"github.com/xeipuuv/gojsonschema"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
"github.com/hyperledger/aries-framework-go/pkg/common/model"
"github.com/hyperledger/aries-framework-go/pkg/doc/jose/jwk"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/jsonld"
sigproof "github.com/hyperledger/aries-framework-go/pkg/doc/signature/proof"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/verifier"
)
const (
// ContextV1 of the DID document is the current V1 context name.
ContextV1 = "https://www.w3.org/ns/did/v1"
// ContextV1Old of the DID document representing the old/legacy V1 context name.
ContextV1Old = "https://w3id.org/did/v1"
contextV011 = "https://w3id.org/did/v0.11"
contextV12019 = "https://www.w3.org/2019/did/v1"
jsonldType = "type"
jsonldID = "id"
jsonldPublicKey = "publicKey"
jsonldServicePoint = "serviceEndpoint"
jsonldRecipientKeys = "recipientKeys"
jsonldRoutingKeys = "routingKeys"
jsonldPriority = "priority"
jsonldController = "controller"
jsonldOwner = "owner"
jsonldCreator = "creator"
jsonldCreated = "created"
jsonldProofValue = "proofValue"
jsonldSignatureValue = "signatureValue"
jsonldDomain = "domain"
jsonldNonce = "nonce"
jsonldProofPurpose = "proofPurpose"
// various public key encodings.
jsonldPublicKeyBase58 = "publicKeyBase58"
jsonldPublicKeyMultibase = "publicKeyMultibase"
jsonldPublicKeyHex = "publicKeyHex"
jsonldPublicKeyPem = "publicKeyPem"
jsonldPublicKeyjwk = "publicKeyJwk"
// service type that needed for v011 did-doc resolution.
legacyServiceType = "IndyAgent"
)
var (
schemaLoaderV1 = gojsonschema.NewStringLoader(schemaV1) //nolint:gochecknoglobals
schemaLoaderV011 = gojsonschema.NewStringLoader(schemaV011) //nolint:gochecknoglobals
schemaLoaderV12019 = gojsonschema.NewStringLoader(schemaV12019) //nolint:gochecknoglobals
logger = log.New("aries-framework/doc/did") //nolint:gochecknoglobals
)
// ErrDIDDocumentNotExist error did doc not exist.
var ErrDIDDocumentNotExist = errors.New("did document not exists")
// DID is parsed according to the generic syntax: https://w3c.github.io/did-core/#generic-did-syntax
type DID struct {
Scheme string // Scheme is always "did"
Method string // Method is the specific DID methods
MethodSpecificID string // MethodSpecificID is the unique ID computed or assigned by the DID method
}
// String returns a string representation of this DID.
func (d *DID) String() string {
return fmt.Sprintf("%s:%s:%s", d.Scheme, d.Method, d.MethodSpecificID)
}
// Parse parses the string according to the generic DID syntax.
// See https://w3c.github.io/did-core/#generic-did-syntax.
func Parse(did string) (*DID, error) {
// I could not find a good ABNF parser :(
const idchar = `a-zA-Z0-9-_\.`
regex := fmt.Sprintf(`^did:[a-z0-9]+:(:+|[:%s]+)*[%%:%s]+[^:]$`, idchar, idchar)
r, err := regexp.Compile(regex)
if err != nil {
return nil, fmt.Errorf("failed to compile regex=%s (this should not have happened!). %w", regex, err)
}
if !r.MatchString(did) {
return nil, fmt.Errorf(
"invalid did: %s. Make sure it conforms to the DID syntax: https://w3c.github.io/did-core/#did-syntax", did)
}
parts := strings.SplitN(did, ":", 3)
return &DID{
Scheme: "did",
Method: parts[1],
MethodSpecificID: parts[2],
}, nil
}
// DIDURL holds a DID URL.
type DIDURL struct { // nolint:golint // ignore name stutter
DID
Path string
Queries map[string][]string
Fragment string
}
// ParseDIDURL parses a DID URL string into a DIDURL object.
func ParseDIDURL(didURL string) (*DIDURL, error) {
split := strings.IndexAny(didURL, "?/#")
didPart := didURL
pathQueryFragment := ""
if split != -1 {
didPart = didURL[:split]
pathQueryFragment = didURL[split:]
}
retDID, err := Parse(didPart)
if err != nil {
return nil, err
}
if pathQueryFragment == "" {
return &DIDURL{
DID: *retDID,
Queries: map[string][]string{},
}, nil
}
hasPath := pathQueryFragment[0] == '/'
if !hasPath {
pathQueryFragment = "/" + pathQueryFragment
}
urlParts, err := url.Parse(pathQueryFragment)
if err != nil {
return nil, fmt.Errorf("failed to parse path, query, and fragment components of DID URL: %w", err)
}
ret := &DIDURL{
DID: *retDID,
Queries: urlParts.Query(),
Fragment: urlParts.Fragment,
}
if hasPath {
ret.Path = urlParts.Path
}
return ret, nil
}
// Context represents JSON-LD representation-specific DID-core @context, which
// must be either a string, or a list containing maps and/or strings.
type Context interface{}
// DocResolution did resolution.
type DocResolution struct {
Context Context
DIDDocument *Doc
DocumentMetadata *DocumentMetadata
}
// MethodMetadata method metadata.
type MethodMetadata struct {
// UpdateCommitment is update commitment key.
UpdateCommitment string `json:"updateCommitment,omitempty"`
// RecoveryCommitment is recovery commitment key.
RecoveryCommitment string `json:"recoveryCommitment,omitempty"`
// Published is published key.
Published bool `json:"published,omitempty"`
// AnchorOrigin is anchor origin.
AnchorOrigin string `json:"anchorOrigin,omitempty"`
// UnpublishedOperations unpublished operations
UnpublishedOperations []*ProtocolOperation `json:"unpublishedOperations,omitempty"`
// PublishedOperations published operations
PublishedOperations []*ProtocolOperation `json:"publishedOperations,omitempty"`
}
// ProtocolOperation info.
type ProtocolOperation struct {
// Operation is operation request.
Operation string `json:"operation,omitempty"`
// ProtocolVersion is protocol version.
ProtocolVersion int `json:"protocolVersion,omitempty"`
// TransactionNumber is transaction number.
TransactionNumber int `json:"transactionNumber,omitempty"`
// TransactionTime is transaction time.
TransactionTime int64 `json:"transactionTime,omitempty"`
// Type is type of operation.
Type string `json:"type,omitempty"`
// AnchorOrigin is anchor origin.
AnchorOrigin string `json:"anchorOrigin,omitempty"`
// CanonicalReference is canonical reference
CanonicalReference string `json:"canonicalReference,omitempty"`
// EquivalentReferences is equivalent references
EquivalentReferences []string `json:"equivalentReferences,omitempty"`
}
// DocumentMetadata document metadata.
type DocumentMetadata struct {
// VersionID is version ID key.
VersionID string `json:"versionId,omitempty"`
// Deactivated is deactivated flag key.
Deactivated bool `json:"deactivated,omitempty"`
// CanonicalID is canonical ID key.
CanonicalID string `json:"canonicalId,omitempty"`
// EquivalentID is equivalent ID array.
EquivalentID []string `json:"equivalentId,omitempty"`
// Method is used for method metadata within did document metadata.
Method *MethodMetadata `json:"method,omitempty"`
}
type rawDocResolution struct {
Context Context `json:"@context"`
DIDDocument json.RawMessage `json:"didDocument,omitempty"`
DocumentMetadata json.RawMessage `json:"didDocumentMetadata,omitempty"`
}
// ParseDocumentResolution parse document resolution.
func ParseDocumentResolution(data []byte) (*DocResolution, error) {
raw := &rawDocResolution{}
if err := json.Unmarshal(data, raw); err != nil {
return nil, err
}
if len(raw.DIDDocument) == 0 {
return nil, ErrDIDDocumentNotExist
}
doc, err := ParseDocument(raw.DIDDocument)
if err != nil {
return nil, err
}
docMeta := &DocumentMetadata{}
if len(raw.DocumentMetadata) != 0 {
if err := json.Unmarshal(raw.DocumentMetadata, docMeta); err != nil {
return nil, err
}
}
context, _ := parseContext(raw.Context)
return &DocResolution{Context: context, DIDDocument: doc, DocumentMetadata: docMeta}, nil
}
// Doc DID Document definition.
type Doc struct {
Context Context
ID string
AlsoKnownAs []string
VerificationMethod []VerificationMethod
Service []Service
Authentication []Verification
AssertionMethod []Verification
CapabilityDelegation []Verification
CapabilityInvocation []Verification
KeyAgreement []Verification
Created *time.Time
Updated *time.Time
Proof []Proof
processingMeta processingMeta
}
// processingMeta include info how to process the doc.
type processingMeta struct {
baseURI string
}
// VerificationMethod DID doc verification method.
// The value of the verification method is defined either as raw public key bytes (Value field) or as JSON Web Key.
// In the first case the Type field can hold additional information to understand the nature of the raw public key.
type VerificationMethod struct {
ID string
Type string
Controller string
Value []byte
jsonWebKey *jwk.JWK
relativeURL bool
multibaseEncoding multibase.Encoding
}
// NewVerificationMethodFromBytesWithMultibase creates a new VerificationMethod based on
// raw public key bytes with multibase.
func NewVerificationMethodFromBytesWithMultibase(id, keyType, controller string, value []byte,
encoding multibase.Encoding) *VerificationMethod {
relativeURL := false
if strings.HasPrefix(id, "#") {
relativeURL = true
}
return &VerificationMethod{
ID: id,
Type: keyType,
Controller: controller,
Value: value,
relativeURL: relativeURL,
multibaseEncoding: encoding,
}
}
// NewVerificationMethodFromBytes creates a new VerificationMethod based on raw public key bytes.
func NewVerificationMethodFromBytes(id, keyType, controller string, value []byte) *VerificationMethod {
relativeURL := false
if strings.HasPrefix(id, "#") {
relativeURL = true
}
if keyType == "Ed25519VerificationKey2020" {
return NewVerificationMethodFromBytesWithMultibase(id, keyType, controller, value, multibase.Base58BTC)
}
return &VerificationMethod{
ID: id,
Type: keyType,
Controller: controller,
Value: value,
relativeURL: relativeURL,
}
}
// NewVerificationMethodFromJWK creates a new VerificationMethod based on JSON Web Key.
func NewVerificationMethodFromJWK(id, keyType, controller string, j *jwk.JWK) (*VerificationMethod, error) {
pkBytes, err := j.PublicKeyBytes()
if err != nil {
return nil, fmt.Errorf("convert JWK to public key bytes: %w", err)
}
relativeURL := false
if strings.HasPrefix(id, "#") {
relativeURL = true
}
return &VerificationMethod{
ID: id,
Type: keyType,
Controller: controller,
Value: pkBytes,
jsonWebKey: j,
relativeURL: relativeURL,
}, nil
}
// JSONWebKey returns JSON Web key if defined.
func (pk *VerificationMethod) JSONWebKey() *jwk.JWK {
return pk.jsonWebKey
}
// Service DID doc service.
type Service struct {
ID string `json:"id"`
Type interface{} `json:"type"`
Priority interface{} `json:"priority,omitempty"`
RecipientKeys []string `json:"recipientKeys,omitempty"`
RoutingKeys []string `json:"routingKeys,omitempty"`
ServiceEndpoint model.Endpoint `json:"serviceEndpoint"`
Accept []string `json:"accept,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
recipientKeysRelativeURL map[string]bool
routingKeysRelativeURL map[string]bool
relativeURL bool
}
// VerificationRelationship defines a verification relationship between DID subject and a verification method.
type VerificationRelationship int
const (
// VerificationRelationshipGeneral is a special case of verification relationship: when a verification method
// defined in Verification is not used by any Verification.
VerificationRelationshipGeneral VerificationRelationship = iota
// Authentication defines verification relationship.
Authentication
// AssertionMethod defines verification relationship.
AssertionMethod
// CapabilityDelegation defines verification relationship.
CapabilityDelegation
// CapabilityInvocation defines verification relationship.
CapabilityInvocation
// KeyAgreement defines verification relationship.
KeyAgreement
)
// Verification authentication verification.
type Verification struct {
VerificationMethod VerificationMethod
Relationship VerificationRelationship
Embedded bool
}
// NewEmbeddedVerification creates a new verification method with embedded verification method.
func NewEmbeddedVerification(vm *VerificationMethod, r VerificationRelationship) *Verification {
return &Verification{
VerificationMethod: *vm,
Relationship: r,
Embedded: true,
}
}
// NewReferencedVerification creates a new verification method with referenced verification method.
func NewReferencedVerification(vm *VerificationMethod, r VerificationRelationship) *Verification {
return &Verification{
VerificationMethod: *vm,
Relationship: r,
}
}
type rawDoc struct {
Context Context `json:"@context,omitempty"`
ID string `json:"id,omitempty"`
AlsoKnownAs []interface{} `json:"alsoKnownAs,omitempty"`
VerificationMethod []map[string]interface{} `json:"verificationMethod,omitempty"`
PublicKey []map[string]interface{} `json:"publicKey,omitempty"`
Service []map[string]interface{} `json:"service,omitempty"`
Authentication []interface{} `json:"authentication,omitempty"`
AssertionMethod []interface{} `json:"assertionMethod,omitempty"`
CapabilityDelegation []interface{} `json:"capabilityDelegation,omitempty"`
CapabilityInvocation []interface{} `json:"capabilityInvocation,omitempty"`
KeyAgreement []interface{} `json:"keyAgreement,omitempty"`
Created *time.Time `json:"created,omitempty"`
Updated *time.Time `json:"updated,omitempty"`
Proof []interface{} `json:"proof,omitempty"`
}
// Proof is cryptographic proof of the integrity of the DID Document.
type Proof struct {
Type string
Created *time.Time
Creator string
ProofValue []byte
Domain string
Nonce []byte
ProofPurpose string
relativeURL bool
}
// UnmarshalJSON unmarshals a DID Document.
func (doc *Doc) UnmarshalJSON(data []byte) error {
_doc, err := ParseDocument(data)
if err != nil {
return fmt.Errorf("failed to parse did doc: %w", err)
}
*doc = *_doc
return nil
}
// ParseDocument creates an instance of DIDDocument by reading a JSON document from bytes.
func ParseDocument(data []byte) (*Doc, error) { // nolint:funlen,gocyclo
raw := &rawDoc{}
err := json.Unmarshal(data, &raw)
if err != nil {
return nil, fmt.Errorf("JSON marshalling of did doc bytes bytes failed: %w", err)
} else if raw == nil {
return nil, errors.New("document payload is not provided")
}
// Interop: handle legacy did docs that incorrectly indicate they use the new format
// aca-py and vcx issue: https://github.com/hyperledger/aries-cloudagent-python/issues/1048
var serviceType string
if len(raw.Service) > 0 {
serviceType, _ = raw.Service[0]["type"].(string) //nolint: errcheck
}
if (doACAPYInterop || serviceType == legacyServiceType) && requiresLegacyHandling(raw) {
raw.Context = []string{contextV011}
} else {
// validate did document
err = validate(data, raw.schemaLoader())
if err != nil {
return nil, err
}
}
doc := &Doc{
ID: raw.ID,
AlsoKnownAs: stringArray(raw.AlsoKnownAs),
Created: raw.Created,
Updated: raw.Updated,
}
context, baseURI := parseContext(raw.Context)
doc.Context = context
doc.processingMeta = processingMeta{baseURI: baseURI}
doc.Service = populateServices(raw.ID, baseURI, raw.Service)
verificationMethod := raw.PublicKey
if len(raw.VerificationMethod) != 0 {
verificationMethod = raw.VerificationMethod
}
schema, _ := ContextPeekString(context)
vm, err := populateVerificationMethod(schema, doc.ID, baseURI, verificationMethod)
if err != nil {
return nil, fmt.Errorf("populate verification method failed: %w", err)
}
doc.VerificationMethod = vm
err = populateVerificationRelationships(doc, raw)
if err != nil {
return nil, err
}
proofs, err := populateProofs(schema, doc.ID, baseURI, raw.Proof)
if err != nil {
return nil, fmt.Errorf("populate proofs failed: %w", err)
}
doc.Proof = proofs
return doc, nil
}
func requiresLegacyHandling(raw *rawDoc) bool {
// aca-py issue: https://github.com/hyperledger/aries-cloudagent-python/issues/1048
// old v1 context is (currently) only used by projects like aca-py that
// have not fully updated to latest did spec for aip2.0
return ContextContainsString(raw.Context, ContextV1Old)
}
func populateVerificationRelationships(doc *Doc, raw *rawDoc) error {
authentications, err := populateVerification(doc, raw.Authentication, Authentication)
if err != nil {
return fmt.Errorf("populate authentications failed: %w", err)
}
doc.Authentication = authentications
assertionMethods, err := populateVerification(doc, raw.AssertionMethod, AssertionMethod)
if err != nil {
return fmt.Errorf("populate assertion methods failed: %w", err)
}
doc.AssertionMethod = assertionMethods
capabilityDelegations, err := populateVerification(doc, raw.CapabilityDelegation, CapabilityDelegation)
if err != nil {
return fmt.Errorf("populate capability delegations failed: %w", err)
}
doc.CapabilityDelegation = capabilityDelegations
capabilityInvocations, err := populateVerification(doc, raw.CapabilityInvocation, CapabilityInvocation)
if err != nil {
return fmt.Errorf("populate capability invocations failed: %w", err)
}
doc.CapabilityInvocation = capabilityInvocations
keyAgreements, err := populateVerification(doc, raw.KeyAgreement, KeyAgreement)
if err != nil {
return fmt.Errorf("populate key agreements failed: %w", err)
}
doc.KeyAgreement = keyAgreements
return nil
}
func populateProofs(context, didID, baseURI string, rawProofs []interface{}) ([]Proof, error) {
proofs := make([]Proof, 0, len(rawProofs))
for _, rawProof := range rawProofs {
emap, ok := rawProof.(map[string]interface{})
if !ok {
return nil, errors.New("rawProofs is not map[string]interface{}")
}
created := stringEntry(emap[jsonldCreated])
timeValue, err := time.Parse(time.RFC3339, created)
if err != nil {
return nil, err
}
proofKey := jsonldProofValue
if context == contextV011 {
proofKey = jsonldSignatureValue
}
proofValue, err := sigproof.DecodeProofValue(stringEntry(emap[proofKey]), stringEntry(emap[jsonldType]))
if err != nil {
return nil, errors.New("unsupported encoding")
}
nonce, err := base64.RawURLEncoding.DecodeString(stringEntry(emap[jsonldNonce]))
if err != nil {
return nil, err
}
creator := stringEntry(emap[jsonldCreator])
isRelative := false
if strings.HasPrefix(creator, "#") {
creator = resolveRelativeDIDURL(didID, baseURI, creator)
isRelative = true
}
proof := Proof{
Type: stringEntry(emap[jsonldType]),
Created: &timeValue,
Creator: creator,
ProofValue: proofValue,
ProofPurpose: stringEntry(emap[jsonldProofPurpose]),
Domain: stringEntry(emap[jsonldDomain]),
Nonce: nonce,
relativeURL: isRelative,
}
proofs = append(proofs, proof)
}
return proofs, nil
}
//nolint:funlen,gocyclo
func populateServices(didID, baseURI string, rawServices []map[string]interface{}) []Service {
services := make([]Service, 0, len(rawServices))
for _, rawService := range rawServices {
id := stringEntry(rawService[jsonldID])
recipientKeys := stringArray(rawService[jsonldRecipientKeys])
routingKeys := stringArray(rawService[jsonldRoutingKeys]) // routingkeys here for DIDComm V1 only.
var recipientKeysRelativeURL map[string]bool
var routingKeysRelativeURL map[string]bool
isRelative := false
if strings.HasPrefix(id, "#") {
id = resolveRelativeDIDURL(didID, baseURI, id)
isRelative = true
}
if len(recipientKeys) != 0 {
recipientKeys, recipientKeysRelativeURL = populateKeys(recipientKeys, didID, baseURI)
}
if len(routingKeys) != 0 {
routingKeys, routingKeysRelativeURL = populateKeys(routingKeys, didID, baseURI)
}
var sp model.Endpoint
//nolint:nestif
if epEntry, ok := rawService[jsonldServicePoint]; ok {
uriStr, ok := epEntry.(string)
// for now handling DIDComm V1 or V2 only.
if ok { // DIDComm V1 format.
sp = model.NewDIDCommV1Endpoint(uriStr)
} else if epEntry != nil { // DIDComm V2 format (first valid entry for now).
entries, ok := epEntry.([]interface{})
if ok && len(entries) > 0 {
firstEntry, is := entries[0].(map[string]interface{})
if is {
epURI := stringEntry(firstEntry["uri"])
epAccept := stringArray(firstEntry["accept"])
epRoutingKeys := stringArray(firstEntry["routingKeys"])
sp = model.NewDIDCommV2Endpoint([]model.DIDCommV2Endpoint{
{URI: epURI, Accept: epAccept, RoutingKeys: epRoutingKeys},
})
}
}
coreServices, ok := epEntry.(map[string]interface{}) // DID Core
if ok && len(coreServices) > 0 {
sp = model.NewDIDCoreEndpoint(coreServices)
}
}
}
service := Service{
ID: id,
Type: rawService[jsonldType],
relativeURL: isRelative,
ServiceEndpoint: sp,
RecipientKeys: recipientKeys,
Priority: rawService[jsonldPriority],
RoutingKeys: routingKeys,
recipientKeysRelativeURL: recipientKeysRelativeURL,
routingKeysRelativeURL: routingKeysRelativeURL,
}
delete(rawService, jsonldID)
delete(rawService, jsonldType)
delete(rawService, jsonldServicePoint)
delete(rawService, jsonldRecipientKeys)
delete(rawService, jsonldRoutingKeys)
delete(rawService, jsonldPriority)
service.Properties = rawService
services = append(services, service)
}
return services
}
func populateKeys(keys []string, didID, baseURI string) ([]string, map[string]bool) {
values := make([]string, 0)
keysRelativeURL := make(map[string]bool)
for _, v := range keys {
if strings.HasPrefix(v, "#") {
id := resolveRelativeDIDURL(didID, baseURI, v)
values = append(values, id)
keysRelativeURL[id] = true
continue
}
keysRelativeURL[v] = false
values = append(values, v)
}
return values, keysRelativeURL
}
func populateVerification(doc *Doc, rawVerification []interface{},
relationship VerificationRelationship) ([]Verification, error) {
var vms []Verification
for _, rawVerification := range rawVerification {
v, err := getVerification(doc, rawVerification, relationship)
if err != nil {
return nil, err
}
vms = append(vms, v...)
}
return vms, nil
}
// getVerification gets verification from raw data.
func getVerification(doc *Doc, rawVerification interface{},
relationship VerificationRelationship) ([]Verification, error) {
// context, docID string
vm := doc.VerificationMethod
context, _ := ContextPeekString(doc.Context)
keyID, keyIDExist := rawVerification.(string)
if keyIDExist {
return getVerificationsByKeyID(doc.ID, doc.processingMeta.baseURI, vm, relationship, keyID)
}
m, ok := rawVerification.(map[string]interface{})
if !ok {
return nil, errors.New("rawVerification is not map[string]interface{}")
}
if context == contextV011 {
keyID, keyIDExist = m[jsonldPublicKey].(string)
if keyIDExist {
return getVerificationsByKeyID(doc.ID, doc.processingMeta.baseURI, vm, relationship, keyID)
}
}
if context == contextV12019 {
keyIDs, keyIDsExist := m[jsonldPublicKey].([]interface{})
if keyIDsExist {
return getVerificationsByKeyID(doc.ID, doc.processingMeta.baseURI, vm, relationship, keyIDs...)
}
}
pk, err := populateVerificationMethod(context, doc.ID, doc.processingMeta.baseURI, []map[string]interface{}{m})
if err != nil {
return nil, err
}
return []Verification{{VerificationMethod: pk[0], Relationship: relationship, Embedded: true}}, nil
}
// getVerificationsByKeyID get verification methods by key IDs.
func getVerificationsByKeyID(didID, baseURI string, vm []VerificationMethod, relationship VerificationRelationship,
keyIDs ...interface{}) ([]Verification, error) {
var vms []Verification
for _, keyID := range keyIDs {
keyExist := false
if keyID == "" {
continue
}
for _, v := range vm {
if v.ID == keyID || v.ID == resolveRelativeDIDURL(didID, baseURI, keyID) {
vms = append(vms, Verification{VerificationMethod: v, Relationship: relationship})
keyExist = true
break
}
}
if !keyExist {
return nil, fmt.Errorf("key %s does not exist in did doc verification method", keyID)
}
}
return vms, nil
}
func resolveRelativeDIDURL(didID, baseURI string, keyID interface{}) string {
id := baseURI
if id == "" {
id = didID
}
return id + keyID.(string)
}
func makeRelativeDIDURL(didURL, baseURI, didID string) string {
id := baseURI
if id == "" {
id = didID
}
return strings.Replace(didURL, id, "", 1)
}
func populateVerificationMethod(context, didID, baseURI string,
rawVM []map[string]interface{}) ([]VerificationMethod, error) {
var verificationMethods []VerificationMethod
for _, v := range rawVM {
controllerKey := jsonldController
if context == contextV011 {
controllerKey = jsonldOwner
}
id := stringEntry(v[jsonldID])
controller := stringEntry(v[controllerKey])
isRelative := false
if strings.HasPrefix(id, "#") {
id = resolveRelativeDIDURL(didID, baseURI, id)
split := strings.Split(id, "#")
controller = split[0]
isRelative = true
}
vm := VerificationMethod{
ID: id, Type: stringEntry(v[jsonldType]),
Controller: controller,
relativeURL: isRelative,
}
err := decodeVM(&vm, v)
if err != nil {
return nil, err
}
verificationMethods = append(verificationMethods, vm)
}
return verificationMethods, nil
}
func decodeVM(vm *VerificationMethod, rawPK map[string]interface{}) error {
if stringEntry(rawPK[jsonldPublicKeyBase58]) != "" {
vm.Value = base58.Decode(stringEntry(rawPK[jsonldPublicKeyBase58]))
return nil
}
if stringEntry(rawPK[jsonldPublicKeyMultibase]) != "" {
multibaseEncoding, value, err := multibase.Decode(stringEntry(rawPK[jsonldPublicKeyMultibase]))
if err != nil {
return err
}
vm.Value = value
vm.multibaseEncoding = multibaseEncoding
return nil
}
if stringEntry(rawPK[jsonldPublicKeyHex]) != "" {
value, err := hex.DecodeString(stringEntry(rawPK[jsonldPublicKeyHex]))
if err != nil {
return fmt.Errorf("decode public key hex failed: %w", err)
}
vm.Value = value
return nil
}
if stringEntry(rawPK[jsonldPublicKeyPem]) != "" {
block, _ := pem.Decode([]byte(stringEntry(rawPK[jsonldPublicKeyPem])))
if block == nil {
return errors.New("failed to decode PEM block containing public key")
}
vm.Value = block.Bytes
return nil
}
if jwkMap := mapEntry(rawPK[jsonldPublicKeyjwk]); jwkMap != nil {
return decodeVMJwk(jwkMap, vm)
}
return errors.New("public key encoding not supported")
}
func decodeVMJwk(jwkMap map[string]interface{}, vm *VerificationMethod) error {
jwkBytes, err := json.Marshal(jwkMap)
if err != nil {
return fmt.Errorf("failed to marshal '%s', cause: %w ", jsonldPublicKeyjwk, err)
}
if string(jwkBytes) == "{}" {
vm.Value = []byte("")
return nil
}
var j jwk.JWK
err = json.Unmarshal(jwkBytes, &j)
if err != nil {
return fmt.Errorf("unmarshal JWK: %w", err)
}
pkBytes, err := j.PublicKeyBytes()
if err != nil {
return fmt.Errorf("failed to decode public key from JWK: %w", err)
}
vm.Value = pkBytes
vm.jsonWebKey = &j
return nil
}
func parseContext(context Context) (Context, string) {
context = ContextCopy(context)
switch ctx := context.(type) {
case string, []string:
return ctx, ""
case []interface{}:
// copy slice to prevent unexpected mutation
var newContext []interface{}
var base string
for _, v := range ctx {
switch value := v.(type) {
case string:
newContext = append(newContext, value)
case map[string]interface{}:
// preserve base value if it exists and is a string
if baseValue, ok := value["@base"].(string); ok {
base = baseValue
}
delete(value, "@base")
if len(value) > 0 {
newContext = append(newContext, value)
}
}