This repository has been archived by the owner on Mar 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 162
/
service.go
570 lines (461 loc) · 16.1 KB
/
service.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package route
import (
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/common/model"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/common/service"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/dispatcher"
"github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdri"
"github.com/hyperledger/aries-framework-go/pkg/kms/legacykms"
"github.com/hyperledger/aries-framework-go/pkg/storage"
"github.com/hyperledger/aries-framework-go/pkg/store/connection"
)
var logger = log.New("aries-framework/route/service")
// constants for route coordination spec types
const (
// Coordination route coordination protocol
Coordination = "routecoordination"
// RouteCoordinationSpec defines the route coordination spec
CoordinationSpec = "https://didcomm.org/routecoordination/1.0/"
// RouteRequestMsgType defines the route coordination request message type.
RequestMsgType = CoordinationSpec + "route-request"
// RouteGrantMsgType defines the route coordination request grant message type.
GrantMsgType = CoordinationSpec + "route-grant"
// KeyListUpdateMsgType defines the route coordination key list update message type.
KeylistUpdateMsgType = CoordinationSpec + "keylist_update"
// KeyListUpdateResponseMsgType defines the route coordination key list update message response type.
KeylistUpdateResponseMsgType = CoordinationSpec + "keylist_update_response"
)
// constants for key list update processing
// https://github.com/hyperledger/aries-rfcs/tree/master/features/0211-route-coordination#keylist-update
const (
// add key to the store
add = "add"
// remove key from the store
remove = "remove"
// server error while storing the key
serverError = "server_error"
// key save success
success = "success"
)
const (
// data key to store router connection ID
routeConnIDDataKey = "route-connID"
// data key to store router config
routeConfigDataKey = "route-config"
)
const (
updateTimeout = 5 * time.Second
)
// ErrConnectionNotFound connection not found error
var ErrConnectionNotFound = errors.New("connection not found")
// ErrRouterNotRegistered router not registered error
var ErrRouterNotRegistered = errors.New("router not registered")
// provider contains dependencies for the Routing protocol and is typically created by using aries.Context()
type provider interface {
OutboundDispatcher() dispatcher.Outbound
StorageProvider() storage.Provider
TransientStorageProvider() storage.Provider
InboundTransportEndpoint() string
KMS() legacykms.KeyManager
VDRIRegistry() vdri.Registry
}
// Service for Route Coordination protocol.
// https://github.com/hyperledger/aries-rfcs/tree/master/features/0211-route-coordination
type Service struct {
service.Action
service.Message
routeStore storage.Store
connectionLookup *connection.Lookup
outbound dispatcher.Outbound
endpoint string
kms legacykms.KeyManager
vdRegistry vdri.Registry
routeRegistrationMap map[string]chan Grant
routeRegistrationMapLock sync.RWMutex
keylistUpdateMap map[string]chan *KeylistUpdateResponse
keylistUpdateMapLock sync.RWMutex
}
// New return route coordination service.
func New(prov provider) (*Service, error) {
store, err := prov.StorageProvider().OpenStore(Coordination)
if err != nil {
return nil, fmt.Errorf("open route coordination store : %w", err)
}
connectionLookup, err := connection.NewLookup(prov)
if err != nil {
return nil, err
}
return &Service{
routeStore: store,
outbound: prov.OutboundDispatcher(),
endpoint: prov.InboundTransportEndpoint(),
kms: prov.KMS(),
vdRegistry: prov.VDRIRegistry(),
connectionLookup: connectionLookup,
routeRegistrationMap: make(map[string]chan Grant),
keylistUpdateMap: make(map[string]chan *KeylistUpdateResponse),
}, nil
}
// HandleInbound handles inbound route coordination messages.
func (s *Service) HandleInbound(msg service.DIDCommMsg, myDID, theirDID string) (string, error) { // nolint gocyclo (5 switch cases)
// perform action on inbound message asynchronously
go func() {
switch msg.Type() {
case RequestMsgType:
if err := s.handleRequest(msg, myDID, theirDID); err != nil {
logger.Errorf("handle route request error : %s", err)
}
case GrantMsgType:
if err := s.handleGrant(msg); err != nil {
logger.Errorf("handle route grant error : %s", err)
}
case KeylistUpdateMsgType:
if err := s.handleKeylistUpdate(msg, myDID, theirDID); err != nil {
logger.Errorf("handle route keylist update error : %s", err)
}
case KeylistUpdateResponseMsgType:
if err := s.handleKeylistUpdateResponse(msg); err != nil {
logger.Errorf("handle route keylist update response error : %s", err)
}
case service.ForwardMsgType:
if err := s.handleForward(msg); err != nil {
logger.Errorf("handle forward error : %s", err)
}
}
}()
return msg.ID(), nil
}
// HandleOutbound handles outbound route coordination messages.
func (s *Service) HandleOutbound(msg service.DIDCommMsg, myDID, theirDID string) error {
return errors.New("not implemented")
}
// Accept checks whether the service can handle the message type.
func (s *Service) Accept(msgType string) bool {
switch msgType {
case RequestMsgType, GrantMsgType, KeylistUpdateMsgType, KeylistUpdateResponseMsgType, service.ForwardMsgType:
return true
}
return false
}
// Name of the service
func (s *Service) Name() string {
return Coordination
}
func (s *Service) handleRequest(msg service.DIDCommMsg, myDID, theirDID string) error {
// unmarshal the payload
request := &Request{}
err := msg.Decode(request)
if err != nil {
return fmt.Errorf("route request message unmarshal : %w", err)
}
// create keys
_, sigPubKey, err := s.kms.CreateKeySet()
if err != nil {
return fmt.Errorf("failed to create keys : %w", err)
}
// send the grant response
grant := &Grant{
Type: GrantMsgType,
ID: msg.ID(),
Endpoint: s.endpoint,
RoutingKeys: []string{sigPubKey},
}
return s.outbound.SendToDID(grant, myDID, theirDID)
}
func (s *Service) handleGrant(msg service.DIDCommMsg) error {
// unmarshal the payload
grantMsg := &Grant{}
err := msg.Decode(grantMsg)
if err != nil {
return fmt.Errorf("route grant message unmarshal : %w", err)
}
// check if there are any channels registered for the message ID
grantCh := s.getRouteRegistrationCh(grantMsg.ID)
if grantCh != nil {
// invoke the channel for the incoming message
grantCh <- *grantMsg
}
return nil
}
func (s *Service) handleKeylistUpdate(msg service.DIDCommMsg, myDID, theirDID string) error {
// unmarshal the payload
keyUpdate := &KeylistUpdate{}
err := msg.Decode(keyUpdate)
if err != nil {
return fmt.Errorf("route key list update message unmarshal : %w", err)
}
var updates []UpdateResponse
// update the db
for _, v := range keyUpdate.Updates {
if v.Action == add {
val := theirDID
result := success
err = s.routeStore.Put(dataKey(v.RecipientKey), []byte(val))
if err != nil {
logger.Errorf("failed to add the route key to store : %s", err)
result = serverError
}
// construct the response doc
updates = append(updates, UpdateResponse{
RecipientKey: v.RecipientKey,
Action: v.Action,
Result: result,
})
} else if v.Action == remove {
// TODO remove from the store
// construct the response doc
updates = append(updates, UpdateResponse{
RecipientKey: v.RecipientKey,
Action: v.Action,
Result: serverError,
})
}
}
// send the key update response
updateResponse := &KeylistUpdateResponse{
Type: KeylistUpdateResponseMsgType,
ID: msg.ID(),
Updated: updates,
}
return s.outbound.SendToDID(updateResponse, myDID, theirDID)
}
func (s *Service) handleKeylistUpdateResponse(msg service.DIDCommMsg) error {
// unmarshal the payload
respMsg := &KeylistUpdateResponse{}
err := msg.Decode(respMsg)
if err != nil {
return fmt.Errorf("route keylist update response message unmarshal : %w", err)
}
// check if there are any channels registered for the message ID
keylistUpdateCh := s.getKeyUpdateResponseCh(respMsg.ID)
if keylistUpdateCh != nil {
// invoke the channel for the incoming message
keylistUpdateCh <- respMsg
}
return nil
}
func (s *Service) handleForward(msg service.DIDCommMsg) error {
// unmarshal the payload
forward := &model.Forward{}
err := msg.Decode(forward)
if err != nil {
return fmt.Errorf("forward message unmarshal : %w", err)
}
// TODO Open question - https://github.com/hyperledger/aries-framework-go/issues/965 Mismatch between Route
// Coordination and Forward RFC. For now assume, the TO field contains the recipient key.
theirDID, err := s.routeStore.Get(dataKey(forward.To))
if err != nil {
return fmt.Errorf("route key fetch : %w", err)
}
dest, err := service.GetDestination(string(theirDID), s.vdRegistry)
if err != nil {
return fmt.Errorf("get destination : %w", err)
}
return s.outbound.Forward(forward.Msg, dest)
}
// Register registers the agent with the router on the other end of the connection identified by
// connectionID. This method blocks until a response is received from the router or it times out.
// The agent is registered with the router and retrieves the router endpoint and routing keys.
// This function throws an error if the agent is already registered against a router.
// TODO https://github.com/hyperledger/aries-framework-go/issues/1076 Register agent with
// multiple routers
func (s *Service) Register(connectionID string) error {
// check if router is already registered
routerConnID, err := s.getRouterConnectionID()
if err != nil && !errors.Is(err, storage.ErrDataNotFound) {
return fmt.Errorf("fetch router connection id : %w", err)
}
if routerConnID != "" {
return errors.New("router is already registered")
}
// get the connection record for the ID to fetch DID information
conn, err := s.getConnection(connectionID)
if err != nil {
return err
}
// generate message ID
msgID := uuid.New().String()
// register chan for callback processing
grantCh := make(chan Grant)
s.setRouteRegistrationCh(msgID, grantCh)
// create request message
req := &Request{
ID: msgID,
Type: RequestMsgType,
}
// send message to the router
if err := s.outbound.SendToDID(req, conn.MyDID, conn.TheirDID); err != nil {
return fmt.Errorf("send route request: %w", err)
}
// callback processing (to make this function look like a sync function)
select {
case grantResp := <-grantCh:
conf := &config{
RouterEndpoint: grantResp.Endpoint,
RoutingKeys: grantResp.RoutingKeys,
}
if err := s.saveRouterConfig(conf); err != nil {
return fmt.Errorf("save route config : %w", err)
}
// TODO https://github.com/hyperledger/aries-framework-go/issues/948 configure this timeout at decorator level
case <-time.After(updateTimeout):
return errors.New("timeout waiting for grant from the router")
}
// remove the channel once its been processed
s.setRouteRegistrationCh(msgID, nil)
// save the connectionID of the router
return s.saveRouterConnectionID(connectionID)
}
// AddKey adds a recKey of the agent to the registered router. This method blocks until a response is
// received from the router or it times out.
// TODO https://github.com/hyperledger/aries-framework-go/issues/1076 Support for multiple routers
// TODO https://github.com/hyperledger/aries-framework-go/issues/1105 Support to Add multiple
// recKeys to the Router
func (s *Service) AddKey(recKey string) error {
// check if router is already registered
routerConnID, err := s.getRouterConnectionID()
if err != nil && !errors.Is(err, storage.ErrDataNotFound) {
return fmt.Errorf("fetch router connection id : %w", err)
}
if routerConnID == "" {
return ErrRouterNotRegistered
}
// get the connection record for the ID to fetch DID information
conn, err := s.getConnection(routerConnID)
if err != nil {
return err
}
// generate message ID
msgID := uuid.New().String()
// register chan for callback processing
keyUpdateCh := make(chan *KeylistUpdateResponse)
s.setKeyUpdateResponseCh(msgID, keyUpdateCh)
keyUpdate := &KeylistUpdate{
ID: msgID,
Type: KeylistUpdateMsgType,
Updates: []Update{
{
RecipientKey: recKey,
Action: add,
},
},
}
if err := s.outbound.SendToDID(keyUpdate, conn.MyDID, conn.TheirDID); err != nil {
return fmt.Errorf("send route request: %w", err)
}
select {
case keyUpdateResp := <-keyUpdateCh:
if err := processKeylistUpdateResp(recKey, keyUpdateResp); err != nil {
return err
}
// TODO https://github.com/hyperledger/aries-framework-go/issues/948 configure this timeout at decorator level
case <-time.After(updateTimeout):
return errors.New("timeout waiting for keylist update response from the router")
}
// remove the channel once its been processed
s.setKeyUpdateResponseCh(msgID, nil)
return nil
}
// Config fetches the router config - endpoint and routingKeys.
func (s *Service) Config() (*Config, error) {
// check if router is already registered
_, err := s.getRouterConnectionID()
if err != nil && !errors.Is(err, storage.ErrDataNotFound) {
return nil, fmt.Errorf("fetch router connection id : %w", err)
} else if errors.Is(err, storage.ErrDataNotFound) {
return nil, ErrRouterNotRegistered
}
return s.getRouterConfig()
}
func processKeylistUpdateResp(recKey string, keyUpdateResp *KeylistUpdateResponse) error {
for _, result := range keyUpdateResp.Updated {
if result.RecipientKey == recKey && result.Action == add && result.Result != success {
return errors.New("failed to update the recipient key with the router")
}
}
return nil
}
func (s *Service) getRouteRegistrationCh(msgID string) chan Grant {
s.routeRegistrationMapLock.RLock()
defer s.routeRegistrationMapLock.RUnlock()
return s.routeRegistrationMap[msgID]
}
func (s *Service) setRouteRegistrationCh(msgID string, grantCh chan Grant) {
s.routeRegistrationMapLock.Lock()
defer s.routeRegistrationMapLock.Unlock()
if grantCh == nil {
delete(s.routeRegistrationMap, msgID)
} else {
s.routeRegistrationMap[msgID] = grantCh
}
}
func (s *Service) getKeyUpdateResponseCh(msgID string) chan *KeylistUpdateResponse {
s.keylistUpdateMapLock.RLock()
defer s.keylistUpdateMapLock.RUnlock()
return s.keylistUpdateMap[msgID]
}
func (s *Service) setKeyUpdateResponseCh(msgID string, keyUpdateCh chan *KeylistUpdateResponse) {
s.keylistUpdateMapLock.Lock()
defer s.keylistUpdateMapLock.Unlock()
if keyUpdateCh == nil {
delete(s.keylistUpdateMap, msgID)
} else {
s.keylistUpdateMap[msgID] = keyUpdateCh
}
}
func (s *Service) getRouterConnectionID() (string, error) {
id, err := s.routeStore.Get(routeConnIDDataKey)
if err != nil {
return "", err
}
return string(id), nil
}
func (s *Service) saveRouterConnectionID(id string) error {
return s.routeStore.Put(routeConnIDDataKey, []byte(id))
}
type config struct {
RouterEndpoint string
RoutingKeys []string
}
func (s *Service) getRouterConfig() (*Config, error) {
val, err := s.routeStore.Get(routeConfigDataKey)
if err != nil {
return nil, fmt.Errorf("get router config data : %w", err)
}
conf := &config{}
err = json.Unmarshal(val, conf)
if err != nil {
return nil, fmt.Errorf("unmarshal router config data : %w", err)
}
return NewConfig(conf.RouterEndpoint, conf.RoutingKeys), nil
}
func (s *Service) saveRouterConfig(conf *config) error {
bytes, err := json.Marshal(conf)
if err != nil {
return fmt.Errorf("store router config data : %w", err)
}
return s.routeStore.Put(routeConfigDataKey, bytes)
}
func (s *Service) getConnection(routerConnID string) (*connection.Record, error) {
conn, err := s.connectionLookup.GetConnectionRecord(routerConnID)
if err != nil {
if errors.Is(err, storage.ErrDataNotFound) {
return nil, ErrConnectionNotFound
}
return nil, fmt.Errorf("fetch connection record from store : %w", err)
}
return conn, nil
}
func dataKey(id string) string {
return "route-" + id
}