-
Notifications
You must be signed in to change notification settings - Fork 19
/
middleware.go
346 lines (259 loc) · 7.99 KB
/
middleware.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
package main
import (
"net/http"
"strings"
"time"
"github.com/dchest/uniuri"
"github.com/raggaer/castro/app/models"
"github.com/raggaer/castro/app/util"
"github.com/ulule/limiter"
"golang.org/x/net/context"
)
// microtimeHandler used to record all requests time spent
type microtimeHandler struct{}
// csrfHandler used to add a token to all requests
type csrfHandler struct{}
// sessionHandler used for application session
type sessionHandler struct{}
// securityHandler used to set some headers
type securityHandler struct{}
// rateLimitHandler used for rate-limiting
type rateLimitHandler struct {
Limiter *limiter.Limiter
}
// i18nHandler used to detect user language
type i18nHandler struct{}
// newI18nHandler creates and returns a new i18nHandler instance
func newI18nHandler() *i18nHandler {
return &i18nHandler{}
}
func (i *i18nHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Retrieve request language header
accept := strings.Split(req.Header.Get("Accept-Language"), ",")
// Create new context with language value
ctx := context.WithValue(req.Context(), "language", accept)
next(w, req.WithContext(ctx))
}
// newRateLimitHandler creates and returns a new rateLimitHandler instance
func newRateLimitHandler(limiter *limiter.Limiter) *rateLimitHandler {
return &rateLimitHandler{limiter}
}
func (r *rateLimitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Check if rate-limit is not enabled
if !util.Config.Configuration.RateLimit.Enabled {
next(w, req)
return
}
// IP data holder
ip := ""
// Check if behind proxy
if util.Config.Configuration.SSL.Proxy {
// Get address from X-Forwarded-For
ip = req.Header.Get("X-Forwarded-For")
} else {
// Get address from RemoteAddress
ip = req.RemoteAddr
}
// Get rate-limit context
ctx, err := r.Limiter.Get(req.Context(), ip)
if err != nil {
http.Error(w, "Cannot get rate-limit instance", 500)
return
}
// Check for limit
if ctx.Reached {
http.Error(w, "Rate-limit reached", 500)
return
}
// Execute next handler
next(w, req)
}
// newSecurityHandler creates and returns a new securityHandler instance
func newSecurityHandler() *securityHandler {
return &securityHandler{}
}
func (s *securityHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Retrieve nonce value from cache
nonce, ok := util.Cache.Get("nonce")
if !ok {
// Create new nonce value
nonce = uniuri.NewLen(3)
// Save new nonce to cache
util.Cache.Set("nonce", nonce, time.Minute*20)
}
// Create new context with cookie value
ctx := context.WithValue(req.Context(), "nonce", nonce)
// Set Strict-Transport-Security header if SSL
if util.Config.Configuration.IsSSL() {
// Set header
w.Header().Set("Strict-Transport-Security", util.Config.Configuration.Security.STS)
}
// Set Engine header
w.Header().Set("Engine", "Castro")
// Set X-XSS-Protection header
w.Header().Set("X-XSS-Protection", util.Config.Configuration.Security.XSS)
// Set X-Frame-Options header
w.Header().Set("X-Frame-Options", util.Config.Configuration.Security.Frame)
// Set X-Content-Type-Options header
w.Header().Set("X-Content-Type-Options", util.Config.Configuration.Security.ContentType)
// Set Referrer-Policy header
w.Header().Set("Referrer-Policy", util.Config.Configuration.Security.ReferrerPolicy)
// Set X-Permitted-Cross-Domain-Policies header
w.Header().Set("X-Permitted-Cross-Domain-Policies", util.Config.Configuration.Security.CrossDomainPolicy)
if util.Config.Configuration.Security.CSP.Enabled {
// Set Content-Security-Policy header
w.Header().Set(
"Content-Security-Policy",
util.Config.Configuration.CSP(nonce.(string)),
)
}
// Run next handler
next(w, req.WithContext(ctx))
}
// newSessionHandler creates and returns a new sessionHandler instance
func newSessionHandler() *sessionHandler {
return &sessionHandler{}
}
func (s *sessionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Get application cookie
cookie, err := req.Cookie(util.Config.Configuration.Cookies.Name)
if err != nil {
// Cookie data
v := make(map[string]interface{})
// Set issuer field
v["issuer"] = "Castro"
// Encode cookie value
encoded, err := util.SessionStore.Encode(util.Config.Configuration.Cookies.Name, v)
if err != nil {
util.Logger.Logger.Errorf("Cannot encode cookie value: %v", err)
return
}
// Create cookie
c := &http.Cookie{
Name: util.Config.Configuration.Cookies.Name,
Value: encoded,
Path: "/",
MaxAge: util.Config.Configuration.Cookies.MaxAge,
Secure: util.Config.Configuration.IsSSL(),
HttpOnly: true,
}
// Set cookie
http.SetCookie(w, c)
// Create new context with cookie value
ctx := context.WithValue(req.Context(), "session", v)
// Run next handler
next(w, req.WithContext(ctx))
return
}
// Cookie data holder
v := make(map[string]interface{})
// Decode cookie
if err := util.SessionStore.Decode(
util.Config.Configuration.Cookies.Name,
cookie.Value,
&v,
); err != nil {
util.Logger.Logger.Errorf("Cannot decode cookie value: %v", err)
return
}
// Get issuer
issuer, ok := v["issuer"].(string)
if !ok {
return
}
// Check issuer
if issuer != "Castro" {
return
}
// Create new context with cookie value
ctx := context.WithValue(req.Context(), "session", v)
// Run next handler
next(w, req.WithContext(ctx))
}
// newCsrfHandler creates and returns a new csrfHandler instance
func newCsrfHandler() *csrfHandler {
return &csrfHandler{}
}
func (c *csrfHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Skip nocsrf routes
if strings.HasPrefix(req.URL.Path, "/nocsrf") {
// Run next handler
next(w, req)
return
}
// Get session
session, ok := req.Context().Value("session").(map[string]interface{})
if !ok {
return
}
// Get token
token, ok := session["csrf-token"].(*models.CsrfToken)
if !ok {
// Check if request is valid
if req.Method == http.MethodPost {
return
}
// Create token
tkn := models.CsrfToken{
Token: uniuri.New(),
At: time.Now(),
}
// Set session value
session["csrf-token"] = &tkn
// Encode session
encoded, err := util.SessionStore.Encode(util.Config.Configuration.Cookies.Name, session)
if err != nil {
util.Logger.Logger.Errorf("Cannot encode session: %v", err)
}
// Create cookie
c := &http.Cookie{
Name: util.Config.Configuration.Cookies.Name,
Value: encoded,
Path: "/",
MaxAge: util.Config.Configuration.Cookies.MaxAge,
Secure: util.Config.Configuration.IsSSL(),
HttpOnly: true,
}
// Set cookie
http.SetCookie(w, c)
// Create context
ctx := context.WithValue(req.Context(), "csrf-token", &tkn)
// Run next handler
next(w, req.WithContext(ctx))
return
}
// Check if valid token
if req.Method == http.MethodPost && (req.FormValue("_csrf") != token.Token && req.URL.Query().Get("_csrf") != token.Token) {
return
}
// Check if token is old
if time.Now().Before(token.At) {
// Create new token
token.Token = uniuri.New()
token.At = time.Now()
// Encode session
encoded, err := util.SessionStore.Encode(util.Config.Configuration.Cookies.Name, session)
if err != nil {
util.Logger.Logger.Errorf("Cannot encode session: %v", err)
}
// Create cookie
c := util.SessionCookie(encoded)
// Set cookie
http.SetCookie(w, c)
}
// Create context
ctx := context.WithValue(req.Context(), "csrf-token", token)
// Run next handler
next(w, req.WithContext(ctx))
}
// newMicrotimeHandler creates and returns a new microtimeHandler instance
func newMicrotimeHandler() *microtimeHandler {
return µtimeHandler{}
}
// ServeHTTP makes microtimeHandler compatible with negroni
func (m *microtimeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Set timestamp on the request context
ctx := context.WithValue(req.Context(), "microtime", time.Now())
// Execute next handler
next(w, req.WithContext(ctx))
}