forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
398 lines (345 loc) · 13.4 KB
/
middleware.go
File metadata and controls
398 lines (345 loc) · 13.4 KB
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
/*
Copyright 2015 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"github.com/PuerkitoBio/purell"
"github.com/gambol99/go-oidc/jose"
"github.com/go-chi/chi/middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/unrolled/secure"
"go.uber.org/zap"
)
const (
// normalizeFlags is the options to purell
normalizeFlags purell.NormalizationFlags = purell.FlagRemoveDotSegments | purell.FlagRemoveDuplicateSlashes
)
// entrypointMiddleware is custom filtering for incoming requests
func entrypointMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
keep := req.URL.Path
purell.NormalizeURL(req.URL, normalizeFlags)
// ensure we have a slash in the url
if !strings.HasPrefix(req.URL.Path, "/") {
req.URL.Path = "/" + req.URL.Path
}
req.RequestURI = req.URL.RawPath
req.URL.RawPath = req.URL.Path
// continue the flow
scope := &RequestScope{}
resp := middleware.NewWrapResponseWriter(w, 2)
next.ServeHTTP(resp, req.WithContext(context.WithValue(req.Context(), contextScopeName, scope)))
// place back the original uri for proxying request
req.URL.Path = keep
req.URL.RawPath = keep
req.RequestURI = keep
})
}
// loggingMiddleware is a custom http logger
func (r *oauthProxy) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
resp := w.(middleware.WrapResponseWriter)
next.ServeHTTP(resp, req)
addr := req.RemoteAddr
r.log.Info("client request",
zap.Duration("latency", time.Since(start)),
zap.Int("status", resp.Status()),
zap.Int("bytes", resp.BytesWritten()),
zap.String("client_ip", addr),
zap.String("method", req.Method),
zap.String("path", req.URL.Path))
})
}
// metricsMiddleware is responsible for collecting metrics
func (r *oauthProxy) metricsMiddleware(next http.Handler) http.Handler {
r.log.Info("enabled the service metrics middleware, available on", zap.String("path", fmt.Sprintf("%s%s", oauthURL, metricsURL)))
statusMetrics := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_request_total",
Help: "The HTTP requests partitioned by status code",
},
[]string{"code", "method"},
)
prometheus.MustRegister(statusMetrics)
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
resp := w.(middleware.WrapResponseWriter)
statusMetrics.WithLabelValues(fmt.Sprintf("%d", resp.Status()), req.Method).Inc()
next.ServeHTTP(w, req)
})
}
// authenticationMiddleware is responsible for verifying the access token
func (r *oauthProxy) authenticationMiddleware(resource *Resource) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
clientIP := req.RemoteAddr
// grab the user identity from the request
user, err := r.getIdentity(req)
if err != nil {
r.log.Error("no session found in request, redirecting for authorization", zap.Error(err))
next.ServeHTTP(w, req.WithContext(r.redirectToAuthorization(w, req)))
return
}
// create the request scope
scope := req.Context().Value(contextScopeName).(*RequestScope)
scope.Identity = user
ctx := context.WithValue(req.Context(), contextScopeName, scope)
// step: skip if we are running skip-token-verification
if r.config.SkipTokenVerification {
r.log.Warn("skip token verification enabled, skipping verification - TESTING ONLY")
if user.isExpired() {
r.log.Error("the session has expired and verification switch off",
zap.String("client_ip", clientIP),
zap.String("username", user.name),
zap.String("expired_on", user.expiresAt.String()))
next.ServeHTTP(w, req.WithContext(r.redirectToAuthorization(w, req)))
return
}
} else {
if err := verifyToken(r.client, user.token); err != nil {
// step: if the error post verification is anything other than a token
// expired error we immediately throw an access forbidden - as there is
// something messed up in the token
if err != ErrAccessTokenExpired {
r.log.Error("access token failed verification",
zap.String("client_ip", clientIP),
zap.Error(err))
next.ServeHTTP(w, req.WithContext(r.accessForbidden(w, req)))
return
}
// step: check if we are refreshing the access tokens and if not re-auth
if !r.config.EnableRefreshTokens {
r.log.Error("session expired and access token refreshing is disabled",
zap.String("client_ip", clientIP),
zap.String("email", user.name),
zap.String("expired_on", user.expiresAt.String()))
next.ServeHTTP(w, req.WithContext(r.redirectToAuthorization(w, req)))
return
}
r.log.Info("accces token for user has expired, attemping to refresh the token",
zap.String("client_ip", clientIP),
zap.String("email", user.email))
// step: check if the user has refresh token
refresh, encrypted, err := r.retrieveRefreshToken(req.WithContext(ctx), user)
if err != nil {
r.log.Error("unable to find a refresh token for user",
zap.String("client_ip", clientIP),
zap.String("email", user.email),
zap.Error(err))
next.ServeHTTP(w, req.WithContext(r.redirectToAuthorization(w, req)))
return
}
// attempt to refresh the access token
token, exp, err := getRefreshedToken(r.client, refresh)
if err != nil {
switch err {
case ErrRefreshTokenExpired:
r.log.Warn("refresh token has expired, cannot retrieve access token",
zap.String("client_ip", clientIP),
zap.String("email", user.email))
r.clearAllCookies(req.WithContext(ctx), w)
default:
r.log.Error("failed to refresh the access token", zap.Error(err))
}
next.ServeHTTP(w, req.WithContext(r.redirectToAuthorization(w, req)))
return
}
// get the expiration of the new access token
expiresIn := r.getAccessCookieExpiration(token, refresh)
r.log.Info("injecting the refreshed access token cookie",
zap.String("client_ip", clientIP),
zap.String("cookie_name", r.config.CookieAccessName),
zap.String("email", user.email),
zap.Duration("expires_in", time.Until(exp)))
accessToken := token.Encode()
if r.config.EnableEncryptedToken {
if accessToken, err = encodeText(accessToken, r.config.EncryptionKey); err != nil {
r.log.Error("unable to encode the access token", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
}
// step: inject the refreshed access token
r.dropAccessTokenCookie(req.WithContext(ctx), w, accessToken, expiresIn)
if r.useStore() {
go func(old, new jose.JWT, encrypted string) {
if err := r.DeleteRefreshToken(old); err != nil {
r.log.Error("failed to remove old token", zap.Error(err))
}
if err := r.StoreRefreshToken(new, encrypted); err != nil {
r.log.Error("failed to store refresh token", zap.Error(err))
return
}
}(user.token, token, encrypted)
}
// update the with the new access token and inject into the context
user.token = token
ctx = context.WithValue(req.Context(), contextScopeName, scope)
}
}
next.ServeHTTP(w, req.WithContext(ctx))
})
}
}
// admissionMiddleware is responsible checking the access token against the protected resource
func (r *oauthProxy) admissionMiddleware(resource *Resource) func(http.Handler) http.Handler {
claimMatches := make(map[string]*regexp.Regexp)
for k, v := range r.config.MatchClaims {
claimMatches[k] = regexp.MustCompile(v)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// we don't need to continue is a decision has been made
scope := req.Context().Value(contextScopeName).(*RequestScope)
if scope.AccessDenied {
next.ServeHTTP(w, req)
return
}
user := scope.Identity
// step: we need to check the roles
if roles := len(resource.Roles); roles > 0 {
if !hasRoles(resource.Roles, user.roles) {
r.log.Warn("access denied, invalid roles",
zap.String("access", "denied"),
zap.String("email", user.email),
zap.String("resource", resource.URL),
zap.String("required", resource.getRoles()))
next.ServeHTTP(w, req.WithContext(r.accessForbidden(w, req)))
return
}
}
// step: if we have any claim matching, lets validate the tokens has the claims
for claimName, match := range claimMatches {
value, found, err := user.claims.StringClaim(claimName)
if err != nil {
r.log.Error("unable to extract the claim from token",
zap.String("access", "denied"),
zap.String("email", user.email),
zap.String("resource", resource.URL),
zap.Error(err))
next.ServeHTTP(w, req.WithContext(r.accessForbidden(w, req)))
return
}
if !found {
r.log.Warn("the token does not have the claim",
zap.String("access", "denied"),
zap.String("claim", claimName),
zap.String("email", user.email),
zap.String("resource", resource.URL))
next.ServeHTTP(w, req.WithContext(r.accessForbidden(w, req)))
return
}
// step: check the claim is the same
if !match.MatchString(value) {
r.log.Warn("the token claims does not match claim requirement",
zap.String("access", "denied"),
zap.String("claim", claimName),
zap.String("email", user.email),
zap.String("issued", value),
zap.String("required", match.String()),
zap.String("resource", resource.URL))
next.ServeHTTP(w, req.WithContext(r.accessForbidden(w, req)))
return
}
}
r.log.Debug("access permitted to resource",
zap.String("access", "permitted"),
zap.String("email", user.email),
zap.Duration("expires", time.Until(user.expiresAt)),
zap.String("resource", resource.URL))
next.ServeHTTP(w, req)
})
}
}
// headersMiddleware is responsible for add the authentication headers for the upstream
func (r *oauthProxy) headersMiddleware(custom []string) func(http.Handler) http.Handler {
customClaims := make(map[string]string)
for _, x := range custom {
customClaims[x] = fmt.Sprintf("X-Auth-%s", toHeader(x))
}
cookieFilter := []string{r.config.CookieAccessName, r.config.CookieRefreshName}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
scope := req.Context().Value(contextScopeName).(*RequestScope)
if scope.Identity != nil {
user := scope.Identity
req.Header.Set("X-Auth-Email", user.email)
req.Header.Set("X-Auth-ExpiresIn", user.expiresAt.String())
req.Header.Set("X-Auth-Roles", strings.Join(user.roles, ","))
req.Header.Set("X-Auth-Subject", user.id)
req.Header.Set("X-Auth-Userid", user.name)
req.Header.Set("X-Auth-Username", user.name)
// should we add the token header?
if r.config.EnableTokenHeader {
req.Header.Set("X-Auth-Token", user.token.Encode())
}
// add the authorization header if requested
if r.config.EnableAuthorizationHeader {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", user.token.Encode()))
}
// are we filtering out the cookies
if !r.config.EnableAuthorizationCookies {
filterCookies(req, cookieFilter)
}
// inject any custom claims
for claim, header := range customClaims {
if claim, found := user.claims[claim]; found {
req.Header.Set(header, fmt.Sprintf("%v", claim))
}
}
}
next.ServeHTTP(w, req)
})
}
}
// securityMiddleware performs numerous security checks on the request
func (r *oauthProxy) securityMiddleware(next http.Handler) http.Handler {
r.log.Info("enabling the security filter middleware")
secure := secure.New(secure.Options{
AllowedHosts: r.config.Hostnames,
BrowserXssFilter: r.config.EnableBrowserXSSFilter,
ContentSecurityPolicy: r.config.ContentSecurityPolicy,
ContentTypeNosniff: r.config.EnableContentNoSniff,
FrameDeny: r.config.EnableFrameDeny,
SSLRedirect: r.config.EnableHTTPSRedirect,
})
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if err := secure.Process(w, req); err != nil {
r.log.Warn("failed security middleware", zap.Error(err))
next.ServeHTTP(w, req.WithContext(r.accessForbidden(w, req)))
return
}
next.ServeHTTP(w, req)
})
}
// proxyDenyMiddleware just block everything
func proxyDenyMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
sc := req.Context().Value(contextScopeName)
var scope *RequestScope
if sc == nil {
scope = &RequestScope{}
} else {
scope = sc.(*RequestScope)
}
scope.AccessDenied = true
// update the request context
ctx := context.WithValue(req.Context(), contextScopeName, scope)
next.ServeHTTP(w, req.WithContext(ctx))
})
}