forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmw_request_size_limit.go
89 lines (72 loc) · 2.54 KB
/
mw_request_size_limit.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
package gateway
import (
"errors"
"net/http"
"strconv"
"github.com/sirupsen/logrus"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/headers"
)
// TransformMiddleware is a middleware that will apply a template to a request body to transform it's contents ready for an upstream API
type RequestSizeLimitMiddleware struct {
BaseMiddleware
}
func (t *RequestSizeLimitMiddleware) Name() string {
return "RequestSizeLimitMiddleware"
}
func (t *RequestSizeLimitMiddleware) EnabledForSpec() bool {
for _, version := range t.Spec.VersionData.Versions {
if len(version.ExtendedPaths.SizeLimit) > 0 {
return true
}
}
return false
}
func (t *RequestSizeLimitMiddleware) checkRequestLimit(r *http.Request, sizeLimit int64) (error, int) {
statedCL := r.Header.Get(headers.ContentLength)
if statedCL == "" {
return errors.New("Content length is required for this request"), 411
}
size, err := strconv.ParseInt(statedCL, 0, 64)
if err != nil {
t.Logger().WithError(err).Error("String conversion for content length failed")
return errors.New("content length is not a valid Integer"), http.StatusBadRequest
}
if r.ContentLength > size {
size = r.ContentLength
}
// Check stated size
if size > sizeLimit {
t.Logger().WithFields(logrus.Fields{"size": size, "limit": sizeLimit}).Info("Attempted access with large request size, blocked.")
return errors.New("Request is too large"), http.StatusBadRequest
}
return nil, http.StatusOK
}
// RequestSizeLimit will check a request for maximum request size, this can be a global limit or a matched limit.
func (t *RequestSizeLimitMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
logger := t.Logger()
logger.Debug("Request size limiter active")
vInfo, versionPaths, _, _ := t.Spec.Version(r)
logger.Debug("Global limit is: ", vInfo.GlobalSizeLimit)
// Manage global headers first
if vInfo.GlobalSizeLimit > 0 {
logger.Debug("Checking global limit")
err, code := t.checkRequestLimit(r, vInfo.GlobalSizeLimit)
// If not OK, block
if code != http.StatusOK {
return err, code
}
}
// if there's no paths at all path check
if len(vInfo.ExtendedPaths.SizeLimit) == 0 {
return nil, http.StatusOK
}
// If there's a potential match, try to match
found, meta := t.Spec.CheckSpecMatchesStatus(r, versionPaths, RequestSizeLimit)
if found {
logger.Debug("Request size limit matched for this URL, checking...")
rmeta := meta.(*apidef.RequestSizeMeta)
return t.checkRequestLimit(r, rmeta.SizeLimit)
}
return nil, http.StatusOK
}