This repository has been archived by the owner on Nov 2, 2023. It is now read-only.
/
echo.go
270 lines (233 loc) · 6.85 KB
/
echo.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
// Copyright (c) 2016 - 2019 Sqreen. All Rights Reserved.
// Please refer to our terms for more information:
// https://www.sqreen.io/terms.html
package sqecho
import (
"bytes"
"net"
"net/http"
"net/textproto"
"net/url"
"strconv"
"github.com/labstack/echo"
"github.com/sqreen/go-agent/internal"
protectioncontext "github.com/sqreen/go-agent/internal/protection/context"
http_protection "github.com/sqreen/go-agent/internal/protection/http"
"github.com/sqreen/go-agent/internal/protection/http/types"
"github.com/sqreen/go-agent/sdk"
)
// FromContext allows to access the HTTPRequestRecord from Echo request handlers
// if present, and nil otherwise. The value is stored in handler contexts by the
// middleware function, and is of type *HTTPRequestRecord.
//
// Note that Echo's context does not implement the `context.Context` interface,
// so `sdk.FromContext()` cannot be used with it, hence another `FromContext()`
// in this package to access the SDK context value from Echo's context.
// `sdk.FromContext()` can still be used on the request context.
func FromContext(c echo.Context) sdk.Context {
return sdk.FromContext(c.Request().Context())
}
// Middleware is Sqreen's middleware function for echo to monitor and protect the
// requests echo receives.
//
// SDK methods can be called from request handlers by using the request context.
// It can be retrieved from the request context using `sdk.FromContext()` or
// on a echo's context.
//
// Usage example:
//
// e := echo.New()
// e.Use(sqecho.Middleware())
//
// e.GET("/", func(c echo.Context) error {
// // Accessing the SDK through Echo's context
// sqecho.FromContext(c).TrackEvent("my.event.one")
// foo(c.Request())
// return nil
// }
//
// func foo(req *http.Request) {
// // Accessing the SDK through the request context
// sdk.FromContext(req.Context()).TrackEvent("my.event.two")
// }
//
// e.GET("/", func(c echo.Context) {
// // Globally identifying a user and checking if the request should be
// // aborted.
// uid := sdk.EventUserIdentifiersMap{"uid": "my-uid"}
// sqUser := sqecho.FromContext(c).ForUser(uid)
// // Globally associate this user to the current request and check if it got
// // blocked.
// if err := sqUser.Identify(); err != nil {
// // Return to stop further handling the request
// return err
// }
// // ... not blocked ...
// return nil
// }
//
func Middleware() echo.MiddlewareFunc {
internal.Start()
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ctx, cancel := internal.NewRootHTTPProtectionContext(c.Request().Context())
if ctx == nil {
return next(c)
}
defer cancel()
return middlewareHandlerFromRootProtectionContext(ctx, next, c)
}
}
}
func middlewareHandlerFromRootProtectionContext(ctx types.RootProtectionContext, next echo.HandlerFunc, c echo.Context) (err error) {
r := &requestReaderImpl{c: c}
p := http_protection.NewProtectionContext(ctx, c.Response(), r)
if p == nil {
return next(c)
}
defer func() {
p.Close(newObservedResponse(c.Response(), err))
}()
return middlewareHandlerFromProtectionContext(p, next, c)
}
type protectionContext interface {
WrapRequest(*http.Request) *http.Request
Before() error
After() error
}
func middlewareHandlerFromProtectionContext(p protectionContext, next echo.HandlerFunc, c echo.Context) error {
c.SetRequest(p.WrapRequest(c.Request()))
c.Set(protectioncontext.ContextKey.String, p)
if err := p.Before(); err != nil {
return err
}
if err := next(c); err != nil {
// Handler-based protection such as user security responses or RASP
// protection may lead to aborted requests bubbling up the error that
// was returned.
return err
}
return p.After()
}
type requestReaderImpl struct {
c echo.Context
bodyReadBuffer bytes.Buffer
queryForm url.Values
}
func (r *requestReaderImpl) Body() []byte {
return nil
}
func (r *requestReaderImpl) UserAgent() string {
return r.c.Request().UserAgent()
}
func (r *requestReaderImpl) Referer() string {
return r.c.Request().Referer()
}
func (r *requestReaderImpl) ClientIP() net.IP {
return nil // Delegated to the middleware according the agent configuration
}
func (r *requestReaderImpl) Method() string {
return r.c.Request().Method
}
func (r *requestReaderImpl) URL() *url.URL {
return r.c.Request().URL
}
func (r *requestReaderImpl) RequestURI() string {
return r.c.Request().RequestURI
}
func (r *requestReaderImpl) Host() string {
return r.c.Request().Host
}
func (r *requestReaderImpl) IsTLS() bool {
return r.c.IsTLS()
}
func (r *requestReaderImpl) Params() types.RequestParamMap {
params := r.c.ParamNames()
l := len(params)
if l == 0 {
return nil
}
m := make(types.RequestParamMap, l)
for _, key := range params {
m.Add(key, r.c.Param(key))
}
return m
}
func (r *requestReaderImpl) QueryForm() url.Values {
if r.queryForm == nil {
r.queryForm = r.c.Request().URL.Query()
}
return r.queryForm
}
func (r *requestReaderImpl) PostForm() url.Values {
return r.c.Request().PostForm
}
func (r *requestReaderImpl) Headers() http.Header {
return r.c.Request().Header
}
func (r *requestReaderImpl) Header(h string) *string {
headers := r.c.Request().Header
if headers == nil {
return nil
}
v := headers[textproto.CanonicalMIMEHeaderKey(h)]
if len(v) == 0 {
return nil
}
return &v[0]
}
func (r *requestReaderImpl) RemoteAddr() string {
return r.c.Request().RemoteAddr
}
// response observed by the response writer
type observedResponse struct {
contentType string
contentLength int64
status int
}
func newObservedResponse(response *echo.Response, err error) *observedResponse {
headers := response.Header()
// Content-Type will be not empty only when explicitly set.
// It could be guessed as net/http does. Not implemented for now.
ct := headers.Get("Content-Type")
// Content-Length is either explicitly set or the amount of written data. It's
// 0 by default with Echo.
cl := response.Size
if cl == 0 {
if contentLength := headers.Get("Content-Length"); contentLength != "" {
if l, err := strconv.ParseInt(contentLength, 10, 0); err == nil {
cl = l
}
}
}
// Echo's status code is not necessarily in the response's Status field.
// For example, it can be based on the handler's returned error.
// Echo's status code field is 200 by default...
var status int
switch actual := err.(type) {
case *echo.HTTPError:
// Take the returned error status code
status = actual.Code
default:
// Take the response status code
status = response.Status
}
return &observedResponse{
contentType: ct,
contentLength: cl,
status: status,
}
}
func (r *observedResponse) Status() int {
if status := r.status; status != 0 {
return status
}
// Default net/http status is 200
return http.StatusOK
}
func (r *observedResponse) ContentType() string {
return r.contentType
}
func (r *observedResponse) ContentLength() int64 {
return r.contentLength
}