forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.go
284 lines (230 loc) · 7.35 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
/*
Copyright SecureKey Technologies Inc. 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 (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/piprate/json-gold/ld"
"github.com/xeipuuv/gojsonschema"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/verifier"
vdrapi "github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr"
)
// TODO https://github.com/square/go-jose/issues/263 support ES256K
// JWSAlgorithm defines JWT signature algorithms of Verifiable Credential.
type JWSAlgorithm int
const (
// RS256 JWT Algorithm.
RS256 JWSAlgorithm = iota
// EdDSA JWT Algorithm.
EdDSA
)
// name return the name of the signature algorithm.
func (ja JWSAlgorithm) name() (string, error) {
switch ja {
case RS256:
return "RS256", nil
case EdDSA:
return "EdDSA", nil
default:
return "", fmt.Errorf("unsupported algorithm: %v", ja)
}
}
type jsonldCredentialOpts struct {
jsonldDocumentLoader ld.DocumentLoader
externalContext []string
jsonldOnlyValidRDF bool
}
// PublicKeyFetcher fetches public key for JWT signing verification based on Issuer ID (possibly DID)
// and Key ID.
// If not defined, JWT encoding is not tested.
type PublicKeyFetcher func(issuerID, keyID string) (*verifier.PublicKey, error)
// SingleKey defines the case when only one verification key is used and we don't need to pick the one.
func SingleKey(pubKey []byte, pubKeyType string) PublicKeyFetcher {
return func(_, _ string) (*verifier.PublicKey, error) {
return &verifier.PublicKey{
Type: pubKeyType,
Value: pubKey,
}, nil
}
}
// VDRKeyResolver resolves DID in order to find public keys for VC verification using vdr.Registry.
// A source of DID could be issuer of VC or holder of VP. It can be also obtained from
// JWS "issuer" claim or "verificationMethod" of Linked Data Proof.
type VDRKeyResolver struct {
vdr vdrapi.Registry
}
// NewVDRKeyResolver creates VDRKeyResolver.
func NewVDRKeyResolver(vdr vdrapi.Registry) *VDRKeyResolver {
return &VDRKeyResolver{vdr: vdr}
}
func (r *VDRKeyResolver) resolvePublicKey(issuerDID, keyID string) (*verifier.PublicKey, error) {
docResolution, err := r.vdr.Resolve(issuerDID)
if err != nil {
return nil, fmt.Errorf("resolve DID %s: %w", issuerDID, err)
}
for _, verifications := range docResolution.DIDDocument.VerificationMethods() {
for _, verification := range verifications {
if strings.Contains(verification.VerificationMethod.ID, keyID) {
return &verifier.PublicKey{
Type: verification.VerificationMethod.Type,
Value: verification.VerificationMethod.Value,
JWK: verification.VerificationMethod.JSONWebKey(),
}, nil
}
}
}
return nil, fmt.Errorf("public key with KID %s is not found for DID %s", keyID, issuerDID)
}
// PublicKeyFetcher returns Public Key Fetcher via DID resolution mechanism.
func (r *VDRKeyResolver) PublicKeyFetcher() PublicKeyFetcher {
return r.resolvePublicKey
}
// 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{}
// TypedID defines a flexible structure with id and name fields and arbitrary extra fields
// kept in CustomFields.
type TypedID struct {
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
CustomFields `json:"-"`
}
// MarshalJSON defines custom marshalling of TypedID to JSON.
func (tid TypedID) MarshalJSON() ([]byte, error) {
// TODO hide this exported method
type Alias TypedID
alias := Alias(tid)
data, err := marshalWithCustomFields(alias, tid.CustomFields)
if err != nil {
return nil, fmt.Errorf("marshal TypedID: %w", err)
}
return data, nil
}
// UnmarshalJSON defines custom unmarshalling of TypedID from JSON.
func (tid *TypedID) UnmarshalJSON(data []byte) error {
// TODO hide this exported method
type Alias TypedID
alias := (*Alias)(tid)
tid.CustomFields = make(CustomFields)
err := unmarshalWithCustomFields(data, alias, tid.CustomFields)
if err != nil {
return fmt.Errorf("unmarshal TypedID: %w", err)
}
return nil
}
func newTypedID(v interface{}) (TypedID, error) {
bytes, err := json.Marshal(v)
if err != nil {
return TypedID{}, err
}
var tid TypedID
err = json.Unmarshal(bytes, &tid)
return tid, err
}
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
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
default:
return nil, nil, errors.New("credential context of unknown type")
}
}
func safeStringValue(v interface{}) string {
if v == nil {
return ""
}
return v.(string)
}
func proofsToRaw(proofs []Proof) ([]byte, error) {
switch len(proofs) {
case 0:
return nil, nil
case 1:
return json.Marshal(proofs[0])
default:
return json.Marshal(proofs)
}
}
func parseProof(proofBytes json.RawMessage) ([]Proof, error) {
if len(proofBytes) == 0 {
return nil, nil
}
var singleProof Proof
err := json.Unmarshal(proofBytes, &singleProof)
if err == nil {
return []Proof{singleProof}, nil
}
var composedProof []Proof
err = json.Unmarshal(proofBytes, &composedProof)
if err == nil {
return composedProof, nil
}
return nil, err
}