-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcommon.go
461 lines (375 loc) · 11 KB
/
common.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
Copyright Avast Software. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package verifiable implements Verifiable Credential and Presentation data model
// (https://www.w3.org/TR/vc-data-model).
// It provides the data structures and functions which allow to process the Verifiable documents on different
// sides and levels. For example, an Issuer can create verifiable.Credential structure and issue it to a
// Holder in JWS form. The Holder can decode received Credential and make sure the signature is valid.
// The Holder can present the Credential to the Verifier or combine one or more Credentials into a Verifiable
// Presentation. The Verifier can decode and verify the received Credentials and Presentations.
package verifiable
import (
"errors"
"fmt"
"strings"
"github.com/piprate/json-gold/ld"
util "github.com/trustbloc/did-go/doc/util/time"
"github.com/veraison/go-cose"
"github.com/xeipuuv/gojsonschema"
kmsapi "github.com/trustbloc/kms-go/spi/kms"
jsonutil "github.com/trustbloc/vc-go/util/json"
)
// JWSAlgorithm defines JWT signature algorithms of Verifiable Credential.
type JWSAlgorithm int
const (
// RS256 JWT Algorithm.
RS256 JWSAlgorithm = iota
// PS256 JWT Algorithm.
PS256
// EdDSA JWT Algorithm.
EdDSA
// ECDSASecp256k1 JWT Algorithm.
ECDSASecp256k1
// ECDSASecp256r1 JWT Algorithm.
ECDSASecp256r1
// ECDSASecp384r1 JWT Algorithm.
ECDSASecp384r1
// ECDSASecp521r1 JWT Algorithm.
ECDSASecp521r1
)
// KeyTypeToJWSAlgo returns the JWSAlgorithm based on keyType.
func KeyTypeToJWSAlgo(keyType kmsapi.KeyType) (JWSAlgorithm, error) {
switch keyType {
case kmsapi.ECDSAP256TypeDER, kmsapi.ECDSAP256TypeIEEEP1363:
return ECDSASecp256r1, nil
case kmsapi.ECDSAP384TypeDER, kmsapi.ECDSAP384TypeIEEEP1363:
return ECDSASecp384r1, nil
case kmsapi.ECDSAP521TypeDER, kmsapi.ECDSAP521TypeIEEEP1363:
return ECDSASecp521r1, nil
case kmsapi.ED25519Type:
return EdDSA, nil
case kmsapi.ECDSASecp256k1TypeIEEEP1363, kmsapi.ECDSASecp256k1DER:
return ECDSASecp256k1, nil
case kmsapi.RSARS256Type:
return RS256, nil
case kmsapi.RSAPS256Type:
return PS256, nil
default:
return 0, errors.New("unsupported key type")
}
}
// KeyTypeToCWSAlgo returns the cose.Algorithm based on keyType.
func KeyTypeToCWSAlgo(keyType kmsapi.KeyType) (cose.Algorithm, error) {
switch keyType {
case kmsapi.ECDSAP256TypeDER, kmsapi.ECDSAP256TypeIEEEP1363:
return cose.AlgorithmES256, nil
case kmsapi.ECDSAP384TypeDER, kmsapi.ECDSAP384TypeIEEEP1363:
return cose.AlgorithmES384, nil
case kmsapi.ED25519Type:
return cose.AlgorithmEdDSA, nil
case kmsapi.RSARS256Type:
return cose.AlgorithmRS256, nil
case kmsapi.RSAPS256Type:
return cose.AlgorithmPS256, nil
default:
return 0, errors.New("unsupported key type")
}
}
// Name return the name of the signature algorithm.
func (ja JWSAlgorithm) Name() (string, error) {
switch ja {
case RS256:
return "RS256", nil
case PS256:
return "PS256", nil
case EdDSA:
return "EdDSA", nil
case ECDSASecp256k1:
return "ES256K", nil
case ECDSASecp256r1:
return "ES256", nil
case ECDSASecp384r1:
return "ES384", nil
case ECDSASecp521r1:
return "ES521", nil
default:
return "", fmt.Errorf("unsupported algorithm: %v", ja)
}
}
type jsonldCredentialOpts struct {
jsonldDocumentLoader ld.DocumentLoader
externalContext []string
jsonldOnlyValidRDF bool
jsonldIncludeDetailedStructureDiffOnError bool
}
// Proof defines embedded proof of Verifiable Credential.
type Proof map[string]interface{}
// CustomFields is a map of extra fields of struct build when unmarshalling JSON which are not
// mapped to the struct fields.
type CustomFields map[string]interface{}
const (
jsonFldTypedIDID = "id"
jsonFldTypedIDType = "type"
jsonFldTypedURLType = "url"
)
// TypedID defines a flexible structure with id and name fields and arbitrary extra fields
// kept in CustomFields.
type TypedID struct {
ID string
Type string
CustomFields
}
func parseTypedIDObj(typedIDObj JSONObject) (TypedID, error) {
flds, rest := jsonutil.SplitJSONObj(typedIDObj, jsonFldTypedIDID, jsonFldTypedIDType)
id, err := parseStringFld(flds, jsonFldTypedIDID)
if err != nil {
return TypedID{}, fmt.Errorf("parse TypedID: %w", err)
}
typeName, err := parseStringFld(flds, jsonFldTypedIDType)
if err != nil {
return TypedID{}, fmt.Errorf("parse TypedID: %w", err)
}
return TypedID{
ID: id,
Type: typeName,
CustomFields: rest,
}, nil
}
func serializeTypedIDObj(typedID TypedID) JSONObject {
json := jsonutil.ShallowCopyObj(typedID.CustomFields)
json[jsonFldTypedIDID] = typedID.ID
json[jsonFldTypedIDType] = typedID.Type
return json
}
func newTypedIDArray(v interface{}) ([]*TypedID, error) {
if v == nil {
return nil, nil
}
// single object
obj, ok := v.(JSONObject)
if ok {
tid, err := parseTypedIDObj(obj)
if err != nil {
return nil, err
}
return []*TypedID{&tid}, nil
}
// array of objects
arr, ok := v.([]JSONObject)
if !ok {
rawArray, ok := v.([]interface{})
if !ok {
return nil, fmt.Errorf("should be array of json objects but got %v", v)
}
arr = make([]JSONObject, len(rawArray))
for i, raw := range rawArray {
obj, ok := raw.(JSONObject)
if !ok {
return nil, fmt.Errorf("should be json object but got %v", raw)
}
arr[i] = obj
}
}
tidArr := make([]*TypedID, len(arr))
for i, typedIDObj := range arr {
tid, err := parseTypedIDObj(typedIDObj)
if err != nil {
return nil, err
}
tidArr[i] = &tid
}
return tidArr, nil
}
func describeSchemaValidationError(result *gojsonschema.Result, what string) string {
errMsg := what + " is not valid:\n"
for _, desc := range result.Errors() {
errMsg += fmt.Sprintf("- %s\n", desc)
}
return errMsg
}
func stringSlice(values []interface{}) ([]string, error) {
s := make([]string, len(values))
for i := range values {
t, valid := values[i].(string)
if !valid {
return nil, errors.New("array element is not a string")
}
s[i] = t
}
return s, nil
}
// decodeType decodes raw type(s).
//
// type can be defined as a single string value or array of strings.
func decodeType(t interface{}) ([]string, error) {
switch rType := t.(type) {
case string:
return []string{rType}, nil
case []interface{}:
types, err := stringSlice(rType)
if err != nil {
return nil, fmt.Errorf("vc types: %w", err)
}
return types, nil
case []string:
return rType, nil
default:
return nil, errors.New("credential type of unknown structure")
}
}
// decodeContext decodes raw context(s).
//
// context can be defined as a single string value or array;
// at the second case, the array can be a mix of string and object types
// (objects can express context information); object context are
// defined at the tail of the array.
func decodeContext(c interface{}) ([]string, []interface{}, error) {
switch rContext := c.(type) {
case string:
return []string{rContext}, nil, nil
case []interface{}:
s := make([]string, 0)
for i := range rContext {
c, valid := rContext[i].(string)
if !valid {
// the remaining contexts are of custom type
return s, rContext[i:], nil
}
s = append(s, c)
}
// no contexts of custom type, just string contexts found
return s, nil, nil
case []string:
return rContext, nil, nil
default:
return nil, nil, errors.New("credential context of unknown type")
}
}
func safeStringValue(v interface{}) string {
if v == nil {
return ""
}
value, ok := v.(string)
if !ok {
return ""
}
return value
}
func proofsToRaw(proofs []Proof) interface{} {
switch len(proofs) {
case 0:
return nil
case 1:
return map[string]interface{}(proofs[0])
default:
return mapSlice(proofs, func(p Proof) interface{} {
return map[string]interface{}(p)
})
}
}
func parseLDProof(proofJSON interface{}) ([]Proof, error) {
if proofJSON == nil {
return nil, nil
}
switch proof := proofJSON.(type) {
case map[string]interface{}:
return []Proof{proof}, nil
case []interface{}:
return mapSlice2(proof, func(raw interface{}) (Proof, error) {
p, ok := raw.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unsupported proof value '%v'", proofJSON)
}
return p, nil
})
default:
return nil, fmt.Errorf("unsupported proof value '%v'", proofJSON)
}
}
func parseStringFld(obj JSONObject, fldName string) (string, error) {
jsonStr := obj[fldName]
if jsonStr == nil {
return "", nil
}
switch str := jsonStr.(type) {
case string:
return str, nil
default:
return "", fmt.Errorf("field %q should be string, instead got '%v'", fldName, jsonStr)
}
}
func parseTimeFld(obj JSONObject, fldName string) (*util.TimeWrapper, error) {
jsonTime := obj[fldName]
if jsonTime == nil {
return nil, nil
}
switch timeStr := jsonTime.(type) {
case string:
time, err := util.ParseTimeWrapper(timeStr)
if err != nil {
return nil, fmt.Errorf("field %q contains invalid time value '%v':%w", fldName, jsonTime, err)
}
return time, nil
default:
return nil, fmt.Errorf("time field %q should be json string, instead got '%v'", fldName, jsonTime)
}
}
func mapSlice[T any, U any](slice []T, mapFN func(T) U) []U {
var result []U
for _, v := range slice {
result = append(result, mapFN(v))
}
return result
}
func mapSlice2[T any, U any](slice []T, mapFN func(T) (U, error)) ([]U, error) {
var result []U
for _, v := range slice {
newVal, err := mapFN(v)
if err != nil {
return nil, err
}
result = append(result, newVal)
}
return result, nil
}
// MediaType specifies the media type of the data.
type MediaType string
// Encoding specifies the encoding of the data.
type Encoding string
// NewDataURL returns a new Data URL given the media type, encoding, and data.
// The URL will be in the format "data:<media type>[;base64],<data>".
// See https://www.rfc-editor.org/rfc/rfc2397.
func NewDataURL(mediaType MediaType, encoding Encoding, data string) string {
if encoding == "" {
return fmt.Sprintf("data:%s,%s", mediaType, data)
}
return fmt.Sprintf("data:%s;%s,%s", mediaType, encoding, data)
}
// ParseDataURL parses the given data URL and returns the media type, encoding, and data.
// The URL must be in the format "data:<media type>[;base64],<data>".
// See https://www.rfc-editor.org/rfc/rfc2397.
func ParseDataURL(url string) (MediaType, Encoding, string, error) {
if !strings.HasPrefix(url, "data:") {
return "", "", "", fmt.Errorf("invalid data URL format: %s", url)
}
url = url[5:] // Remove "data:" prefix
commaIndex := strings.Index(url, ",")
if commaIndex == -1 {
return "", "", "", fmt.Errorf("invalid data URL format: %s", url)
}
fullMediaType := url[:commaIndex]
if fullMediaType == "" {
return "", "", "", errors.New("media type is required")
}
data := url[commaIndex+1:]
semicolonIndex := strings.Index(fullMediaType, ";")
if semicolonIndex == -1 {
return MediaType(fullMediaType), "", data, nil
}
mediaType := MediaType(fullMediaType[:semicolonIndex])
encoding := Encoding(fullMediaType[semicolonIndex+1:])
return mediaType, encoding, data, nil
}