-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
517 lines (443 loc) · 15.3 KB
/
http.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
package servers
import (
"context"
"encoding/json"
"net/http"
"time"
"net"
"github.com/ellcrys/util"
"github.com/gorilla/mux"
"github.com/jinzhu/copier"
"github.com/labstack/gommon/log"
"github.com/ellcrys/cocoon/core/config"
"github.com/ellcrys/patchain"
"github.com/ellcrys/patchain/object"
"github.com/ellcrys/safehold/servers/common"
"github.com/ellcrys/safehold/servers/oauth"
"github.com/ellcrys/safehold/servers/proto_rpc"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
var logHTTP = config.MakeLogger("http")
// HTTP defines a structure for an HTTP server
// that provides REST API services.
type HTTP struct {
rpcServerAddr string
oauth *oauth.OAuth
db patchain.DB
}
// NewHTTP creates an new http server instance
func NewHTTP(db patchain.DB, rpcServerAddr string) *HTTP {
return &HTTP{
rpcServerAddr: rpcServerAddr,
db: db,
oauth: oauth.NewOAuth(db),
}
}
// getRouter returns the router
func (s *HTTP) getRouter() *mux.Router {
r := mux.NewRouter()
// oauth endpoints
r.HandleFunc("/token", common.EasyHandle(http.MethodPost, s.oauth.GetToken))
g := r.PathPrefix("/v1").Subrouter()
// v1 endpoints
g.HandleFunc("/identities", common.EasyHandle(http.MethodPost, s.createIdentity))
g.HandleFunc("/identities/{id}", common.EasyHandle(http.MethodGet, s.getIdentity))
g.HandleFunc("/mappings", common.EasyHandle(http.MethodPost, s.createMapping)).Methods(http.MethodPost)
g.HandleFunc("/mappings", common.EasyHandle(http.MethodGet, s.getAllMapping)).Methods(http.MethodGet)
g.HandleFunc("/mappings/{name}", common.EasyHandle(http.MethodGet, s.getMapping))
g.HandleFunc("/sessions", common.EasyHandle(http.MethodPost, s.createSession))
g.HandleFunc("/sessions/{id}", common.EasyHandle(http.MethodGet, s.getSession)).Methods(http.MethodGet)
g.HandleFunc("/sessions/{id}", common.EasyHandle(http.MethodDelete, s.deleteSession)).Methods(http.MethodDelete)
g.HandleFunc("/sessions/{id}/commit", common.EasyHandle(http.MethodGet, s.commitSession)).Methods(http.MethodGet)
g.HandleFunc("/sessions/{id}/rollback", common.EasyHandle(http.MethodGet, s.rollbackSession)).Methods(http.MethodGet)
g.HandleFunc("/objects", common.EasyHandle(http.MethodPost, s.createObjects)).Methods(http.MethodPost)
g.HandleFunc("/objects/query", common.EasyHandle(http.MethodPost, s.getObjects)).Methods(http.MethodPost)
g.HandleFunc("/objects/count", common.EasyHandle(http.MethodPost, s.countObjects)).Methods(http.MethodPost)
return r
}
// dialRPC creates a client connection to the RPC API
// and passes it to the callback function. It will close the connection
// after the callback function has finished
func (s *HTTP) dialRPC(cb func(client proto_rpc.APIClient) error) error {
conn, err := grpc.Dial(s.rpcServerAddr, grpc.WithInsecure())
if err != nil {
return errors.Wrap(err, "failed to dial RPC API")
}
defer conn.Close()
return cb(proto_rpc.NewAPIClient(conn))
}
// Start starts the http server. Passes true to the startedCh channel
// when started
func (s *HTTP) Start(addr string, startedCB func(*HTTP)) error {
_, port, err := net.SplitHostPort(addr)
if err != nil {
logHTTP.Errorf("%+v", errors.Wrap(err, "failed to parse address"))
return err
}
// attempt to connect to the RPC API
if err := s.dialRPC(func(client proto_rpc.APIClient) error {
return nil
}); err != nil {
logHTTP.Errorf("%+v", err)
return err
}
time.AfterFunc(2*time.Second, func() {
logHTTP.Infof("Started HTTP API server @ :%s", port)
if startedCB != nil {
startedCB(s)
}
})
return http.ListenAndServe(addr, s.getRouter())
}
// createSession creates a new session
func (s *HTTP) createSession(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var body proto_rpc.DBSession
var resp *proto_rpc.DBSession
if err = json.NewDecoder(r.Body).Decode(&body); err != nil {
return common.BodyMalformedError, 400
}
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md metadata.MD
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.CreateDBSession(ctx, &body)
return err
}); err != nil {
logHTTP.Errorf("%+v", err)
return err, 0
}
return resp, 201
}
// getSession gets a new session
func (s *HTTP) getSession(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.DBSession
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md metadata.MD
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.GetDBSession(ctx, &proto_rpc.DBSession{
ID: mux.Vars(r)["id"],
})
return err
}); err != nil {
logHTTP.Errorf("%+v", err)
return err, 0
}
return resp, 200
}
// deleteSession deletes a session
func (s *HTTP) deleteSession(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.DBSession
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md metadata.MD
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.DeleteDBSession(ctx, &proto_rpc.DBSession{
ID: mux.Vars(r)["id"],
})
return err
}); err != nil {
logHTTP.Errorf("%+v", err)
return err, 0
}
return resp, 200
}
// commitSession commits a session
func (s *HTTP) commitSession(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.DBSession
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md metadata.MD
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.CommitSession(ctx, &proto_rpc.DBSession{
ID: mux.Vars(r)["id"],
})
return err
}); err != nil {
logHTTP.Errorf("%+v", err)
return err, 0
}
return resp, 200
}
// rollbackSession rolls back a session
func (s *HTTP) rollbackSession(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.DBSession
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md metadata.MD
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.RollbackSession(ctx, &proto_rpc.DBSession{
ID: mux.Vars(r)["id"],
})
return err
}); err != nil {
logHTTP.Errorf("%+v", err)
return err, 0
}
return resp, 200
}
// createIdentity creates an identity
func (s *HTTP) createIdentity(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var body proto_rpc.CreateIdentityMsg
var resp *proto_rpc.GetObjectResponse
if err = json.NewDecoder(r.Body).Decode(&body); err != nil {
return common.BodyMalformedError, 400
}
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
resp, err = client.CreateIdentity(context.Background(), &body)
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
var identity map[string]interface{}
util.FromJSON(resp.Object, &identity)
return common.SingleObjectResp("identity", identity), 201
}
// createMapping creates a mapping for an identity
func (s *HTTP) createMapping(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var body struct {
Name string `json:"name"`
Mapping map[string]interface{} `json:"mapping"`
}
var resp *proto_rpc.CreateMappingResponse
if err = json.NewDecoder(r.Body).Decode(&body); err != nil {
return common.BodyMalformedError, 400
}
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
authorization := r.Header.Get("Authorization")
var md metadata.MD
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.CreateMapping(ctx, &proto_rpc.CreateMappingMsg{
Name: body.Name,
Mapping: util.MustStringify(body.Mapping),
})
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
return resp, 201
}
// getMapping fetches a mapping belonging to the logged in developer
func (s *HTTP) getMapping(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var md metadata.MD
var resp *proto_rpc.GetMappingResponse
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.GetMapping(ctx, &proto_rpc.GetMappingMsg{
Name: mux.Vars(r)["name"],
})
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
var respMap map[string]interface{}
if err := util.FromJSON(resp.Mapping, &respMap); err != nil {
logHTTP.Errorf("%+v", errors.Wrap(err, "failed to parse response to json"))
return common.ServerError, 500
}
var mapping map[string]interface{}
util.FromJSON([]byte(respMap["value"].(string)), &mapping)
return common.SingleObjectResp("mapping", map[string]interface{}{
"id": respMap["id"],
"name": mux.Vars(r)["name"],
"mapping": mapping,
}), 200
}
// getAllMapping fetches the most recent mappings belonging to the logged in developer
func (s *HTTP) getAllMapping(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var md metadata.MD
var authorization = r.Header.Get("Authorization")
var resp *proto_rpc.GetAllMappingResponse
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.GetAllMapping(ctx, &proto_rpc.GetAllMappingMsg{
Limit: 50,
Name: r.URL.Query().Get("name"),
})
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
var respMaps []map[string]interface{}
util.FromJSON(resp.Mappings, &respMaps)
attrs := make([]map[string]interface{}, len(respMaps))
for i, mapping := range respMaps {
var mappingVal map[string]string
util.FromJSON([]byte(mapping["value"].(string)), &mappingVal)
_, name, _ := object.SplitKey(mapping["key"].(string))
attrs[i] = map[string]interface{}{
"id": mapping["id"],
"name": name,
"mapping": mappingVal,
}
}
return common.MultiObjectResp("mapping", attrs), 200
}
// getIdentity gets an identity
func (s *HTTP) getIdentity(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.GetObjectResponse
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md metadata.MD
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Pairs("authorization", authorization)
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.GetIdentity(ctx, &proto_rpc.GetIdentityMsg{
ID: mux.Vars(r)["id"],
})
return err
}); err != nil {
logHTTP.Errorf("%+v", err)
return err, 0
}
var identity map[string]interface{}
util.FromJSON(resp.Object, &identity)
return common.SingleObjectResp("identity", identity), 200
}
// createObjects creates an arbitrary object.
// Requires an app token included in the authorization header.
// If mapping name is provided, pass the mapping name and body encoded in json to rpc.CreateObjects
// so that it can process/unmap the custom/mapped fields in the request body.
// Otherwise, copy the body into a slice of proto_rpc.Object and pass this.
func (s *HTTP) createObjects(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var bodyJSON []map[string]interface{}
var resp *proto_rpc.GetObjectsResponse
var mappingName = r.URL.Query().Get("mapping")
var sessionID = r.URL.Query().Get("session")
var md = metadata.Join(metadata.Pairs("session_id", sessionID))
var authorization = r.Header.Get("Authorization")
if err = json.NewDecoder(r.Body).Decode(&bodyJSON); err != nil {
return common.BodyMalformedError, 400
}
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
if len(authorization) > 0 {
md = metadata.Join(md, metadata.Pairs("authorization", authorization))
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.CreateObjects(ctx, &proto_rpc.CreateObjectsMsg{
Objects: util.MustStringify(bodyJSON),
Mapping: mappingName,
})
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
var objects []map[string]interface{}
util.FromJSON(resp.Objects, &objects)
return common.MultiObjectResp("objects", objects), 201
}
// getObjects performs query operations
func (s *HTTP) getObjects(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.GetObjectsResponse
var rpcBody proto_rpc.GetObjectMsg
var mappingName = r.URL.Query().Get("mapping")
var sessionID = r.URL.Query().Get("session")
var md = metadata.Join(metadata.Pairs("session_id", sessionID))
var authorization = r.Header.Get("Authorization")
var body struct {
Query map[string]interface{} `json:"query"`
Owner string `json:"owner"`
Creator string `json:"creator"`
Limit int32 `json:"limit"`
Order []struct {
Field string `json:"field"`
Order int32 `json:"order"`
} `json:"order"`
}
if err = json.NewDecoder(r.Body).Decode(&body); err != nil {
return common.BodyMalformedError, 400
}
copier.Copy(&rpcBody, body)
rpcBody.Query = util.MustStringify(body.Query)
rpcBody.Mapping = mappingName
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
if len(authorization) > 0 {
md = metadata.Join(md, metadata.Pairs("authorization", authorization))
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.GetObjects(ctx, &rpcBody)
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
var objects []map[string]interface{}
util.FromJSON(resp.Objects, &objects)
return common.MultiObjectResp("object", objects), 200
}
// countObjects counts objects matching a query
func (s *HTTP) countObjects(w http.ResponseWriter, r *http.Request) (interface{}, int) {
var err error
var resp *proto_rpc.ObjectCountResponse
var rpcBody proto_rpc.GetObjectMsg
var body struct {
Query map[string]interface{} `json:"query"`
Owner string `json:"owner"`
Creator string `json:"creator"`
}
if err = json.NewDecoder(r.Body).Decode(&body); err != nil {
return common.BodyMalformedError, 400
}
copier.Copy(&rpcBody, body)
rpcBody.Query = util.MustStringify(body.Query)
var sessionID = r.URL.Query().Get("session")
if err = s.dialRPC(func(client proto_rpc.APIClient) error {
var md = metadata.Join(metadata.Pairs("session_id", sessionID))
authorization := r.Header.Get("Authorization")
if len(authorization) > 0 {
md = metadata.Join(md, metadata.Pairs("authorization", authorization))
}
ctx := metadata.NewContext(context.Background(), md)
resp, err = client.CountObjects(ctx, &rpcBody)
return err
}); err != nil {
log.Errorf("%+v", err)
return err, 0
}
return resp, 200
}