forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcredential.go
1425 lines (1173 loc) · 36.4 KB
/
credential.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 verifiable
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"time"
"github.com/piprate/json-gold/ld"
"github.com/xeipuuv/gojsonschema"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
"github.com/hyperledger/aries-framework-go/pkg/doc/jwt"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/verifier"
"github.com/hyperledger/aries-framework-go/pkg/doc/util"
)
var logger = log.New("aries-framework/doc/verifiable")
// DefaultSchema describes default schema.
const DefaultSchema = `{
"required": [
"@context",
"type",
"credentialSubject",
"issuer",
"issuanceDate"
],
"properties": {
"@context": {
"oneOf": [
{
"type": "string",
"const": "https://www.w3.org/2018/credentials/v1"
},
{
"type": "array",
"items": [
{
"type": "string",
"const": "https://www.w3.org/2018/credentials/v1"
}
],
"uniqueItems": true,
"additionalItems": {
"oneOf": [
{
"type": "object"
},
{
"type": "string"
}
]
}
}
]
},
"id": {
"type": "string",
"format": "uri"
},
"type": {
"oneOf": [
{
"type": "array",
"minItems": 1,
"contains": {
"type": "string",
"pattern": "^VerifiableCredential$"
}
},
{
"type": "string",
"pattern": "^VerifiableCredential$"
}
]
},
"credentialSubject": {
"anyOf": [
{
"type": "array"
},
{
"type": "object"
},
{
"type": "string"
}
]
},
"issuer": {
"anyOf": [
{
"type": "string",
"format": "uri"
},
{
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"format": "uri"
}
}
}
]
},
"issuanceDate": {
"type": "string",
"format": "date-time"
},
"proof": {
"anyOf": [
{
"$ref": "#/definitions/proof"
},
{
"type": "array",
"items": {
"$ref": "#/definitions/proof"
}
},
{
"type": "null"
}
]
},
"expirationDate": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"credentialStatus": {
"$ref": "#/definitions/typedID"
},
"credentialSchema": {
"$ref": "#/definitions/typedIDs"
},
"evidence": {
"$ref": "#/definitions/typedIDs"
},
"refreshService": {
"$ref": "#/definitions/typedID"
}
},
"definitions": {
"typedID": {
"anyOf": [
{
"type": "null"
},
{
"type": "object",
"required": [
"id",
"type"
],
"properties": {
"id": {
"type": "string",
"format": "uri"
},
"type": {
"anyOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
}
}
}
]
},
"typedIDs": {
"anyOf": [
{
"$ref": "#/definitions/typedID"
},
{
"type": "array",
"items": {
"$ref": "#/definitions/typedID"
}
},
{
"type": "null"
}
]
},
"proof": {
"type": "object",
"required": [
"type"
],
"properties": {
"type": {
"type": "string"
}
}
}
}
}
`
// https://www.w3.org/TR/vc-data-model/#data-schemas
const jsonSchema2018Type = "JsonSchemaValidator2018"
const (
// https://www.w3.org/TR/vc-data-model/#base-context
baseContext = "https://www.w3.org/2018/credentials/v1"
// https://www.w3.org/TR/vc-data-model/#types
vcType = "VerifiableCredential"
// https://www.w3.org/TR/vc-data-model/#presentations-0
vpType = "VerifiablePresentation"
)
// vcModelValidationMode defines constraint put on context and type of VC.
type vcModelValidationMode int
const (
// combinedValidation when set it makes JSON validation using JSON Schema and JSON-LD validation.
//
// JSON validation verifies the format of the fields and the presence of
// mandatory fields. It can also decline VC with field(s) not defined in the schema if
// additionalProperties=true is configured in that schema. To enable such check for base JSON schema, use
// WithStrictValidation() option.
//
// JSON-LD validation is applied when there is more than one (base) context defined. In this case,
// JSON-LD parser can load machine-readable vocabularies used to describe information in the data model.
// In JSON-LD schemas, it's not possible to define custom mandatory fields. A possibility to decline
// JSON document with field(s) not defined in any of JSON-LD schema is built on top of JSON-LD parser and is
// enabled using WithStrictValidation().
//
// This is a default validation mode.
combinedValidation vcModelValidationMode = iota
// jsonldValidation when set it uses JSON-LD parser for validation.
jsonldValidation
// baseContextValidation when defined it's validated that only the fields and values (when applicable)
// are present in the document. No extra fields are allowed (outside of credentialSubject).
baseContextValidation
// baseContextExtendedValidation when set it's validated that fields that are specified in base context are
// as specified. Additional fields are allowed.
baseContextExtendedValidation
)
// SchemaCache defines a cache of credential schemas.
type SchemaCache interface {
// Put element to the cache.
Put(k string, v []byte)
// Get element from the cache, returns false at second return value if element is not present.
Get(k string) ([]byte, bool)
}
// cache defines a cache interface.
type cache interface {
Set(k, v []byte)
HasGet(dst, k []byte) ([]byte, bool)
Del(k []byte)
}
// ExpirableSchemaCache is an implementation of SchemaCache based fastcache.Cache with expirable elements.
type ExpirableSchemaCache struct {
cache cache
expiration time.Duration
}
// CredentialSchemaLoader defines expirable cache.
type CredentialSchemaLoader struct {
schemaDownloadClient *http.Client
cache SchemaCache
jsonLoader gojsonschema.JSONLoader
}
// CredentialSchemaLoaderBuilder defines a builder of CredentialSchemaLoader.
type CredentialSchemaLoaderBuilder struct {
loader *CredentialSchemaLoader
}
// NewCredentialSchemaLoaderBuilder creates a new instance of CredentialSchemaLoaderBuilder.
func NewCredentialSchemaLoaderBuilder() *CredentialSchemaLoaderBuilder {
return &CredentialSchemaLoaderBuilder{
loader: &CredentialSchemaLoader{},
}
}
// SetSchemaDownloadClient sets HTTP client to be used to download the schema.
func (b *CredentialSchemaLoaderBuilder) SetSchemaDownloadClient(client *http.Client) *CredentialSchemaLoaderBuilder {
b.loader.schemaDownloadClient = client
return b
}
// SetCache defines SchemaCache.
func (b *CredentialSchemaLoaderBuilder) SetCache(cache SchemaCache) *CredentialSchemaLoaderBuilder {
b.loader.cache = cache
return b
}
// SetJSONLoader defines gojsonschema.JSONLoader.
func (b *CredentialSchemaLoaderBuilder) SetJSONLoader(loader gojsonschema.JSONLoader) *CredentialSchemaLoaderBuilder {
b.loader.jsonLoader = loader
return b
}
// Build constructed CredentialSchemaLoader.
// It creates default HTTP client and JSON schema loader if not defined.
func (b *CredentialSchemaLoaderBuilder) Build() *CredentialSchemaLoader {
l := b.loader
if l.schemaDownloadClient == nil {
l.schemaDownloadClient = &http.Client{}
}
if l.jsonLoader == nil {
l.jsonLoader = defaultSchemaLoader()
}
return l
}
// Put element to the cache. It also adds a mark of when the element will expire.
func (sc *ExpirableSchemaCache) Put(k string, v []byte) {
expires := time.Now().Add(sc.expiration).Unix()
const numBytesTime = 8
b := make([]byte, numBytesTime)
binary.LittleEndian.PutUint64(b, uint64(expires))
ve := make([]byte, numBytesTime+len(v))
copy(ve[:numBytesTime], b)
copy(ve[numBytesTime:], v)
sc.cache.Set([]byte(k), ve)
}
// Get element from the cache. If element is present, it checks if the element is expired.
// If yes, it clears the element from the cache and indicates that the key is not found.
func (sc *ExpirableSchemaCache) Get(k string) ([]byte, bool) {
b, ok := sc.cache.HasGet(nil, []byte(k))
if !ok {
return nil, false
}
const numBytesTime = 8
expires := int64(binary.LittleEndian.Uint64(b[:numBytesTime]))
if expires < time.Now().Unix() {
// cache expires
sc.cache.Del([]byte(k))
return nil, false
}
return b[numBytesTime:], true
}
// Evidence defines evidence of Verifiable Credential.
type Evidence interface{}
// Issuer of the Verifiable Credential.
type Issuer struct {
ID string `json:"id,omitempty"`
CustomFields CustomFields `json:"-"`
}
// MarshalJSON marshals Issuer to JSON.
func (i *Issuer) MarshalJSON() ([]byte, error) {
if len(i.CustomFields) == 0 {
// as string
return json.Marshal(i.ID)
}
// as object
type Alias Issuer
alias := Alias(*i)
data, err := marshalWithCustomFields(alias, i.CustomFields)
if err != nil {
return nil, fmt.Errorf("marshal Issuer: %w", err)
}
return data, nil
}
// UnmarshalJSON unmarshals issuer from JSON.
func (i *Issuer) UnmarshalJSON(bytes []byte) error {
var issuerID string
if err := json.Unmarshal(bytes, &issuerID); err == nil {
// as string
i.ID = issuerID
return nil
}
// as object
type Alias Issuer
alias := (*Alias)(i)
i.CustomFields = make(CustomFields)
err := unmarshalWithCustomFields(bytes, alias, i.CustomFields)
if err != nil {
return fmt.Errorf("unmarshal Issuer: %w", err)
}
if i.ID == "" {
return errors.New("issuer ID is not defined")
}
return nil
}
// Subject of the Verifiable Credential.
type Subject struct {
ID string `json:"id,omitempty"`
CustomFields CustomFields `json:"-"`
}
// MarshalJSON marshals Subject to JSON.
func (s *Subject) MarshalJSON() ([]byte, error) {
if len(s.CustomFields) == 0 {
// Subject ID as string
return json.Marshal(s.ID)
}
type Alias Subject
alias := Alias(*s)
data, err := marshalWithCustomFields(alias, s.CustomFields)
if err != nil {
return nil, fmt.Errorf("marshal Subject: %w", err)
}
return data, nil
}
// UnmarshalJSON unmarshals Subject from JSON.
func (s *Subject) UnmarshalJSON(bytes []byte) error {
var subjectID string
if err := json.Unmarshal(bytes, &subjectID); err == nil {
// as string
s.ID = subjectID
return nil
}
type Alias Subject
alias := (*Alias)(s)
s.CustomFields = make(CustomFields)
err := unmarshalWithCustomFields(bytes, alias, s.CustomFields)
if err != nil {
return fmt.Errorf("unmarshal Subject: %w", err)
}
return nil
}
// Credential Verifiable Credential definition.
type Credential struct {
Context []string
CustomContext []interface{}
ID string
Types []string
// Subject can be a string, map, slice of maps, struct (Subject or any custom), slice of structs.
Subject interface{}
Issuer Issuer
Issued *util.TimeWithTrailingZeroMsec
Expired *util.TimeWithTrailingZeroMsec
Proofs []Proof
Status *TypedID
Schemas []TypedID
Evidence Evidence
TermsOfUse []TypedID
RefreshService []TypedID
CustomFields CustomFields
}
// rawCredential is a basic verifiable credential.
type rawCredential struct {
Context interface{} `json:"@context,omitempty"`
ID string `json:"id,omitempty"`
Type interface{} `json:"type,omitempty"`
Subject json.RawMessage `json:"credentialSubject,omitempty"`
Issued *util.TimeWithTrailingZeroMsec `json:"issuanceDate,omitempty"`
Expired *util.TimeWithTrailingZeroMsec `json:"expirationDate,omitempty"`
Proof json.RawMessage `json:"proof,omitempty"`
Status *TypedID `json:"credentialStatus,omitempty"`
Issuer json.RawMessage `json:"issuer,omitempty"`
Schema interface{} `json:"credentialSchema,omitempty"`
Evidence Evidence `json:"evidence,omitempty"`
TermsOfUse json.RawMessage `json:"termsOfUse,omitempty"`
RefreshService json.RawMessage `json:"refreshService,omitempty"`
// All unmapped fields are put here.
CustomFields `json:"-"`
}
// MarshalJSON defines custom marshalling of rawCredential to JSON.
func (rc *rawCredential) MarshalJSON() ([]byte, error) {
type Alias rawCredential
alias := (*Alias)(rc)
return marshalWithCustomFields(alias, rc.CustomFields)
}
// UnmarshalJSON defines custom unmarshalling of rawCredential from JSON.
func (rc *rawCredential) UnmarshalJSON(data []byte) error {
type Alias rawCredential
alias := (*Alias)(rc)
rc.CustomFields = make(CustomFields)
err := unmarshalWithCustomFields(data, alias, rc.CustomFields)
if err != nil {
return err
}
return nil
}
// CredentialDecoder makes a custom decoding of Verifiable Credential in JSON form to existent
// instance of Credential.
type CredentialDecoder func(dataJSON []byte, vc *Credential) error
// CredentialTemplate defines a factory method to create new Credential template.
type CredentialTemplate func() *Credential
// credentialOpts holds options for the Verifiable Credential decoding.
type credentialOpts struct {
publicKeyFetcher PublicKeyFetcher
disabledCustomSchema bool
schemaLoader *CredentialSchemaLoader
modelValidationMode vcModelValidationMode
allowedCustomContexts map[string]bool
allowedCustomTypes map[string]bool
disabledProofCheck bool
strictValidation bool
ldpSuites []verifier.SignatureSuite
jsonldCredentialOpts
}
// CredentialOpt is the Verifiable Credential decoding option.
type CredentialOpt func(opts *credentialOpts)
// WithDisabledProofCheck option for disabling of proof check.
func WithDisabledProofCheck() CredentialOpt {
return func(opts *credentialOpts) {
opts.disabledProofCheck = true
}
}
// WithNoCustomSchemaCheck option is for disabling of Credential Schemas download if defined
// in Verifiable Credential. Instead, the Verifiable Credential is checked against default Schema.
func WithNoCustomSchemaCheck() CredentialOpt {
return func(opts *credentialOpts) {
opts.disabledCustomSchema = true
}
}
// WithPublicKeyFetcher set public key fetcher used when decoding from JWS.
func WithPublicKeyFetcher(fetcher PublicKeyFetcher) CredentialOpt {
return func(opts *credentialOpts) {
opts.publicKeyFetcher = fetcher
}
}
// WithCredentialSchemaLoader option is used to define custom credentials schema loader.
// If not defined, the default one is created with default HTTP client to download the schema
// and no caching of the schemas.
func WithCredentialSchemaLoader(loader *CredentialSchemaLoader) CredentialOpt {
return func(opts *credentialOpts) {
opts.schemaLoader = loader
}
}
// WithJSONLDValidation uses the JSON LD parser for validation.
func WithJSONLDValidation() CredentialOpt {
return func(opts *credentialOpts) {
opts.modelValidationMode = jsonldValidation
}
}
// WithBaseContextValidation validates that only the fields and values (when applicable) are present
// in the document. No extra fields are allowed (outside of credentialSubject).
func WithBaseContextValidation() CredentialOpt {
return func(opts *credentialOpts) {
opts.modelValidationMode = baseContextValidation
}
}
// WithBaseContextExtendedValidation validates that fields that are specified in base context are as specified.
// Additional fields are allowed.
func WithBaseContextExtendedValidation(customContexts, customTypes []string) CredentialOpt {
return func(opts *credentialOpts) {
opts.modelValidationMode = baseContextExtendedValidation
opts.allowedCustomContexts = make(map[string]bool)
for _, context := range customContexts {
opts.allowedCustomContexts[context] = true
}
opts.allowedCustomContexts[baseContext] = true
opts.allowedCustomTypes = make(map[string]bool)
for _, context := range customTypes {
opts.allowedCustomTypes[context] = true
}
opts.allowedCustomTypes[vcType] = true
}
}
// WithJSONLDDocumentLoader defines a JSON-LD document loader.
func WithJSONLDDocumentLoader(documentLoader ld.DocumentLoader) CredentialOpt {
return func(opts *credentialOpts) {
opts.jsonldDocumentLoader = documentLoader
}
}
// WithStrictValidation enabled strict validation of VC.
//
// In case of JSON Schema validation, additionalProperties=true is set on the schema.
//
// In case of JSON-LD validation, the comparison of JSON-LD VC document after compaction with original VC one is made.
// In case of mismatch a validation exception is raised.
func WithStrictValidation() CredentialOpt {
return func(opts *credentialOpts) {
opts.strictValidation = true
}
}
// WithExternalJSONLDContext defines external JSON-LD contexts to be used in JSON-LD validation and
// Linked Data Signatures verification.
func WithExternalJSONLDContext(context ...string) CredentialOpt {
return func(opts *credentialOpts) {
opts.externalContext = context
}
}
// WithJSONLDOnlyValidRDF indicates the need to remove all invalid RDF dataset from normalize document
// when verifying linked data signatures of verifiable credential.
func WithJSONLDOnlyValidRDF() CredentialOpt {
return func(opts *credentialOpts) {
opts.jsonldOnlyValidRDF = true
}
}
// WithEmbeddedSignatureSuites defines the suites which are used to check embedded linked data proof of VC.
func WithEmbeddedSignatureSuites(suites ...verifier.SignatureSuite) CredentialOpt {
return func(opts *credentialOpts) {
opts.ldpSuites = suites
}
}
// parseIssuer parses raw issuer.
//
// Issuer can be defined by:
//
// - a string which is ID of the issuer;
//
// - object with mandatory "id" field and optional "name" field.
func parseIssuer(issuerBytes json.RawMessage) (Issuer, error) {
if len(issuerBytes) == 0 {
return Issuer{}, nil
}
var issuer Issuer
err := json.Unmarshal(issuerBytes, &issuer)
if err != nil {
return Issuer{}, err
}
return issuer, err
}
// parseSubject parses raw credential subject.
//
// Subject can be defined as a string (subject ID) or single object or array of objects.
func parseSubject(subjectBytes json.RawMessage) ([]Subject, error) {
if len(subjectBytes) == 0 {
return nil, nil
}
var subjectID string
err := json.Unmarshal(subjectBytes, &subjectID)
if err == nil {
return []Subject{{
ID: subjectID,
CustomFields: make(CustomFields),
}}, nil
}
var subject Subject
err = json.Unmarshal(subjectBytes, &subject)
if err == nil {
return []Subject{subject}, nil
}
var subjects []Subject
err = json.Unmarshal(subjectBytes, &subjects)
if err == nil {
return subjects, nil
}
return nil, errors.New("verifiable credential subject of unsupported format")
}
// decodeCredentialSchemas decodes credential schema(s).
//
// credential schema can be defined as a single object or array of objects.
func decodeCredentialSchemas(data *rawCredential) ([]TypedID, error) {
switch schema := data.Schema.(type) {
case []interface{}:
tids := make([]TypedID, len(schema))
for i := range schema {
tid, err := newTypedID(schema[i])
if err != nil {
return nil, err
}
tids[i] = tid
}
return tids, nil
case interface{}:
tid, err := newTypedID(schema)
if err != nil {
return nil, err
}
return []TypedID{tid}, nil
default:
return nil, errors.New("verifiable credential schema of unsupported format")
}
}
// ParseCredential parses Verifiable Credential from bytes which could be marshalled JSON or serialized JWT.
// It also applies miscellaneous options like settings of schema validation.
// It returns decoded Credential.
func ParseCredential(vcData []byte, opts ...CredentialOpt) (*Credential, error) {
// Apply options.
vcOpts := getCredentialOpts(opts)
// Decode credential (e.g. from JWT).
vcDataDecoded, err := decodeRaw(vcData, vcOpts)
if err != nil {
return nil, fmt.Errorf("decode new credential: %w", err)
}
// Unmarshal raw credential from JSON.
var raw rawCredential
err = json.Unmarshal(vcDataDecoded, &raw)
if err != nil {
return nil, fmt.Errorf("unmarshal new credential: %w", err)
}
// Create credential from raw.
vc, err := newCredential(&raw)
if err != nil {
return nil, fmt.Errorf("build new credential: %w", err)
}
err = validateCredential(vc, vcDataDecoded, vcOpts)
if err != nil {
return nil, err
}
return vc, nil
}
func validateCredential(vc *Credential, vcBytes []byte, vcOpts *credentialOpts) error {
// Credential and type constraint.
switch vcOpts.modelValidationMode {
case combinedValidation:
// TODO Validation mechanism will be changed after completing of #968 and #976
// Validate VC using JSON schema. Even in case of VC data model extension (i.e. more than one @context
// is defined and thus JSON-LD validation is made), it's reasonable to do JSON Schema validation
// prior to the JSON-LD one as the former does not check several aspects like mandatory fields or fields format.
err := vc.validateJSONSchema(vcBytes, vcOpts)
if err != nil {
return err
}
return vc.validateJSONLD(vcBytes, vcOpts)
case jsonldValidation:
return vc.validateJSONLD(vcBytes, vcOpts)
case baseContextValidation:
return vc.validateBaseContext(vcBytes, vcOpts)
case baseContextExtendedValidation:
return vc.validateBaseContextWithExtendedValidation(vcOpts, vcBytes)
default:
return fmt.Errorf("unsupported vcModelValidationMode: %v", vcOpts.modelValidationMode)
}
}
func (vc *Credential) validateBaseContext(vcBytes []byte, vcOpts *credentialOpts) error {
if len(vc.Types) > 1 || vc.Types[0] != vcType {
return errors.New("violated type constraint: not base only type defined")
}
if len(vc.Context) > 1 || vc.Context[0] != baseContext {
return errors.New("violated @context constraint: not base only @context defined")
}
return vc.validateJSONSchema(vcBytes, vcOpts)
}
func (vc *Credential) validateBaseContextWithExtendedValidation(vcOpts *credentialOpts, vcBytes []byte) error {
for _, vcContext := range vc.Context {
if _, ok := vcOpts.allowedCustomContexts[vcContext]; !ok {
return fmt.Errorf("not allowed @context: %s", vcContext)
}
}
for _, vcType := range vc.Types {
if _, ok := vcOpts.allowedCustomTypes[vcType]; !ok {
return fmt.Errorf("not allowed type: %s", vcType)
}
}
return vc.validateJSONSchema(vcBytes, vcOpts)
}
func (vc *Credential) validateJSONLD(vcBytes []byte, vcOpts *credentialOpts) error {
return compactJSONLD(string(vcBytes), &vcOpts.jsonldCredentialOpts, vcOpts.strictValidation)
}
// CustomCredentialProducer is a factory for Credentials with extended data model.
type CustomCredentialProducer interface {
// Accept checks if producer is capable of building extended Credential data model.
Accept(vc *Credential) bool
// Apply creates custom credential using base credential and its JSON bytes.
Apply(vc *Credential, dataJSON []byte) (interface{}, error)
}
// CreateCustomCredential creates custom extended credentials from bytes which could be marshalled JSON
// or serialized JWT. It parses input bytes to the base Verifiable Credential using ParseCredential().
// It then checks all producers to find the capable one to build extended Credential data model.
// If none of producers accept the credential, the base credential is returned.
func CreateCustomCredential(vcData []byte, producers []CustomCredentialProducer,
opts ...CredentialOpt) (interface{}, error) {
vcBase, credErr := ParseCredential(vcData, opts...)
if credErr != nil {
return nil, fmt.Errorf("build base verifiable credential: %w", credErr)
}
vcBaseBytes, _ := vcBase.MarshalJSON() //nolint:errcheck
for _, p := range producers {
if p.Accept(vcBase) {
customCred, err := p.Apply(vcBase, vcBaseBytes)
if err != nil {
return nil, fmt.Errorf("build extended verifiable credential: %w", err)
}
return customCred, nil
}
}
// Return base credential as no producers are capable of VC extension.
return vcBase, nil
}
//nolint: funlen
func newCredential(raw *rawCredential) (*Credential, error) {
var schemas []TypedID
if raw.Schema != nil {
var err error
schemas, err = decodeCredentialSchemas(raw)
if err != nil {
return nil, fmt.Errorf("fill credential schemas from raw: %w", err)
}
} else {
schemas = make([]TypedID, 0)
}
types, err := decodeType(raw.Type)
if err != nil {
return nil, fmt.Errorf("fill credential types from raw: %w", err)
}
issuer, err := parseIssuer(raw.Issuer)
if err != nil {
return nil, fmt.Errorf("fill credential issuer from raw: %w", err)
}
context, customContext, err := decodeContext(raw.Context)
if err != nil {
return nil, fmt.Errorf("fill credential context from raw: %w", err)
}
termsOfUse, err := parseTypedID(raw.TermsOfUse)
if err != nil {
return nil, fmt.Errorf("fill credential terms of use from raw: %w", err)
}
refreshService, err := parseTypedID(raw.RefreshService)
if err != nil {
return nil, fmt.Errorf("fill credential refresh service from raw: %w", err)
}
proofs, err := parseProof(raw.Proof)
if err != nil {
return nil, fmt.Errorf("fill credential proof from raw: %w", err)
}
subjects, err := parseSubject(raw.Subject)
if err != nil {
return nil, fmt.Errorf("fill credential subject from raw: %w", err)
}
return &Credential{
Context: context,
CustomContext: customContext,
ID: raw.ID,
Types: types,
Subject: subjects,
Issuer: issuer,
Issued: raw.Issued,
Expired: raw.Expired,
Proofs: proofs,
Status: raw.Status,
Schemas: schemas,
Evidence: raw.Evidence,
TermsOfUse: termsOfUse,
RefreshService: refreshService,
CustomFields: raw.CustomFields,
}, nil
}
func parseTypedID(bytes json.RawMessage) ([]TypedID, error) {
if len(bytes) == 0 {
return nil, nil
}
var singleTypedID TypedID
err := json.Unmarshal(bytes, &singleTypedID)
if err == nil {
return []TypedID{singleTypedID}, nil
}
var composedTypedID []TypedID
err = json.Unmarshal(bytes, &composedTypedID)
if err == nil {