forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
371 lines (294 loc) · 13 KB
/
command.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package messaging
import (
"encoding/json"
"fmt"
"io"
"github.com/hyperledger/aries-framework-go/pkg/internal/logutil"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
"github.com/hyperledger/aries-framework-go/pkg/controller/command"
"github.com/hyperledger/aries-framework-go/pkg/controller/internal/cmdutil"
"github.com/hyperledger/aries-framework-go/pkg/controller/webhook"
"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/didcomm/messaging/service/http"
"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/controller/common")
const (
// command name
commandName = "messaging"
// states
stateNameCompleted = "completed"
// error messages
errMsgSvcNameRequired = "service name is required"
errMsgInvalidAcceptanceCrit = "invalid acceptance criteria"
errMsgBodyEmpty = "empty message body"
errMsgDestinationMissing = "missing message destination"
errMsgDestSvcEndpointMissing = "missing service endpoint in message destination"
errMsgDestSvcEndpointKeysMissing = "missing service endpoint recipient/routing keys in message destination"
errMsgConnectionMatchingDIDNotFound = "unable to find connection matching theirDID[%s]"
errMsgIDEmpty = "empty message ID"
// command methods
registeredServicesCommandMethod = "Services"
registerMessageServiceCommandMethod = "RegisterService"
unregisterMessageServiceCommandMethod = "UnregisterService"
registerHTTPMessageServiceCommandMethod = "RegisterHTTPService"
sendNewMessageCommandMethod = "Send"
sendReplyMessageCommandMethod = "Reply"
// log constants
connectionIDString = "connectionID"
destinationString = "destination"
successString = "success"
)
// Error codes
const (
// InvalidRequestErrorCode is typically a code for invalid requests
InvalidRequestErrorCode = command.Code(iota + command.Messaging)
// RegisterMsgSvcError is for failures while registering new message service
RegisterMsgSvcError
// UnregisterMsgSvcError is for failures while unregistering a message service
UnregisterMsgSvcError
// SendMsgError is for failures while sending messages
SendMsgError
// SendMsgReplyError is for failures while sending message replies
SendMsgReplyError
)
// provider contains dependencies for the messaging controller command operations
// and is typically created by using aries.Context()
type provider interface {
OutboundDispatcher() dispatcher.Outbound
TransientStorageProvider() storage.Provider
StorageProvider() storage.Provider
LegacyKMS() legacykms.KeyManager
}
// Command contains basic command operations provided by messaging controller command
type Command struct {
ctx provider
msgRegistrar command.MessageHandler
notifier webhook.Notifier
connectionLookup *connection.Lookup
}
// New returns new command instance for messaging controller API
func New(ctx provider, registrar command.MessageHandler, notifier webhook.Notifier) (*Command, error) {
connectionLookup, err := connection.NewLookup(ctx)
if err != nil {
return nil, fmt.Errorf("failed to initialize connection lookup : %w", err)
}
o := &Command{
ctx: ctx,
msgRegistrar: registrar,
notifier: notifier,
connectionLookup: connectionLookup,
}
return o, nil
}
// GetHandlers returns list of all commands supported by this controller command
func (o *Command) GetHandlers() []command.Handler {
return []command.Handler{
cmdutil.NewCommandHandler(commandName, registeredServicesCommandMethod, o.Services),
cmdutil.NewCommandHandler(commandName, registerMessageServiceCommandMethod, o.RegisterService),
cmdutil.NewCommandHandler(commandName, unregisterMessageServiceCommandMethod, o.UnregisterService),
cmdutil.NewCommandHandler(commandName, registerHTTPMessageServiceCommandMethod, o.RegisterHTTPService),
cmdutil.NewCommandHandler(commandName, sendNewMessageCommandMethod, o.Send),
cmdutil.NewCommandHandler(commandName, sendReplyMessageCommandMethod, o.Reply),
}
}
// RegisterService registers new message service to message handler registrar
func (o *Command) RegisterService(rw io.Writer, req io.Reader) command.Error {
var request RegisterMsgSvcArgs
err := json.NewDecoder(req).Decode(&request)
if err != nil {
logutil.LogInfo(logger, commandName, registerMessageServiceCommandMethod, err.Error())
return command.NewValidationError(InvalidRequestErrorCode, err)
}
return o.registerMessageService(&request)
}
// UnregisterService unregisters given message service handler registrar
func (o *Command) UnregisterService(rw io.Writer, req io.Reader) command.Error {
var request UnregisterMsgSvcArgs
err := json.NewDecoder(req).Decode(&request)
if err != nil {
logutil.LogInfo(logger, commandName, unregisterMessageServiceCommandMethod, err.Error())
return command.NewValidationError(InvalidRequestErrorCode, err)
}
if request.Name == "" {
logutil.LogDebug(logger, commandName, unregisterMessageServiceCommandMethod, errMsgSvcNameRequired)
return command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(errMsgSvcNameRequired))
}
err = o.msgRegistrar.Unregister(request.Name)
if err != nil {
logutil.LogError(logger, commandName, registerMessageServiceCommandMethod, err.Error(),
logutil.CreateKeyValueString("name", request.Name))
return command.NewExecuteError(UnregisterMsgSvcError, err)
}
logutil.LogDebug(logger, commandName, unregisterMessageServiceCommandMethod, successString,
logutil.CreateKeyValueString("name", request.Name))
return nil
}
// Services returns list of registered service names
func (o *Command) Services(rw io.Writer, req io.Reader) command.Error {
names := []string{}
for _, svc := range o.msgRegistrar.Services() {
names = append(names, svc.Name())
}
command.WriteNillableResponse(rw, RegisteredServicesResponse{Names: names}, logger)
logutil.LogDebug(logger, commandName, registeredServicesCommandMethod, successString)
return nil
}
// Send sends new message to destination provided
func (o *Command) Send(rw io.Writer, req io.Reader) command.Error {
var request SendNewMessageArgs
err := json.NewDecoder(req).Decode(&request)
if err != nil {
logutil.LogInfo(logger, commandName, sendNewMessageCommandMethod, err.Error())
return command.NewValidationError(InvalidRequestErrorCode, err)
}
if len(request.MessageBody) == 0 {
logutil.LogDebug(logger, commandName, sendNewMessageCommandMethod, errMsgBodyEmpty)
return command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(errMsgBodyEmpty))
}
err = o.validateMessageDestination(&request)
if err != nil {
logutil.LogError(logger, commandName, sendNewMessageCommandMethod, err.Error())
return command.NewValidationError(InvalidRequestErrorCode, err)
}
if request.ConnectionID != "" {
conn, err := o.connectionLookup.GetConnectionRecord(request.ConnectionID)
if err != nil {
logutil.LogError(logger, commandName, sendNewMessageCommandMethod, err.Error(),
logutil.CreateKeyValueString(connectionIDString, request.ConnectionID))
return command.NewExecuteError(SendMsgError, err)
}
return o.sendMessageToConnection(request.MessageBody, conn)
}
if request.TheirDID != "" {
conn, err := o.getConnectionByTheirDID(request.TheirDID)
if err != nil {
logutil.LogError(logger, commandName, sendNewMessageCommandMethod, err.Error())
return command.NewExecuteError(SendMsgError, err)
}
return o.sendMessageToConnection(request.MessageBody, conn)
}
return o.sendMessageToDestination(request.MessageBody, request.ServiceEndpointDestination)
}
// Reply sends reply to existing message
func (o *Command) Reply(rw io.Writer, req io.Reader) command.Error {
var request SendReplyMessageArgs
err := json.NewDecoder(req).Decode(&request)
if err != nil {
logutil.LogInfo(logger, commandName, sendReplyMessageCommandMethod, err.Error())
return command.NewValidationError(InvalidRequestErrorCode, err)
}
if len(request.MessageBody) == 0 {
logutil.LogDebug(logger, commandName, sendReplyMessageCommandMethod, errMsgBodyEmpty)
return command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(errMsgBodyEmpty))
}
if request.MessageID == "" {
logutil.LogDebug(logger, commandName, sendReplyMessageCommandMethod, errMsgIDEmpty)
return command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(errMsgIDEmpty))
}
// TODO this operation will be supported once messenger API [Issue #1039] is available
// TODO implementation for SendReply to be added as part of [Issue #1089]
return command.NewExecuteError(SendMsgReplyError, fmt.Errorf("to be implemented"))
}
// RegisterHTTPService registers new http over didcomm service to message handler registrar
func (o *Command) RegisterHTTPService(rw io.Writer, req io.Reader) command.Error {
var request RegisterHTTPMsgSvcArgs
err := json.NewDecoder(req).Decode(&request)
if err != nil {
logutil.LogInfo(logger, commandName, registerHTTPMessageServiceCommandMethod, err.Error())
return command.NewValidationError(InvalidRequestErrorCode, err)
}
return o.registerMessageService(&RegisterMsgSvcArgs{
Name: request.Name,
Type: http.OverDIDCommMsgRequestType,
Purpose: request.Purpose,
})
}
func (o *Command) registerMessageService(params *RegisterMsgSvcArgs) command.Error {
if params.Name == "" {
logutil.LogDebug(logger, commandName, registerMessageServiceCommandMethod, errMsgSvcNameRequired)
return command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(errMsgSvcNameRequired))
}
if params.Type == "" {
logutil.LogDebug(logger, commandName, registerMessageServiceCommandMethod, errMsgInvalidAcceptanceCrit)
return command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(errMsgInvalidAcceptanceCrit))
}
err := o.msgRegistrar.Register(newMessageService(params, o.notifier))
if err != nil {
logutil.LogError(logger, commandName, registerMessageServiceCommandMethod, err.Error(),
logutil.CreateKeyValueString("name", params.Name),
logutil.CreateKeyValueString("type", params.Type))
return command.NewExecuteError(RegisterMsgSvcError, err)
}
return nil
}
func (o *Command) validateMessageDestination(dest *SendNewMessageArgs) error {
var didMissing, connIDMissing, svcEPMissing = dest.TheirDID == "",
dest.ConnectionID == "",
dest.ServiceEndpointDestination == nil
if didMissing && connIDMissing && svcEPMissing {
return fmt.Errorf(errMsgDestinationMissing)
}
if !didMissing || !connIDMissing {
return nil
}
if dest.ServiceEndpointDestination.ServiceEndpoint == "" {
return fmt.Errorf(errMsgDestSvcEndpointMissing)
}
if len(dest.ServiceEndpointDestination.RecipientKeys) == 0 &&
len(dest.ServiceEndpointDestination.RoutingKeys) == 0 {
return fmt.Errorf(errMsgDestSvcEndpointKeysMissing)
}
return nil
}
func (o *Command) getConnectionByTheirDID(theirDID string) (*connection.Record, error) {
records, err := o.connectionLookup.QueryConnectionRecords()
if err != nil {
return nil, err
}
for _, record := range records {
if record.State == stateNameCompleted && record.TheirDID == theirDID {
return record, nil
}
}
return nil, fmt.Errorf(errMsgConnectionMatchingDIDNotFound, theirDID)
}
func (o *Command) sendMessageToConnection(msg json.RawMessage, conn *connection.Record) command.Error {
err := o.ctx.OutboundDispatcher().SendToDID(msg, conn.MyDID, conn.TheirDID)
if err != nil {
logutil.LogError(logger, commandName, sendNewMessageCommandMethod, err.Error(),
logutil.CreateKeyValueString(connectionIDString, conn.ConnectionID))
return command.NewExecuteError(SendMsgError, err)
}
logutil.LogDebug(logger, commandName, sendNewMessageCommandMethod, successString,
logutil.CreateKeyValueString(connectionIDString, conn.ConnectionID))
return nil
}
func (o *Command) sendMessageToDestination(msg json.RawMessage, dest *ServiceEndpointDestinationParams) command.Error {
_, sigPubKey, err := o.ctx.LegacyKMS().CreateKeySet()
if err != nil {
logutil.LogError(logger, commandName, sendNewMessageCommandMethod, err.Error(),
logutil.CreateKeyValueString(destinationString, dest.ServiceEndpoint))
return command.NewExecuteError(SendMsgError, err)
}
err = o.ctx.OutboundDispatcher().Send(msg, sigPubKey, &service.Destination{
RoutingKeys: dest.RoutingKeys,
RecipientKeys: dest.RecipientKeys,
ServiceEndpoint: dest.ServiceEndpoint,
})
if err != nil {
logutil.LogError(logger, commandName, sendNewMessageCommandMethod, err.Error(),
logutil.CreateKeyValueString(destinationString, dest.ServiceEndpoint))
return command.NewExecuteError(SendMsgError, err)
}
logutil.LogDebug(logger, commandName, sendNewMessageCommandMethod, successString,
logutil.CreateKeyValueString(destinationString, dest.ServiceEndpoint))
return nil
}