-
Notifications
You must be signed in to change notification settings - Fork 0
/
httproutes.go
593 lines (507 loc) · 15 KB
/
httproutes.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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package internet
import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/go-chi/chi"
"github.com/pkg/errors"
"github.com/getblank/blank-router/taskq"
"github.com/getblank/blank-sr/config"
"github.com/getblank/uuid"
"github.com/getblank/blank-one/sr"
)
const apiV1baseURI = "/api/v1/"
var (
routesBuildingCompleted bool
paramConverterRGX = regexp.MustCompile(":([a-zA-Z]+[a-zA-Z0-9]*)")
)
type result struct {
Type string `json:"type"`
Data string `json:"data"`
RAWData interface{} `json:"rawData"`
Code int `json:"code"`
Header map[string]string `json:"header"`
FileName string `json:"fileName"`
FilePath string `json:"filePath"`
Store string `json:"store"`
ID string `json:"_id"`
}
func onConfigUpdate(c map[string]config.Store) {
wamp.Disconnect()
log.Info("New config arrived")
if routesBuildingCompleted {
log.Warn("Routes already built. Need to restart if http hooks or actions modified.")
}
httpEnabledStores := []config.Store{}
for s, store := range c {
if !strings.HasPrefix(store.Store, "_") {
httpEnabledStores = append(httpEnabledStores, store)
}
storeName := s
groupURI := "/hooks/" + storeName
var lowerGroupURI string
var lowerGroup chi.Router
if lowerStoreName := strings.ToLower(storeName); lowerStoreName != storeName {
lowerGroupURI = "/hooks/" + lowerStoreName
lowerGroup = r.Route(lowerGroupURI, nil)
}
group := r.Route(groupURI, nil)
for i, hook := range store.HTTPHooks {
hook.URI = convertHookURI(hook.URI)
if len(hook.URI) == 0 {
log.Error("Empty URI in hook", strconv.Itoa(i), " for "+groupURI+". Will ignored")
continue
}
var handler func(pattern string, handlerFn http.HandlerFunc)
var lowerHandler func(pattern string, handlerFn http.HandlerFunc)
switch hook.Method {
case "GET", "Get", "get":
handler = group.Get
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Get
}
case "POST", "Post", "post":
handler = group.Post
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Post
}
case "PUT", "Put", "put":
handler = group.Put
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Put
}
case "PATCH", "Patch", "patch":
handler = group.Patch
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Patch
}
case "DELETE", "Delete", "delete":
handler = group.Delete
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Delete
}
case "HEAD", "Head", "head":
handler = group.Head
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Head
}
case "OPTIONS", "Options", "options":
handler = group.Options
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Options
}
default:
log.Warn("UNKNOWN HTTP METHOD. Will use GET method ", hook)
handler = group.Get
if lowerGroupURI != "" {
lowerHandler = lowerGroup.Get
}
}
hookIndex := i
hookHandler := func(w http.ResponseWriter, r *http.Request) {
t := taskq.Task{
Store: storeName,
Type: taskq.HTTPHook,
UserID: "root",
Arguments: map[string]interface{}{
"request": extractRequest(r),
"hookIndex": hookIndex,
},
}
_res, err := taskq.PushAndGetResult(&t, 0)
if err != nil {
errorResponse(w, http.StatusSeeOther, err)
return
}
res, err := parseResult(_res)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err)
return
}
defaultResponse(w, r, res)
}
handler(hook.URI, hookHandler)
log.Infof("Created '%s' httpHook for store '%s' with path %s", hook.Method, storeName, groupURI+hook.URI)
if lowerHandler != nil {
lowerHandler(hook.URI, hookHandler)
log.Infof("Created '%s' httpHook on lower case for store '%s' with path %s", hook.Method, storeName, lowerGroupURI+hook.URI)
}
}
if len(store.Actions) > 0 {
createHTTPActions(storeName, store.Actions)
}
if len(store.StoreActions) > 0 {
createHTTPActions(storeName, store.StoreActions)
}
if store.Type == "file" || store.Type == "files" {
createFileHandlers(storeName)
}
}
routesBuildingCompleted = true
log.Info("Routes building complete")
createRESTAPI(httpEnabledStores)
log.Info("REST API building complete")
}
func createFileHandlers(storeName string) {
groupURI := fmt.Sprintf("/files/%s", storeName)
group := r.Route(groupURI, nil)
group.With(jwtAuthMiddleware(false)).Post("/", postFileHandler(storeName))
group.With(jwtAuthMiddleware(true)).Get("/:id", getFileHandler(storeName))
group.With(jwtAuthMiddleware(false)).Post("/:id", postFileHandler(storeName))
group.With(jwtAuthMiddleware(false)).Delete("/:id", deleteFileHandler(storeName))
log.Infof("Created handlers for fileStore '%s' with path %s", storeName, groupURI)
}
func writeFileFromFileStore(w http.ResponseWriter, storeName, fileID, fileName string) {
res, err := http.Get(fmt.Sprintf("%s/%s/%s", sr.FSAddress(), storeName, fileID))
if err != nil {
jsonResponseWithStatus(w, res.StatusCode, res.Status)
return
}
defer res.Body.Close()
if len(fileName) == 0 {
if _, params, err := mime.ParseMediaType(res.Header.Get(headerContentDisposition)); err == nil && len(params["filename"]) > 0 {
fileName = params["filename"]
} else {
fileName = res.Header.Get("File-Name")
}
}
for k, v := range res.Header {
if k == "File-Name" {
continue
}
for _, h := range v {
w.Header().Add(k, h)
}
}
w.Header().Set(headerContentDisposition, fmt.Sprintf("attachment; filename=%s", fileName))
body, _ := ioutil.ReadAll(res.Body)
if _, err := w.Write(body); err != nil {
log.Errorf("[writeFileFromFileStore] write error: %v", err)
}
}
func createHTTPActions(storeName string, actions []config.Action) {
groupURI := fmt.Sprintf("/actions/%s", storeName)
for _, v := range actions {
actionID := v.ID
handler := func(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value(credKey)
if c == nil {
log.Warn("HTTP ACTION: no cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
cred, ok := c.(credentials)
if !ok {
log.Warn("HTTP ACTION: invalid cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
t := taskq.Task{
Store: storeName,
Type: taskq.DbAction,
UserID: cred.userID,
Arguments: map[string]interface{}{
"request": extractRequest(r),
"actionId": actionID,
},
}
if cred.claims != nil {
t.Arguments["tokenInfo"] = cred.claims.toMap()
}
if itemID := r.URL.Query().Get("item-id"); len(itemID) > 0 {
t.Arguments["itemId"] = itemID
}
_res, err := taskq.PushAndGetResult(&t, 0)
if err != nil {
errorResponse(w, http.StatusSeeOther, err)
return
}
res, err := parseResult(_res)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err)
return
}
defaultResponse(w, r, res)
}
if v.Type == "http" {
r.With(jwtAuthMiddleware(false)).Get(fmt.Sprintf("%s/%s", groupURI, v.ID), handler)
} else {
r.With(jwtAuthMiddleware(false)).Post(fmt.Sprintf("%s/%s", groupURI, v.ID), handler)
}
log.Infof("Registered httpAction for store '%s' with path %s", storeName, groupURI+v.ID)
}
}
func extractRequest(r *http.Request) map[string]interface{} {
routeCtx := chi.RouteContext(r.Context())
urlParams := routeCtx.URLParams
params := map[string]string{}
for _, p := range urlParams.Keys {
params[p] = routeCtx.URLParam(p)
}
header := map[string]string{}
for k, v := range r.Header {
if len(v) > 0 {
header[k] = v[0]
}
}
if err := r.ParseMultipartForm(1024); err != nil {
if err := r.ParseForm(); err != nil {
log.Debugf("[extractRequest] extract form data error: %v", err)
}
}
formParams := r.PostForm
var data interface{}
if d := formParams.Get("data"); len(d) > 0 {
data = d
}
var body string
b, err := ioutil.ReadAll(r.Body)
if err != nil && err != io.EOF {
log.Errorf("Can't read request http body. Error: %v", err)
} else {
if rtype := header["Content-Type"]; strings.HasPrefix(rtype, "application/json") || strings.HasPrefix(rtype, "text/plain") {
body = string(b)
} else {
body = base64.StdEncoding.EncodeToString(b)
}
}
return map[string]interface{}{
"params": params,
"query": r.URL.Query(),
"form": formParams,
"ip": r.RemoteAddr,
"referer": r.Referer(),
"header": header,
"body": body,
"data": data,
}
}
func defaultResponse(w http.ResponseWriter, r *http.Request, res *result) {
if res == nil {
jsonResponse(w, http.StatusText(http.StatusOK))
return
}
code := res.Code
if code == 0 {
code = http.StatusOK
}
for k, v := range res.Header {
w.Header().Set(k, v)
}
switch res.Type {
case "REDIRECT", "redirect":
if code == 200 {
code = http.StatusFound
}
redirectResponseWithStatus(w, code, res.Data)
return
case "JSON", "json":
if res.RAWData == nil {
jsonBlobResponseWithStatus(w, code, []byte(res.Data))
return
}
jsonResponseWithStatus(w, code, res.RAWData)
return
case "HTML", "html":
htmlResponseWithStatus(w, code, res.Data)
return
case "XML", "xml":
xmlResponseWithStatus(w, code, []byte(res.Data))
return
case "file":
responseFile(w, r, res)
return
default:
jsonResponseWithStatus(w, http.StatusSeeOther, "unknown encoding type")
return
}
}
func responseFile(w http.ResponseWriter, r *http.Request, res *result) {
if len(res.Store) > 0 && len(res.ID) > 0 {
writeFileFromFileStore(w, res.Store, res.ID, res.FileName)
return
}
if len(res.FilePath) > 0 {
fileName := res.FileName
if len(fileName) == 0 {
fileName = filepath.Base(res.FilePath)
}
if len(w.Header().Get(headerContentDisposition)) == 0 {
w.Header().Set(headerContentDisposition, fmt.Sprintf("attachment; filename=%s", fileName))
}
http.ServeFile(w, r, res.FilePath)
return
}
var content []byte
var err error
content, err = base64.StdEncoding.DecodeString(res.Data)
if err != nil {
jsonResponseWithStatus(w, http.StatusInternalServerError, fmt.Sprintf("can't read file, error: %v", err))
return
}
if len(w.Header().Get(headerContentDisposition)) == 0 {
w.Header().Set(headerContentDisposition, fmt.Sprintf("attachment; filename=%s", res.FileName))
}
if len(w.Header().Get(headerContentType)) == 0 {
w.Header().Set(headerContentType, detectContentType(res.FileName, content))
}
if _, err := w.Write(content); err != nil {
log.Debugf("[responseFile] write error: %v", err)
}
}
func parseResult(in interface{}) (*result, error) {
if in == nil {
return nil, nil
}
encoded, err := json.Marshal(in)
if err != nil {
return nil, errors.Wrap(err, "when parse result")
}
res := new(result)
err = json.Unmarshal(encoded, res)
if err != nil {
err = errors.Wrap(err, "when unmarshal result")
}
return res, err
}
func getFileHandler(storeName string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value(credKey)
if c == nil {
log.Warn("[file get]: no cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
cred, ok := c.(credentials)
if !ok {
log.Warn("[file get]: invalid cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
fileID := chi.URLParam(r, "id")
t := taskq.Task{
Type: taskq.DbGet,
UserID: cred.userID,
Store: storeName,
Arguments: map[string]interface{}{"_id": fileID},
}
if cred.claims != nil {
t.Arguments["tokenInfo"] = cred.claims.toMap()
}
_, err := taskq.PushAndGetResult(&t, 0)
if err != nil {
errorResponse(w, http.StatusBadRequest, err)
return
}
writeFileFromFileStore(w, storeName, fileID, "")
}
}
func postFileHandler(storeName string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value(credKey)
if c == nil {
log.Warn("[file post]: no cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
cred, ok := c.(credentials)
if !ok {
log.Warn("[file post]: invalid cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
fileID := chi.URLParam(r, "id")
if len(fileID) == 0 {
fileID = uuid.NewV4()
}
_, fileHeader, err := r.FormFile("file")
if err != nil {
jsonResponseWithStatus(w, http.StatusBadRequest, http.StatusText(http.StatusBadRequest))
return
}
fileName := fileHeader.Filename
t := taskq.Task{
Type: taskq.DbSet,
UserID: cred.userID,
Store: storeName,
Arguments: map[string]interface{}{"item": map[string]string{"_id": fileID, "name": fileName}},
}
if cred.claims != nil {
t.Arguments["tokenInfo"] = cred.claims.toMap()
}
_, err = taskq.PushAndGetResult(&t, 0)
if err != nil {
errorResponse(w, http.StatusBadRequest, err)
return
}
file, err := fileHeader.Open()
if err != nil {
errorResponse(w, http.StatusInternalServerError, err)
return
}
defer file.Close()
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/%s/%s", sr.FSAddress(), storeName, fileID), file)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err)
return
}
req.Header.Set("File-Name", fileName)
req.Header.Set(headerContentDisposition, fmt.Sprintf(`attachment; filename="%s"`, fileName))
client := &http.Client{}
_, err = client.Do(req)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err)
return
}
jsonResponse(w, fileID)
}
}
func deleteFileHandler(storeName string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value(credKey)
if c == nil {
log.Warn("[file delete]: no cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
cred, ok := c.(credentials)
if !ok {
log.Warn("[file delete]: invalid cred in echo context")
jsonResponseWithStatus(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
fileID := chi.URLParam(r, "id")
t := taskq.Task{
Type: taskq.DbDelete,
UserID: cred.userID,
Store: storeName,
Arguments: map[string]interface{}{"item": map[string]string{"_id": fileID}},
}
if cred.claims != nil {
t.Arguments["tokenInfo"] = cred.claims.toMap()
}
_, err := taskq.PushAndGetResult(&t, 0)
if err != nil {
errorResponse(w, http.StatusBadRequest, err)
return
}
jsonResponse(w, http.StatusText(http.StatusOK))
}
}
func convertHookURI(uri string) string {
matched := paramConverterRGX.FindAllStringSubmatch(uri, -1)
for _, v := range matched {
uri = strings.Replace(uri, v[0], fmt.Sprintf("{%s}", v[1]), 1)
}
if !strings.HasPrefix(uri, "/") {
uri = "/" + uri
}
return uri
}