-
Notifications
You must be signed in to change notification settings - Fork 28
/
operations.go
428 lines (334 loc) · 11.1 KB
/
operations.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package operation
import (
"crypto/ed25519"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/ed25519signature2018"
"github.com/hyperledger/aries-framework-go/pkg/doc/verifiable"
log "github.com/sirupsen/logrus"
"github.com/trustbloc/edge-core/pkg/storage"
"github.com/trustbloc/edv/pkg/restapi/edv/operation"
"github.com/trustbloc/edge-service/pkg/internal/common/support"
)
const (
credentialStore = "credential"
profile = "/profile"
credentialContext = "https://www.w3.org/2018/credentials/v1"
// endpoints
createCredentialEndpoint = "/credential"
verifyCredentialEndpoint = "/verify"
createProfileEndpoint = profile
getProfileEndpoint = profile + "/{id}"
storeCredentialEndpoint = "/store"
retrieveCredentialEndpoint = "/retrieve"
successMsg = "success"
)
var errProfileNotFound = errors.New("specified profile ID does not exist")
// Handler http handler for each controller API endpoint
type Handler interface {
Path() string
Method() string
Handle() http.HandlerFunc
}
// Client interface to interact with edv client
type Client interface {
CreateDataVault(config *operation.DataVaultConfiguration) (string, error)
CreateDocument(vaultID string, document *operation.StructuredDocument) (string, error)
RetrieveDocument(vaultID, docID string) ([]byte, error)
}
// New returns CreateCredential instance
func New(provider storage.Provider, client Client) (*Operation, error) {
store, err := provider.OpenStore(credentialStore)
if err != nil {
return nil, err
}
// TODO: replace by KMS
pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
svc := &Operation{
profileStore: NewProfile(store),
// TODO: replace private key by signer, public key by resolver
keySet: &keySet{private: privKey, public: pubKey},
client: client,
}
// TODO: Remove default profile when bdd test is done
err = svc.profileStore.SaveProfile(&ProfileResponse{
Name: "issuer",
DID: "did:method:abc",
URI: "https://issuer.com/credentials",
SignatureType: "Ed25519Signature2018",
Creator: "did:method:abc#key1",
})
if err != nil {
return nil, err
}
svc.registerHandler()
return svc, nil
}
// Operation defines handlers for Edge service
type Operation struct {
handlers []Handler
profileStore *Profile
keySet *keySet
client Client
}
// KeySet will be replaced with KMS/profile configuration
type keySet struct {
private []byte
public []byte
}
func (o *Operation) createCredentialHandler(rw http.ResponseWriter, req *http.Request) {
data := CreateCrendentialRequest{}
err := json.NewDecoder(req.Body).Decode(&data)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, "Failed to write response for invalid request received")
return
}
profile, err := o.profileStore.GetProfile(data.Profile)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, fmt.Sprintf("failed to read profile: %s", err.Error()))
return
}
validCredential, err := createCredential(profile, &data)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, fmt.Sprintf("failed to create credential: %s", err.Error()))
return
}
signedVC, err := o.signCredential(profile, validCredential)
if err != nil {
o.writeErrorResponse(rw, http.StatusInternalServerError, fmt.Sprintf("failed to sign credential: %s", err.Error()))
return
}
rw.WriteHeader(http.StatusCreated)
o.writeResponse(rw, signedVC)
}
func (o *Operation) signCredential(profile *ProfileResponse, vc *verifiable.Credential) (*verifiable.Credential, error) { // nolint:lll
signingCtx := &verifiable.LinkedDataProofContext{
Creator: profile.Creator,
SignatureType: profile.SignatureType,
Suite: ed25519signature2018.New(),
PrivateKey: o.keySet.private,
}
err := vc.AddLinkedDataProof(signingCtx)
if err != nil {
return nil, err
}
return vc, nil
}
func (o *Operation) verifyCredentialHandler(rw http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest,
fmt.Sprintf("failed to read request body: %s", err.Error()))
return
}
verified := true
message := successMsg
// Q: should signature suite this be passed in or handled (loaded automatically) by verifiable package
// based on signature type in proof
// Q: we should have default implementation for key fetcher in verifiable package as well
_, _, err = verifiable.NewCredential(body, verifiable.WithEmbeddedSignatureSuites(ed25519signature2018.New()),
verifiable.WithPublicKeyFetcher(verifiable.SingleKey(o.keySet.public)))
if err != nil {
verified = false
message = err.Error()
}
response := &VerifyCredentialResponse{
Verified: verified,
Message: message}
rw.WriteHeader(http.StatusOK)
o.writeResponse(rw, response)
}
func (o *Operation) createProfileHandler(rw http.ResponseWriter, req *http.Request) {
data := ProfileRequest{}
err := json.NewDecoder(req.Body).Decode(&data)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, "Failed to write response for invalid request received")
return
}
profileResponse, err := o.createProfile(&data)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
rw.WriteHeader(http.StatusCreated)
o.writeResponse(rw, profileResponse)
}
func (o *Operation) getProfileHandler(rw http.ResponseWriter, req *http.Request) {
profileID := mux.Vars(req)["id"]
profileResponseJSON, err := o.profileStore.GetProfile(profileID)
if err != nil {
if err == errProfileNotFound {
o.writeErrorResponse(rw, http.StatusNotFound, "Failed to find the profile")
return
}
o.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
o.writeResponse(rw, profileResponseJSON)
}
func (o *Operation) storeVCHandler(rw http.ResponseWriter, req *http.Request) {
data := &CreateCrendentialResponse{}
err := json.NewDecoder(req.Body).Decode(&data)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, "invalid request received")
return
}
if err = validateRequest(data.Profile, data.ID); err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
doc := operation.StructuredDocument{}
doc.Content = make(map[string]interface{})
doc.Content["message"] = data
// todo remove the stripping of the string issue-34
doc.ID = data.ID[strings.LastIndex(data.ID, "/")+1:]
locationOfDocument, err := o.client.CreateDocument(data.Profile, &doc)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
o.writeResponse(rw, locationOfDocument)
}
func (o *Operation) retrieveVCHandler(rw http.ResponseWriter, req *http.Request) {
id := req.URL.Query().Get("id")
profile := req.URL.Query().Get("profile")
if err := validateRequest(profile, id); err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
// todo remove the stripping of the string issue-34
credentialID := id[strings.LastIndex(id, "/")+1:]
credentialResponse, err := o.client.RetrieveDocument(profile, credentialID)
if err != nil {
o.writeErrorResponse(rw, http.StatusBadRequest, err.Error())
return
}
_, err = rw.Write(credentialResponse)
if err != nil {
log.Errorf("Failed to write response for document retrieval success: %s",
err.Error())
}
}
func createCredential(profile *ProfileResponse, data *CreateCrendentialRequest) (*verifiable.Credential, error) {
credential := &verifiable.Credential{}
issueDate := time.Now().UTC()
credential.Context = []string{credentialContext}
credential.Subject = data.Subject
credential.Types = data.Type
credential.Issuer = verifiable.Issuer{
ID: profile.DID,
Name: profile.Name,
}
credential.Issued = &issueDate
credential.ID = profile.URI + "/" + uuid.New().String()
cred, err := json.Marshal(credential)
if err != nil {
return nil, fmt.Errorf("create credential marshalling failed: %s", err.Error())
}
validatedCred, _, err := verifiable.NewCredential(cred)
if err != nil {
return nil, fmt.Errorf("failed to create new credential: %s", err.Error())
}
return validatedCred, nil
}
func (o *Operation) createProfile(pr *ProfileRequest) (*ProfileResponse, error) {
if err := validateProfileRequest(pr); err != nil {
return nil, err
}
created := time.Now().UTC()
profileResponse := &ProfileResponse{
Name: pr.Name,
URI: pr.URI,
Created: &created,
DID: pr.DID,
SignatureType: pr.SignatureType,
Creator: pr.Creator,
}
err := o.profileStore.SaveProfile(profileResponse)
if err != nil {
return nil, err
}
// create the vault associated with the profile
_, err = o.client.CreateDataVault(&operation.DataVaultConfiguration{ReferenceID: pr.Name})
if err != nil {
return nil, err
}
return profileResponse, nil
}
func validateProfileRequest(pr *ProfileRequest) error {
if pr.Name == "" {
return fmt.Errorf("missing profile name")
}
if pr.DID == "" {
return fmt.Errorf("missing DID information")
}
if pr.URI == "" {
return fmt.Errorf("missing URI information")
}
if pr.Creator == "" {
return fmt.Errorf("missing creator")
}
if pr.SignatureType == "" {
return fmt.Errorf("missing signature type")
}
_, err := url.Parse(pr.URI)
if err != nil {
return fmt.Errorf("invalid uri: %s", err.Error())
}
return nil
}
func validateRequest(profileName, vcID string) error {
if profileName == "" {
return fmt.Errorf("missing profile name")
}
if vcID == "" {
return fmt.Errorf("missing verifiable credential ID")
}
return nil
}
// writeResponse writes interface value to response
func (o *Operation) writeResponse(rw io.Writer, v interface{}) {
err := json.NewEncoder(rw).Encode(v)
if err != nil {
log.Errorf("Unable to send error response, %s", err)
}
}
func (o *Operation) writeErrorResponse(rw http.ResponseWriter, status int, msg string) {
rw.WriteHeader(status)
if _, err := rw.Write([]byte(msg)); err != nil {
log.Errorf("Unable to send error message, %s", err)
}
}
// registerHandler register handlers to be exposed from this service as REST API endpoints
func (o *Operation) registerHandler() {
// Add more protocol endpoints here to expose them as controller API endpoints
o.handlers = []Handler{
support.NewHTTPHandler(createCredentialEndpoint, http.MethodPost, o.createCredentialHandler),
support.NewHTTPHandler(createProfileEndpoint, http.MethodPost, o.createProfileHandler),
support.NewHTTPHandler(getProfileEndpoint, http.MethodGet, o.getProfileHandler),
support.NewHTTPHandler(storeCredentialEndpoint, http.MethodPost, o.storeVCHandler),
support.NewHTTPHandler(verifyCredentialEndpoint, http.MethodPost, o.verifyCredentialHandler),
support.NewHTTPHandler(retrieveCredentialEndpoint, http.MethodGet, o.retrieveVCHandler),
}
}
// GetRESTHandlers get all controller API handler available for this service
func (o *Operation) GetRESTHandlers() []Handler {
return o.handlers
}