/
handlers.go
607 lines (459 loc) · 15.7 KB
/
handlers.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package handlers
import (
"bytes"
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/context"
"go.uber.org/zap"
"io"
"net/http"
"net/url"
"os/exec"
"regexp"
"strings"
"time"
)
/////////////////
/// for debugging
/////////////////
// formatRequest generates ascii representation of a request
func formatRequest(r *http.Request) string {
// Create return string
var request []string
// Add the request string
url := fmt.Sprintf("%v %v %v", r.Method, r.URL, r.Proto)
request = append(request, url)
// Add the host
request = append(request, fmt.Sprintf("Host: %v", r.Host))
// Loop through headers
for name, headers := range r.Header {
name = strings.ToLower(name)
for _, h := range headers {
request = append(request, fmt.Sprintf("%v: %v", name, h))
}
}
// If this is a POST, add post data
if r.Method == "POST" {
r.ParseForm()
request = append(request, "\n")
request = append(request, r.Form.Encode())
}
// Return the request as a string
return strings.Join(request, "\n")
}
/////////////////
type CmdError struct {
Error string `json:"error"`
Statuscode int `json:"statuscode"`
}
func CheckSharedSecret(logger *zap.Logger, secret string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The secret is passed in the header: Authorization: Bearer mysecret
h := r.Header.Get("Authorization")
secret := "bearer " + secret
if secret != strings.ToLower(h) {
logger.Warn("wrong secret")
w.WriteHeader(http.StatusUnauthorized)
return
}
handler.ServeHTTP(w, r)
})
}
func CheckNothing(logger *zap.Logger, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
}
func CheckHostAllowed(origin url.URL, allowFrom string, logger *zap.Logger) bool {
if origin.Scheme != "https" {
logger.Info(fmt.Sprintf("***** Only https scheme is supported. Origin is %s", origin))
return false
}
// TODO: case insensitive
matched, _ := regexp.MatchString(allowFrom, origin.Host)
logger.Info(fmt.Sprintf("***** Checking Allowed Host: %s matches %s => %b", origin.String(), allowFrom, matched))
return matched
}
func Token(logger *zap.Logger, signKey string, allowFrom string, shibReferer string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info(formatRequest(r))
username := r.Header.Get("adfs_login") // this comes back from shibolleth (the name of the header depends on shibd configuration)
if username == "" {
logger.Error("Request header 'adfs_login' is empty or not set")
w.WriteHeader(http.StatusBadRequest)
return
}
m, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
logger.Error(fmt.Sprintf("URL query parsing error: %s '%s' ", err))
w.WriteHeader(http.StatusBadRequest)
return
}
var origin string
if val, ok := m["Origin"]; ok {
origin = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing origin query parameter"))
w.WriteHeader(http.StatusBadRequest)
return
}
referer, err := url.Parse(origin)
if err != nil {
logger.Error(fmt.Sprintf("Error parsing Referer header: '%s' %s", r.Header.Get("Referer"), err))
w.WriteHeader(http.StatusBadRequest)
return
}
referer_url := url.URL{Scheme: referer.Scheme, Host: referer.Host}
referer_host := referer_url.String() // format the allowed host including the scheme
// TODO(labkode): check with kuba
if referer_host == shibReferer {
w.WriteHeader(http.StatusNoContent)
return
}
if !CheckHostAllowed(*referer, allowFrom, logger) {
logger.Error(fmt.Sprintf("Referer host '%s' does not match allowFrom pattern '%s'", referer.Host, allowFrom))
w.WriteHeader(http.StatusBadRequest)
return
}
//logger.Info(fmt.Sprintf("***** ALLOWED_HOST: %s",referer_host))
expire := time.Now().Add(time.Duration(3600) * time.Second) // TODO(labkode): expire data in config
token := jwt.New(jwt.GetSigningMethod("HS256"))
claims := token.Claims.(jwt.MapClaims)
claims["username"] = username
claims["exp"] = expire.UnixNano()
tokenString, _ := token.SignedString([]byte(signKey))
response := &struct {
Token string `json:"authtoken"`
Expire time.Time `json:"expire"`
}{Token: tokenString, Expire: expire}
jsonBody, _ := json.Marshal(response)
w.Header().Set("X-Frame-Options", fmt.Sprintf("ALLOW-FROM %s", referer_host))
w.WriteHeader(http.StatusOK)
w.Write([]byte("<script>parent.postMessage(" + string(jsonBody) + ", '" + referer_host + "');</script>"))
})
}
func CheckJWTToken(logger *zap.Logger, signKey string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The jwt token is passed in the header: Authorization: Bearer mysecret
h := r.Header.Get("Authorization")
parts := strings.Split(h, " ")
if len(parts) != 2 {
logger.Error("wrong JWT header")
w.WriteHeader(http.StatusUnauthorized)
return
}
token := parts[1]
rawToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return []byte(signKey), nil
})
if err != nil {
logger.Error("invalid JWT token")
w.WriteHeader(http.StatusUnauthorized)
return
}
claims := rawToken.Claims.(jwt.MapClaims)
username, ok := claims["username"].(string)
if !ok {
logger.Error("jwt token username claim is not a string")
w.WriteHeader(http.StatusUnauthorized)
return
}
context.Set(r, "username", username)
fmt.Println(r.URL)
handler.ServeHTTP(w, r)
})
}
func Handle404(logger *zap.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
return
})
}
func Handle200(logger *zap.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info(formatRequest(r))
//w.WriteHeader(http.Success)
})
}
// Handle CORS Origin header and return true if the request is allowed to continue
func CORSProcessOriginHeader(logger *zap.Logger, w http.ResponseWriter, r *http.Request, allowFrom string) bool {
origin, err := url.Parse(r.Header.Get("Origin"))
if err != nil {
logger.Error(fmt.Sprintf("Error parsing Origin header: '%s' %s", r.Header.Get("Origin"), err))
w.WriteHeader(http.StatusBadRequest)
return false
}
if !CheckHostAllowed(*origin, allowFrom, logger) {
logger.Error(fmt.Sprintf("Origin URL '%s' does not match allowFrom pattern '%s'", origin, allowFrom))
w.WriteHeader(http.StatusBadRequest)
return false
}
w.Header().Set("Access-Control-Allow-Origin", origin.String())
return true
}
func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func Options(logger *zap.Logger, allowedMethods []string, allowFrom string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !CORSProcessOriginHeader(logger, w, r, allowFrom) {
return
}
x := r.Header.Get("Access-Control-Request-Headers")
if strings.ToUpper(x) != "AUTHORIZATION" {
logger.Error(fmt.Sprintf("OPTIONS: Wrong or missing Access-Control-Request-Headers header: '%s'", x))
w.WriteHeader(http.StatusBadRequest)
return
}
x = r.Header.Get("Access-Control-Request-Method")
if !stringInSlice(strings.ToUpper(x), allowedMethods) {
logger.Error(fmt.Sprintf("OPTIONS: Wrong or missing Access-Control-Request-Method header: '%' ", x))
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowedMethods, ","))
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
})
}
/* ------------------------ */
func executeCMD(cmd *exec.Cmd) (*bytes.Buffer, *bytes.Buffer, error) {
outBuf := &bytes.Buffer{}
errBuf := &bytes.Buffer{}
cmd.Stdout = outBuf
cmd.Stderr = errBuf
err := cmd.Run()
return outBuf, errBuf, err
}
func Search(logger *zap.Logger, allowFrom, cboxgroupdUrl, cboxgroupdSecret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !CORSProcessOriginHeader(logger, w, r, allowFrom) {
return
}
params := r.URL.Query()
filter := params.Get("filter")
fmt.Printf("filter:%s\n", filter)
url := strings.Join([]string{cboxgroupdUrl, filter}, "/")
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", cboxgroupdSecret))
res, err := http.DefaultClient.Do(req)
if err != nil {
logger.Error(fmt.Sprintf("error sending request: %s", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(res.StatusCode)
defer res.Body.Close()
io.Copy(w, res.Body)
})
}
func CloneShare(logger *zap.Logger, cboxShareScript string, allowFrom string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !CORSProcessOriginHeader(logger, w, r, allowFrom) {
return
}
v := context.Get(r, "username")
username, _ := v.(string)
logger.Info("loggedin user is " + username)
sharer := ""
shared_project := ""
cloned_project := ""
m, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
logger.Error(fmt.Sprintf("URL query parsing error: %s '%s' ", err))
w.WriteHeader(http.StatusBadRequest)
return
}
if val, ok := m["sharer"]; ok {
sharer = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing query parameter: sharer not specified"))
w.WriteHeader(http.StatusBadRequest)
return
}
if val, ok := m["project"]; ok {
shared_project = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing query parameter: project to clone not specified"))
w.WriteHeader(http.StatusBadRequest)
return
}
if val, ok := m["destination"]; ok {
cloned_project = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing query parameter: new name of the cloned project not specified"))
w.WriteHeader(http.StatusBadRequest)
return
}
args := []string{"--json", "clone-share", sharer, shared_project, username, cloned_project}
logger.Info(fmt.Sprintf("cmd args %s", args))
cmd := exec.Command(cboxShareScript, args...)
jsonResponse, errBuf, err := executeCMD(cmd)
if err != nil {
logger.Error(fmt.Sprintf("Error calling cmd %s %s %s: '%s'", cmd.Path, cmd.Args, err, errBuf.String()))
cmderr := CmdError{Statuscode: http.StatusInternalServerError}
json.Unmarshal(jsonResponse.Bytes(), &cmderr)
// TODO: inject error string if applicable
w.WriteHeader(cmderr.Statuscode)
//return
}
w.Write(jsonResponse.Bytes())
})
}
func DeleteShare(logger *zap.Logger, cboxShareScript, allowFrom string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !CORSProcessOriginHeader(logger, w, r, allowFrom) {
return
}
v := context.Get(r, "username")
username, _ := v.(string)
logger.Info("loggedin user is " + username)
project := ""
m, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
logger.Error(fmt.Sprintf("URL query parsing error: %s '%s' ", err))
w.WriteHeader(http.StatusBadRequest)
return
}
if val, ok := m["project"]; ok {
project = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing query parameter: project not specified"))
w.WriteHeader(http.StatusBadRequest)
return
}
args := []string{"--json", "delete-share", username, project}
logger.Info(fmt.Sprintf("cmd args %s", args))
cmd := exec.Command(cboxShareScript, args...)
jsonResponse, errBuf, err := executeCMD(cmd)
if err != nil {
logger.Error(fmt.Sprintf("Error calling cmd %s %s %s: '%s'", cmd.Path, cmd.Args, err, errBuf.String()))
cmderr := CmdError{Statuscode: http.StatusInternalServerError}
json.Unmarshal(jsonResponse.Bytes(), &cmderr)
// TODO: inject error string if applicable
w.WriteHeader(cmderr.Statuscode)
//return
}
w.Write(jsonResponse.Bytes())
})
}
func UpdateShare(logger *zap.Logger, cboxShareScript, allowFrom string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !CORSProcessOriginHeader(logger, w, r, allowFrom) {
return
}
v := context.Get(r, "username")
username, _ := v.(string)
logger.Info("loggedin user is " + username)
project := ""
m, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
logger.Error(fmt.Sprintf("URL query parsing error: %s '%s' ", err))
w.WriteHeader(http.StatusBadRequest)
return
}
if val, ok := m["project"]; ok {
project = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing query parameter: project not specified"))
w.WriteHeader(http.StatusBadRequest)
return
}
args := []string{"--json", "update-share", username, project}
type Sharee struct {
Name string `json:"name"` // name of user or group
Entity string `json:"entity"` // "u" is user, "egroup" is group
}
type ShareRequest struct {
ShareWith []Sharee `json:"share_with"`
}
var share_request ShareRequest
if err = json.NewDecoder(r.Body).Decode(&share_request); err != nil {
logger.Error(fmt.Sprintf("Cannot unmarshal JSON request body"))
w.WriteHeader(http.StatusBadRequest)
return
}
// TODO: BadRequest if empty ShareWith array
if len(share_request.ShareWith) == 0 {
logger.Error(fmt.Sprintf("Empty request"))
w.WriteHeader(http.StatusBadRequest)
return
}
logger.Info(fmt.Sprintf("request %s", share_request))
for i := range share_request.ShareWith {
// FIXME: TODO: sanitize names
// FIXME: TODO: check for missing fields, e.g. empty name or empty entity
share := share_request.ShareWith[i]
args = append(args, share.Entity+":"+share.Name)
}
logger.Info(fmt.Sprintf("cmd args %s", args))
cmd := exec.Command(cboxShareScript, args...)
jsonResponse, errBuf, err := executeCMD(cmd)
if err != nil {
logger.Error(fmt.Sprintf("Error calling cmd %s %s %s: '%s'", cmd.Path, cmd.Args, err, errBuf.String()))
cmderr := CmdError{Statuscode: http.StatusInternalServerError}
json.Unmarshal(jsonResponse.Bytes(), &cmderr)
// TODO: inject error string if applicable
w.WriteHeader(cmderr.Statuscode)
//return
}
w.Write(jsonResponse.Bytes())
})
}
func Shared(logger *zap.Logger, cboxShareScript, allowFrom string, action string, requireProject bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !CORSProcessOriginHeader(logger, w, r, allowFrom) {
return
}
v := context.Get(r, "username")
username, _ := v.(string)
logger.Info("loggedin user is " + username)
project := ""
if requireProject {
m, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
logger.Error(fmt.Sprintf("URL query parsing error: %s '%s' ", err))
w.WriteHeader(http.StatusBadRequest)
return
}
if val, ok := m["project"]; ok {
project = val[0]
} else {
logger.Error(fmt.Sprintf("URL missing query parameter: project not specified "))
w.WriteHeader(http.StatusBadRequest)
return
}
}
type shareInfo struct {
User string `json:"user"`
Path string `json:"path"`
Size int `json:"size"`
Date int64 `json:"date"`
}
type response struct {
Shared []*shareInfo `json:"shared"`
}
args := []string{"--json", action}
if project != "" {
args = append(args, "--project", project)
}
args = append(args, username)
logger.Info(fmt.Sprintf("cmd args %s", args))
cmd := exec.Command(cboxShareScript, args...)
jsonResponse, errBuf, err := executeCMD(cmd)
if err != nil {
logger.Error(fmt.Sprintf("Error calling cmd %s %s %s: '%s' ", cmd.Path, cmd.Args, err, errBuf.String()))
cmderr := CmdError{Statuscode: http.StatusInternalServerError}
json.Unmarshal(jsonResponse.Bytes(), &cmderr)
// TODO: inject error string if applicable
w.WriteHeader(cmderr.Statuscode)
//return
}
w.Write(jsonResponse.Bytes())
})
}