/
api_node.go
468 lines (395 loc) · 15.2 KB
/
api_node.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
package node
import (
"fmt"
"math/big"
"net/http"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/momentum-xyz/ubercontroller/types/entry"
"github.com/momentum-xyz/ubercontroller/universe"
"github.com/momentum-xyz/ubercontroller/universe/logic/api"
"github.com/momentum-xyz/ubercontroller/universe/logic/api/dto"
"github.com/momentum-xyz/ubercontroller/utils"
"github.com/momentum-xyz/ubercontroller/utils/umid"
)
// @Summary Checks if an odyssey can be registered with a node
// @Description Checks if an odyssey can be registered with a node
// @Tags node
// @Security Bearer
// @Param body body node.apiNodeGetChallenge.Body true "body params"
// @Success 200 {object} node.apiNodeGetChallenge.ChallengeResponse
// @Failure 400 {object} api.HTTPError
// /api/v4/node/get-challenge [post]
func (n *Node) apiNodeGetChallenge(c *gin.Context) {
type Body struct {
OdysseyID string `json:"odyssey_id" binding:"required"`
}
var inBody Body
if err := c.ShouldBindJSON(&inBody); err != nil {
err = errors.WithMessage(err, "Node: apiNodeGetChallenge: failed to bind json")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
type ChallengeResponse struct {
Challenge string `json:"challenge"`
}
hostingAllowID := entry.NewAttributeID(universe.GetSystemPluginID(), "hosting_allow_list")
nodePrivateKeyID := entry.NewAttributeID(universe.GetSystemPluginID(), "node_private_key")
hostingAllowValue, ok := n.GetNodeAttributes().GetValue(hostingAllowID)
if !ok || hostingAllowValue == nil {
err := errors.New("Node: apiNodeGetChallenge: node attribute not found")
api.AbortRequest(c, http.StatusNotFound, "attribute_not_found", err, n.log)
return
}
nodePrivateKeyValue, ok := n.GetNodeAttributes().GetValue(nodePrivateKeyID)
if !ok || nodePrivateKeyValue == nil {
err := errors.New("Node: apiNodeGetChallenge: node attribute not found")
api.AbortRequest(c, http.StatusNotFound, "attribute_not_found", err, n.log)
return
}
allowedUserIDs := utils.GetFromAnyMap(*hostingAllowValue, "users", []interface{}{})
privateKey := utils.GetFromAnyMap(*nodePrivateKeyValue, "node_private_key", "")
userID, err := api.GetUserIDFromContext(c)
if err != nil {
err := errors.WithMessage(err, "Node: apiNodeGetChallenge: failed to get user umid from context")
api.AbortRequest(c, http.StatusInternalServerError, "get_user_id_failed", err, n.log)
return
}
nodeID := n.GetID().String()
signature, err := GetSignature(privateKey, nodeID, inBody.OdysseyID)
if err != nil {
err := errors.WithMessage(err, "Node: apiNodeGetChallenge: failed to get signature")
api.AbortRequest(c, http.StatusInternalServerError, "failed_to_get_signature", err, n.log)
return
}
if !n.cfg.Common.HostingAllowAll && !utils.AnyContains(allowedUserIDs, userID.String()) {
err := errors.New("Node: apiNodeGetChallenge: allow list does not contain user id: " + userID.String())
api.AbortRequest(c, http.StatusBadRequest, "user_not_allowed", err, n.log)
return
}
c.JSON(http.StatusOK, ChallengeResponse{Challenge: hexutil.Encode(signature)})
}
func signHash(data []byte) []byte {
msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
return crypto.Keccak256([]byte(msg))
}
func padTo256bits(data []byte) []byte {
if len(data) >= 32 {
return data
}
pad := make([]byte, 32-len(data))
return append(pad, data...)
}
func GetSignature(privateKey string, nodeID string, odysseyID string) ([]byte, error) {
privateKeyBytes, err := hexutil.Decode(privateKey)
if err != nil {
return nil, err
}
privateECDSAKey, err := crypto.ToECDSA(privateKeyBytes)
if err != nil {
return nil, err
}
uuidNodeID, err := umid.Parse(nodeID)
if err != nil {
return nil, err
}
uuidOdysseyID, err := umid.Parse(odysseyID)
if err != nil {
return nil, err
}
nodeIDBigInt := new(big.Int)
nodeIDBigInt.SetBytes(uuidNodeID[:])
odysseyIDBigInt := new(big.Int)
odysseyIDBigInt.SetBytes(uuidOdysseyID[:])
message := append(padTo256bits(nodeIDBigInt.Bytes()), padTo256bits(odysseyIDBigInt.Bytes())...)
hashedMessage := crypto.Keccak256(message)
prefixedMessageHash := signHash(hashedMessage)
signature, err := crypto.Sign(prefixedMessageHash, privateECDSAKey)
if err != nil {
return nil, err
}
signature[64] += 27
return signature, nil
}
// @Summary Get node hosting allow list users
// @Description Returns node hosting allow list users with resolved details
// @Tags hosting,node
// @Security Bearer
// @Success 200 {array} dto.AllowListItem
// @Failure 400 {object} api.HTTPError
// @Router /api/v4/node/hosting-allow-list [get]
func (n *Node) apiGetHostingAllowList(c *gin.Context) {
hostingAllowID := entry.NewAttributeID(universe.GetSystemPluginID(), "hosting_allow_list")
hostingAllowValue, ok := n.GetNodeAttributes().GetValue(hostingAllowID)
if !ok || hostingAllowValue == nil {
err := errors.New("Node: apiNodeGetChallenge: node attribute not found")
api.AbortRequest(c, http.StatusNotFound, "attribute_not_found", err, n.log)
return
}
allowedUserIDsInterface := utils.GetFromAnyMap(*hostingAllowValue, "users", []interface{}{})
allowedUserIDs := make([]string, 0, len(allowedUserIDsInterface))
for _, v := range allowedUserIDsInterface {
allowedUserIDs = append(allowedUserIDs, v.(string))
}
resolvedUsers := make([]*dto.AllowListItem, 0, len(allowedUserIDs))
for _, allowListUserID := range allowedUserIDs {
umidUserID := umid.MustParse(allowListUserID)
user, err := n.db.GetUsersDB().GetUserByID(c, umidUserID)
if err != nil {
err = errors.WithMessage(err, "Node: apiGetHostingAllowList: failed to GetUser")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
wallets, err := n.db.GetUsersDB().GetUserWalletsByUserID(c, umidUserID)
if err != nil {
err = errors.WithMessage(err, "Node: apiGetHostingAllowList: failed to GetUserWalletsByUserID")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
item := &dto.AllowListItem{
UserID: user.UserID.String(),
Wallets: wallets,
AvatarHash: *user.Profile.AvatarHash,
Name: *user.Profile.Name,
}
resolvedUsers = append(resolvedUsers, item)
}
c.JSON(http.StatusOK, resolvedUsers)
}
// @Summary Add user to node hosting allow list
// @Description Add user to hosting allow list
// @Tags hosting,node
// @Security Bearer
// @Param body body node.apiPostItemForHostingAllowList.Body true "body params"
// @Success 200 {object} nil
// @Failure 400 {object} api.HTTPError
// /api/v4/node/hosting-allow-list [post]
func (n *Node) apiPostItemForHostingAllowList(c *gin.Context) {
type Body struct {
UserID *umid.UMID `json:"user_id"`
Wallet *string `json:"wallet"`
}
var inBody Body
if err := c.ShouldBindJSON(&inBody); err != nil {
err = errors.WithMessage(err, "Node: apiPostHostingAllowListItem: failed to bind json")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
if inBody.Wallet == nil && inBody.UserID == nil {
err := errors.New("Node: apiPostHostingAllowListItem: user_id or wallet must be provided")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
if inBody.Wallet != nil && inBody.UserID != nil {
err := errors.New("Node: apiPostHostingAllowListItem: only one parameter should be provided: user_id or wallet")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
var userID umid.UMID
if inBody.Wallet != nil {
user, err := n.db.GetUsersDB().GetUserByWallet(c, *inBody.Wallet)
if err != nil {
err = errors.WithMessage(err, "Node: apiPostHostingAllowListItem: failed to GetUserByWallet")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
userID = user.UserID
} else {
userID = *inBody.UserID
}
hostingAllowID := entry.NewAttributeID(universe.GetSystemPluginID(), "hosting_allow_list")
hostingAllowValue, ok := n.GetNodeAttributes().GetValue(hostingAllowID)
if !ok || hostingAllowValue == nil {
err := errors.New("Node: apiNodeGetChallenge: node attribute not found")
api.AbortRequest(c, http.StatusNotFound, "attribute_not_found", err, n.log)
return
}
modifyFunc := func(v *entry.AttributeValue) (*entry.AttributeValue, error) {
if v == nil {
v = &entry.AttributeValue{}
(*v)["users"] = []interface{}{}
}
users := utils.GetFromAny((*v)["users"], []interface{}{})
if users == nil {
return nil, errors.New("Node: apiPostHostingAllowListItem: failed to get users from attribute value")
}
if !utils.AnyContains(users, userID.String()) {
(*v)["users"] = append(users, userID.String())
}
return v, nil
}
_, err := n.GetNodeAttributes().UpdateValue(hostingAllowID, modifyFunc, true)
if err != nil {
err = errors.WithMessage(err, "Node: apiPostHostingAllowListItem: failed to update attribute value")
api.AbortRequest(c, http.StatusInternalServerError, "internal_error", err, n.log)
return
}
c.JSON(http.StatusOK, nil)
}
// @Summary Remove user from node hosting allow list
// @Description Remove user from hosting allow list
// @Tags hosting,node
// @Security Bearer
// @Param user_id path string true "user_id"
// @Success 200 {object} nil
// @Failure 400 {object} api.HTTPError
// /api/v4/node/hosting-allow-list/{user_id} [delete]
func (n *Node) apiDeleteItemFromHostingAllowList(c *gin.Context) {
userID, err := umid.Parse(c.Param("userID"))
if err != nil {
err = errors.WithMessage(err, "Node: apiDeleteItemForHostingAllowList: failed to parse user_id")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
hostingAllowID := entry.NewAttributeID(universe.GetSystemPluginID(), "hosting_allow_list")
hostingAllowValue, ok := n.GetNodeAttributes().GetValue(hostingAllowID)
if !ok || hostingAllowValue == nil {
err := errors.New("Node: apiNodeGetChallenge: node attribute not found")
api.AbortRequest(c, http.StatusNotFound, "attribute_not_found", err, n.log)
return
}
modifyFunc := func(v *entry.AttributeValue) (*entry.AttributeValue, error) {
if v == nil {
v = &entry.AttributeValue{}
(*v)["users"] = []interface{}{}
}
users := utils.GetFromAny((*v)["users"], []interface{}{})
if users == nil {
return nil, errors.New("Node: apiDeleteItemForHostingAllowList: failed to get users from attribute value")
}
userIDStr := userID.String()
var filtered []interface{}
for _, id := range users {
if id.(string) != userIDStr {
filtered = append(filtered, id)
}
}
(*v)["users"] = filtered
return v, nil
}
_, err = n.GetNodeAttributes().UpdateValue(hostingAllowID, modifyFunc, true)
if err != nil {
err = errors.WithMessage(err, "Node: apiDeleteItemForHostingAllowList: failed to update attribute value")
api.AbortRequest(c, http.StatusInternalServerError, "internal_error", err, n.log)
return
}
c.JSON(http.StatusOK, nil)
}
// @Summary Activate plugin by hash
// @Description Activate plugin by hash
// @Tags plugins
// @Security Bearer
// @Param body body node.apiNodeActivatePlugin.Body true "body params"
// @Success 200 {object} nil
// @Failure 400 {object} api.HTTPError
// @Router /api/v4/node/activate-plugin [post]
func (n *Node) apiNodeActivatePlugin(c *gin.Context) {
type Body struct {
PluginHash string `json:"plugin_hash" binding:"required"`
}
var inBody Body
if err := c.ShouldBindJSON(&inBody); err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to bind json")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
manifest, err := n.media.GetPluginManifest(inBody.PluginHash)
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to get plugin manifest")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
n.log.Debug("Register plugin by manifest:", manifest)
// Create/Update plugin
var plugin universe.Plugin
n.GetPlugins().FilterPlugins(func(pluginID umid.UMID, p universe.Plugin) bool {
if p.GetMeta()["name"] == manifest.Name {
plugin = p
}
return false
})
pluginMeta := entry.PluginMeta{
"name": manifest.Name,
"displayName": manifest.DisplayName,
"description": manifest.Description,
"version": manifest.Version,
"author": manifest.Author,
"repository": manifest.Repository,
"homepage": manifest.Homepage,
"license": manifest.License,
"attribute_types": manifest.AttributeTypes,
"scopes": manifest.Scopes,
"scopeName": manifest.Name,
"hash": inBody.PluginHash,
"scriptUrl": inBody.PluginHash,
}
if plugin == nil {
plugin, err = n.plugins.CreatePlugin(umid.New())
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to create plugin")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
err = n.plugins.Save()
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to save plugins")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
}
err = plugin.SetMeta(pluginMeta, true)
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to set plugin meta")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
// Create/Update attributes
if manifest.AttributeTypes != nil {
for _, attrTypeDescription := range *manifest.AttributeTypes {
n.log.Debug("Process attrTypeDescription:", attrTypeDescription, "plugin.GetID():", plugin.GetID().String())
attrTypeID := entry.NewAttributeTypeID(plugin.GetID(), attrTypeDescription.Name)
attrType, _ := n.attributeTypes.GetAttributeType(attrTypeID)
if attrType == nil {
n.log.Debug("Create attribute type:", attrTypeID)
attrType, err = n.attributeTypes.CreateAttributeType(attrTypeID)
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to create attribute type")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
}
description := attrTypeDescription.Description
err = attrType.SetDescription(&description, true)
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to set attribute type description")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
modifyFn := func(options *entry.AttributeOptions) (*entry.AttributeOptions, error) {
if attrTypeDescription.Sync == nil {
return nil, nil
}
if *attrTypeDescription.Sync == "object" {
scope := make([]string, 1)
scope[0] = "object"
posbus_auto := make(map[string]interface{})
posbus_auto["scope"] = scope
posbus_auto["send_to"] = 1
options = &entry.AttributeOptions{
"posbus_auto": posbus_auto,
}
}
return options, nil
}
attrType.SetOptions(modifyFn, false)
}
err = n.attributeTypes.Save()
if err != nil {
err = errors.WithMessage(err, "Node: apiNodeRegisterPlugin: failed to save attribute types")
api.AbortRequest(c, http.StatusBadRequest, "invalid_request_body", err, n.log)
return
}
}
}