forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpresentation.go
627 lines (533 loc) · 15.9 KB
/
presentation.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package verifiable
import (
"encoding/json"
"errors"
"fmt"
"github.com/piprate/json-gold/ld"
"github.com/xeipuuv/gojsonschema"
"github.com/hyperledger/aries-framework-go/pkg/doc/jose"
"github.com/hyperledger/aries-framework-go/pkg/doc/jwt"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/verifier"
)
const basePresentationSchema = `
{
"required": [
"@context",
"type"
],
"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": "^VerifiablePresentation$"
}
},
{
"type": "string",
"pattern": "^VerifiablePresentation$"
}
]
},
"verifiableCredential": {
"anyOf": [
{
"type": "array"
},
{
"type": "object"
},
{
"type": "string"
},
{
"type": "null"
}
]
},
"holder": {
"type": "string",
"format": "uri"
},
"proof": {
"anyOf": [
{
"type": "array",
"items": [
{
"$ref": "#/definitions/proof"
}
]
},
{
"$ref": "#/definitions/proof"
}
]
},
"refreshService": {
"$ref": "#/definitions/typedID"
}
},
"definitions": {
"typedID": {
"type": "object",
"required": [
"id",
"type"
],
"properties": {
"id": {
"type": "string",
"format": "uri"
},
"type": {
"anyOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
}
}
},
"proof": {
"type": "object",
"required": [
"type"
],
"properties": {
"type": {
"type": "string"
}
}
}
}
}
`
//nolint:gochecknoglobals
var basePresentationSchemaLoader = gojsonschema.NewStringLoader(basePresentationSchema)
// MarshalledCredential defines marshalled Verifiable Credential enclosed into Presentation.
// MarshalledCredential can be passed to verifiable.ParseCredential().
type MarshalledCredential []byte
// CreatePresentationOpt are options for creating a new presentation.
type CreatePresentationOpt func(p *Presentation) error
// Presentation Verifiable Presentation base data model definition.
type Presentation struct {
Context []string
CustomContext []interface{}
ID string
Type []string
credentials []interface{}
Holder string
Proofs []Proof
CustomFields CustomFields
}
// NewPresentation creates a new Presentation with default context and type with the provided credentials.
func NewPresentation(opts ...CreatePresentationOpt) (*Presentation, error) {
p := Presentation{
Context: []string{baseContext},
Type: []string{vpType},
credentials: []interface{}{},
}
for _, o := range opts {
err := o(&p)
if err != nil {
return nil, err
}
}
return &p, nil
}
// WithCredentials sets the provided credentials into the presentation.
func WithCredentials(cs ...*Credential) CreatePresentationOpt {
return func(p *Presentation) error {
for _, c := range cs {
p.credentials = append(p.credentials, c)
}
return nil
}
}
// WithJWTCredentials sets the provided base64url encoded JWT credentials into the presentation.
func WithJWTCredentials(cs ...string) CreatePresentationOpt {
return func(p *Presentation) error {
for _, c := range cs {
if !jose.IsCompactJWS(c) {
return errors.New("credential is not base64url encoded JWT")
}
p.credentials = append(p.credentials, c)
}
return nil
}
}
// MarshalJSON converts Verifiable Presentation to JSON bytes.
func (vp *Presentation) MarshalJSON() ([]byte, error) {
raw, err := vp.raw()
if err != nil {
return nil, fmt.Errorf("JSON marshalling of verifiable presentation: %w", err)
}
byteCred, err := json.Marshal(raw)
if err != nil {
return nil, fmt.Errorf("JSON marshalling of verifiable presentation: %w", err)
}
return byteCred, nil
}
// JWTClaims converts Verifiable Presentation into JWT Presentation claims, which can be than serialized
// e.g. into JWS.
func (vp *Presentation) JWTClaims(audience []string, minimizeVP bool) (*JWTPresClaims, error) {
return newJWTPresClaims(vp, audience, minimizeVP)
}
// Credentials returns current credentials of presentation.
func (vp *Presentation) Credentials() []interface{} {
return vp.credentials
}
// AddCredentials adds credentials to presentation.
func (vp *Presentation) AddCredentials(credentials ...*Credential) {
for _, credential := range credentials {
vp.credentials = append(vp.credentials, credential)
}
}
// MarshalledCredentials provides marshalled credentials enclosed into Presentation in raw byte array format.
// They can be used to decode Credentials into struct.
func (vp *Presentation) MarshalledCredentials() ([]MarshalledCredential, error) {
mCreds := make([]MarshalledCredential, len(vp.credentials))
for i := range vp.credentials {
cred := vp.credentials[i]
switch c := cred.(type) {
case string:
mCreds[i] = MarshalledCredential(c)
case []byte:
mCreds[i] = c
default:
credBytes, err := json.Marshal(cred)
if err != nil {
return nil, fmt.Errorf("marshal credentials from presentation: %w", err)
}
mCreds[i] = credBytes
}
}
return mCreds, nil
}
func (vp *Presentation) raw() (*rawPresentation, error) {
proof, err := proofsToRaw(vp.Proofs)
if err != nil {
return nil, err
}
return &rawPresentation{
// TODO single value contexts should be compacted as part of Issue [#1730]
// Not compacting now to support interoperability
Context: vp.Context,
ID: vp.ID,
Type: typesToRaw(vp.Type),
Credential: vp.credentials,
Holder: vp.Holder,
Proof: proof,
CustomFields: vp.CustomFields,
}, nil
}
// rawPresentation is a basic verifiable credential.
type rawPresentation struct {
Context interface{} `json:"@context,omitempty"`
ID string `json:"id,omitempty"`
Type interface{} `json:"type,omitempty"`
Credential interface{} `json:"verifiableCredential,omitempty"`
Holder string `json:"holder,omitempty"`
Proof json.RawMessage `json:"proof,omitempty"`
// All unmapped fields are put here.
CustomFields `json:"-"`
}
// MarshalJSON defines custom marshalling of rawPresentation to JSON.
func (rp *rawPresentation) MarshalJSON() ([]byte, error) {
type Alias rawPresentation
alias := (*Alias)(rp)
return marshalWithCustomFields(alias, rp.CustomFields)
}
// UnmarshalJSON defines custom unmarshalling of rawPresentation from JSON.
func (rp *rawPresentation) UnmarshalJSON(data []byte) error {
type Alias rawPresentation
alias := (*Alias)(rp)
rp.CustomFields = make(CustomFields)
err := unmarshalWithCustomFields(data, alias, rp.CustomFields)
if err != nil {
return err
}
return nil
}
// presentationOpts holds options for the Verifiable Presentation decoding.
type presentationOpts struct {
publicKeyFetcher PublicKeyFetcher
disabledProofCheck bool
ldpSuites []verifier.SignatureSuite
strictValidation bool
requireVC bool
requireProof bool
jsonldCredentialOpts
}
// PresentationOpt is the Verifiable Presentation decoding option.
type PresentationOpt func(opts *presentationOpts)
// WithPresPublicKeyFetcher indicates that Verifiable Presentation should be decoded from JWS using
// the public key fetcher.
func WithPresPublicKeyFetcher(fetcher PublicKeyFetcher) PresentationOpt {
return func(opts *presentationOpts) {
opts.publicKeyFetcher = fetcher
}
}
// WithPresEmbeddedSignatureSuites defines the suites which are used to check embedded linked data proof of VP.
func WithPresEmbeddedSignatureSuites(suites ...verifier.SignatureSuite) PresentationOpt {
return func(opts *presentationOpts) {
opts.ldpSuites = suites
}
}
// WithPresDisabledProofCheck option for disabling of proof check.
func WithPresDisabledProofCheck() PresentationOpt {
return func(opts *presentationOpts) {
opts.disabledProofCheck = true
}
}
// WithPresStrictValidation enabled strict JSON-LD validation of VP.
// In case of JSON-LD validation, the comparison of JSON-LD VP document after compaction with original VP one is made.
// In case of mismatch a validation exception is raised.
func WithPresStrictValidation() PresentationOpt {
return func(opts *presentationOpts) {
opts.strictValidation = true
}
}
// WithPresJSONLDDocumentLoader defines custom JSON-LD document loader. If not defined, when decoding VP
// a new document loader will be created using CachingJSONLDLoader() if JSON-LD validation is made.
func WithPresJSONLDDocumentLoader(documentLoader ld.DocumentLoader) PresentationOpt {
return func(opts *presentationOpts) {
opts.jsonldDocumentLoader = documentLoader
}
}
// ParsePresentation creates an instance of Verifiable Presentation by reading a JSON document from bytes.
// It also applies miscellaneous options like custom decoders or settings of schema validation.
func ParsePresentation(vpData []byte, opts ...PresentationOpt) (*Presentation, error) {
vpOpts := getPresentationOpts(opts)
vpDataDecoded, vpRaw, err := decodeRawPresentation(vpData, vpOpts)
if err != nil {
return nil, err
}
err = validateVP(vpDataDecoded, vpOpts)
if err != nil {
return nil, err
}
p, err := newPresentation(vpRaw, vpOpts)
if err != nil {
return nil, err
}
if vpOpts.requireVC && len(p.credentials) == 0 {
return nil, fmt.Errorf("verifiableCredential is required")
}
return p, nil
}
func getPresentationOpts(opts []PresentationOpt) *presentationOpts {
vpOpts := defaultPresentationOpts()
for _, opt := range opts {
opt(vpOpts)
}
return vpOpts
}
func newPresentation(vpRaw *rawPresentation, vpOpts *presentationOpts) (*Presentation, error) {
types, err := decodeType(vpRaw.Type)
if err != nil {
return nil, fmt.Errorf("fill presentation types from raw: %w", err)
}
context, customContext, err := decodeContext(vpRaw.Context)
if err != nil {
return nil, fmt.Errorf("fill presentation contexts from raw: %w", err)
}
creds, err := decodeCredentials(vpRaw.Credential, vpOpts)
if err != nil {
return nil, fmt.Errorf("decode credentials of presentation: %w", err)
}
proofs, err := parseProof(vpRaw.Proof)
if err != nil {
return nil, fmt.Errorf("fill credential proof from raw: %w", err)
}
return &Presentation{
Context: context,
CustomContext: customContext,
ID: vpRaw.ID,
Type: types,
credentials: creds,
Holder: vpRaw.Holder,
Proofs: proofs,
CustomFields: vpRaw.CustomFields,
}, nil
}
// decodeCredentials decodes credential(s) embedded into presentation.
// It must be one of the following:
// 1) string - it could be credential decoded into e.g. JWS.
// 2) the same as 1) but as array - e.g. zero ore more JWS
// 3) struct (should be map[string]interface{}) representing credential data model
// 4) the same as 3) but as array - i.e. zero or more credentials structs.
func decodeCredentials(rawCred interface{}, opts *presentationOpts) ([]interface{}, error) {
// Accept the case when VP does not have any VCs.
if rawCred == nil {
return nil, nil
}
marshalSingleCredFn := func(cred interface{}) (interface{}, error) {
// Check the case when VC is defined in string format (e.g. JWT).
// Decode credential and keep result of decoding.
if sCred, ok := cred.(string); ok {
bCred := []byte(sCred)
credDecoded, err := decodeRaw(bCred, mapOpts(opts))
if err != nil {
return nil, fmt.Errorf("decode credential of presentation: %w", err)
}
return credDecoded, nil
}
// return credential in a structure format as is
return cred, nil
}
switch cred := rawCred.(type) {
case []interface{}:
// Accept the case when VP does not have any VCs.
if len(cred) == 0 {
return nil, nil
}
// 1 or more credentials
creds := make([]interface{}, len(cred))
for i := range cred {
c, err := marshalSingleCredFn(cred[i])
if err != nil {
return nil, err
}
creds[i] = c
}
return creds, nil
default:
// single credential
c, err := marshalSingleCredFn(cred)
if err != nil {
return nil, err
}
return []interface{}{c}, nil
}
}
func mapOpts(vpOpts *presentationOpts) *credentialOpts {
return &credentialOpts{
publicKeyFetcher: vpOpts.publicKeyFetcher,
disabledProofCheck: vpOpts.disabledProofCheck,
ldpSuites: vpOpts.ldpSuites,
}
}
func validateVP(data []byte, opts *presentationOpts) error {
err := validateVPJSONSchema(data)
if err != nil {
return err
}
return validateVPJSONLD(data, opts)
}
func validateVPJSONLD(vpBytes []byte, opts *presentationOpts) error {
return compactJSONLD(string(vpBytes), &opts.jsonldCredentialOpts, opts.strictValidation)
}
func validateVPJSONSchema(data []byte) error {
loader := gojsonschema.NewStringLoader(string(data))
result, err := gojsonschema.Validate(basePresentationSchemaLoader, loader)
if err != nil {
return fmt.Errorf("validation of verifiable credential: %w", err)
}
if !result.Valid() {
errMsg := describeSchemaValidationError(result, "verifiable presentation")
return errors.New(errMsg)
}
return nil
}
//nolint:gocyclo
func decodeRawPresentation(vpData []byte, vpOpts *presentationOpts) ([]byte, *rawPresentation, error) {
vpStr := string(vpData)
if jwt.IsJWS(vpStr) {
if vpOpts.publicKeyFetcher == nil {
return nil, nil, errors.New("public key fetcher is not defined")
}
vcDataFromJwt, rawCred, err := decodeVPFromJWS(vpStr, !vpOpts.disabledProofCheck, vpOpts.publicKeyFetcher)
if err != nil {
return nil, nil, fmt.Errorf("decoding of Verifiable Presentation from JWS: %w", err)
}
return vcDataFromJwt, rawCred, nil
}
embeddedProofCheckOpts := &embeddedProofCheckOpts{
publicKeyFetcher: vpOpts.publicKeyFetcher,
disabledProofCheck: vpOpts.disabledProofCheck,
ldpSuites: vpOpts.ldpSuites,
jsonldCredentialOpts: vpOpts.jsonldCredentialOpts,
}
if jwt.IsJWTUnsecured(vpStr) {
rawBytes, rawPres, err := decodeVPFromUnsecuredJWT(vpStr)
if err != nil {
return nil, nil, fmt.Errorf("decoding of Verifiable Presentation from unsecured JWT: %w", err)
}
if _, err := checkEmbeddedProof(rawBytes, embeddedProofCheckOpts); err != nil {
return nil, nil, err
}
return rawBytes, rawPres, nil
}
vpBytes, vpRaw, err := decodeVPFromJSON(vpData)
if err != nil {
return nil, nil, err
}
_, err = checkEmbeddedProof(vpBytes, embeddedProofCheckOpts)
if err != nil {
return nil, nil, err
}
// check that embedded proof is present, if not, it's not a verifiable presentation
if vpOpts.requireProof && vpRaw.Proof == nil {
return nil, nil, errors.New("embedded proof is missing")
}
return vpBytes, vpRaw, err
}
func decodeVPFromJSON(vpData []byte) ([]byte, *rawPresentation, error) {
// unmarshal VP from JSON
raw := new(rawPresentation)
err := json.Unmarshal(vpData, raw)
if err != nil {
return nil, nil, fmt.Errorf("JSON unmarshalling of verifiable presentation: %w", err)
}
return vpData, raw, nil
}
func defaultPresentationOpts() *presentationOpts {
return &presentationOpts{}
}