forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
577 lines (493 loc) · 16.9 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
/*
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 (
"net/http"
"path"
"regexp"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/coreos/go-oidc/jose"
"github.com/coreos/go-oidc/oauth2"
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
//
// The logic is broken into four handlers just to simplify the code
//
// a) entryPointHandler checks if the the uri requires authentication
// b) authenticationHandler verifies the access token
// c) admissionHandler verifies that the token is authorized to access to uri resource
// c) proxyHandler is responsible for handling the reverse proxy to the upstream endpoint
//
const (
// cxEnforce is the tag name for a request requiring
cxEnforce = "Enforcing"
)
//
// loggingHandler is a custom http logger
//
func (r *KeycloakProxy) loggingHandler() gin.HandlerFunc {
return func(cx *gin.Context) {
start := time.Now()
cx.Next()
latency := time.Now().Sub(start)
log.WithFields(log.Fields{
"client_ip": cx.ClientIP(),
"method": cx.Request.Method,
"status": cx.Writer.Status(),
"bytes": cx.Writer.Size(),
"path": cx.Request.URL.Path,
"latency": latency.String(),
}).Infof("[%d] |%s| |%10v| %-5s %s", cx.Writer.Status(), cx.ClientIP(), latency, cx.Request.Method, cx.Request.URL.Path)
}
}
//
// securityHandler performs numerous security checks on the request
//
func (r *KeycloakProxy) securityHandler() gin.HandlerFunc {
// step: create the security options
secure := secure.New(secure.Options{
AllowedHosts: r.config.Hostnames,
BrowserXssFilter: true,
ContentTypeNosniff: true,
FrameDeny: true,
STSIncludeSubdomains: true,
STSSeconds: 31536000,
})
return func(cx *gin.Context) {
// step: pass through the security middleware
if err := secure.Process(cx.Writer, cx.Request); err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed security middleware")
cx.Abort()
return
}
// step: permit the request to continue
cx.Next()
}
}
//
// entryPointHandler checks to see if the request requires authentication
//
func (r *KeycloakProxy) entryPointHandler() gin.HandlerFunc {
return func(cx *gin.Context) {
if strings.HasPrefix(cx.Request.URL.Path, oauthURL) {
cx.Next()
return
}
// step: check if authentication is required - gin doesn't support wildcard url, so we have have to use prefixes
for _, resource := range r.config.Resources {
if strings.HasPrefix(cx.Request.URL.Path, resource.URL) {
// step: has the resource been white listed?
if resource.WhiteListed {
break
}
// step: inject the resource into the context, saves us from doing this again
if containedIn(cx.Request.Method, resource.Methods) || containedIn("ANY", resource.Methods) {
cx.Set(cxEnforce, resource)
}
break
}
}
// step: pass into the authentication and admission handlers
cx.Next()
// step: add a custom headers to the request
for k, v := range r.config.Header {
cx.Request.Header.Set(k, v)
}
// step: check the request has not been aborted and if not, proxy request
if !cx.IsAborted() {
r.proxyHandler(cx)
}
}
}
//
// authenticationHandler is responsible for verifying the access token
//
// steps:
// - check if the request is protected and requires validation
// - retrieve the access token from the cookie or authorization header, if there isn't a token, check
// if there is a session state and use the refresh token to refresh access token
// - extract the user context from the access token, ensuring the minimum claims
// - validate the audience of the access token is directed to us
// - inject the user context into the request context for later layers
// - skip verification of the access token if enabled
// - else we validate the access token against the keypair via openid client
// - if everything is cool, move on, else thrown a redirect or forbidden
//
func (r *KeycloakProxy) authenticationHandler() gin.HandlerFunc {
return func(cx *gin.Context) {
var session jose.JWT
// step: is authentication required on this uri?
if _, found := cx.Get(cxEnforce); !found {
log.Debugf("skipping the authentication handler, resource not protected")
cx.Next()
return
}
// step: retrieve the access token from the request
session, isBearer, err := r.getSessionToken(cx)
if err != nil {
// step: there isn't a session cookie, do we have refresh session cookie?
if err == ErrSessionNotFound && r.config.RefreshSessions && !isBearer {
session, err = r.refreshUserSessionToken(cx)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed to refresh the access token")
r.redirectToAuthorization(cx)
return
}
} else {
log.Errorf("failed to get session redirecting for authorization, %s", err)
r.redirectToAuthorization(cx)
return
}
}
// step: retrieve the identity and inject in the context
userContext, err := r.getUserContext(session)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed to retrieve the identity from the token")
r.redirectToAuthorization(cx)
return
}
userContext.bearerToken = isBearer
log.Debugf("found user context: %s", userContext)
// step: check the audience for the token is us
if !userContext.isAudience(r.config.ClientID) {
log.WithFields(log.Fields{
"username": userContext.name,
"expired_on": userContext.expiresAt.String(),
"issued": userContext.audience,
"clientid": r.config.ClientID,
}).Warnf("the access token audience is not us, redirecting back for authentication")
r.redirectToAuthorization(cx)
return
}
cx.Set(userContextName, userContext)
// step: verify the access token
if r.config.SkipTokenVerification {
log.Warnf("token verification enabled, skipping verification process - FOR TESTING ONLY")
if userContext.isExpired() {
log.WithFields(log.Fields{
"username": userContext.name,
"expired_on": userContext.expiresAt.String(),
}).Errorf("the session has expired and verification switch off")
r.redirectToAuthorization(cx)
}
return
}
if err := r.verifyToken(userContext.token); err != nil {
fields := log.Fields{
"username": userContext.name,
"expired_on": userContext.expiresAt.String(),
"error": err.Error(),
}
// 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 {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("access token has expired")
r.accessForbidden(cx)
return
}
if isBearer {
log.WithFields(fields).Errorf("the session has expired and we are using bearer token")
r.redirectToAuthorization(cx)
return
}
// step: are we refreshing the access tokens?
if !r.config.RefreshSessions {
log.WithFields(fields).Errorf("the session has expired and token refreshing is disabled")
r.redirectToAuthorization(cx)
return
}
// step: attempt to refresh the access token
if _, err := r.refreshUserSessionToken(cx); err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed to refresh the access token")
r.redirectToAuthorization(cx)
return
}
}
cx.Next()
}
}
//
// admissionHandler is responsible checking the access token against the protected resource
//
// steps:
// - check if authentication and validation is required
// - if so, retrieve the resource and user from the request context
// - if we have any roles requirements validate the roles exists in the access token
// - if er have any claim requirements validate the claims are the same
// - if everything is ok, we permit the request to pass through
//
func (r *KeycloakProxy) admissionHandler() gin.HandlerFunc {
// step: compile the regex's for the claims
claimMatches := make(map[string]*regexp.Regexp, 0)
for k, v := range r.config.ClaimsMatch {
claimMatches[k] = regexp.MustCompile(v)
}
return func(cx *gin.Context) {
// step: if authentication is required on this, grab the resource spec
ur, found := cx.Get(cxEnforce)
if !found {
return
}
// step: grab the identity from the context
uc, found := cx.Get(userContextName)
if !found {
panic("there is no identity in the request context")
}
resource := ur.(*Resource)
identity := uc.(*userContext)
// step: we need to check the roles
if roles := len(resource.Roles); roles > 0 {
if !hasRoles(resource.Roles, identity.roles) {
log.WithFields(log.Fields{
"access": "denied",
"username": identity.name,
"resource": resource.URL,
"required": resource.getRoles(),
}).Warnf("access denied, invalid roles")
r.accessForbidden(cx)
return
}
}
// step: if we have any claim matching, validate the tokens has the claims
// @TODO we should probably convert the claim checks to regexs
for claimName, match := range claimMatches {
// step: if the claim is NOT in the token, we access deny
value, found, err := identity.claims.StringClaim(claimName)
if err != nil {
log.WithFields(log.Fields{
"access": "denied",
"username": identity.name,
"resource": resource.URL,
"error": err.Error(),
}).Errorf("unable to extract the claim from token")
r.accessForbidden(cx)
return
}
if !found {
log.WithFields(log.Fields{
"access": "denied",
"username": identity.name,
"resource": resource.URL,
"claim": claimName,
}).Warnf("the token does not have the claim")
r.accessForbidden(cx)
return
}
// step: check the claim is the same
if !match.MatchString(value) {
log.WithFields(log.Fields{
"access": "denied",
"username": identity.name,
"resource": resource.URL,
"claim": claimName,
"issued": value,
"required": match,
}).Warnf("the token claims does not match claim requirement")
r.accessForbidden(cx)
return
}
}
log.WithFields(log.Fields{
"access": "permitted",
"username": identity.name,
"resource": resource.URL,
"expires": identity.expiresAt.Sub(time.Now()).String(),
"bearer": identity.bearerToken,
}).Debugf("resource access permitted: %s", cx.Request.RequestURI)
}
}
//
// proxyHandler is responsible to proxy the requests on to the upstream endpoint
//
func (r *KeycloakProxy) proxyHandler(cx *gin.Context) {
// step: double check, if enforce is true and no user context it's a internal error
if _, found := cx.Get(cxEnforce); found {
if _, found := cx.Get(userContextName); !found {
log.Errorf("no user context found for a secure request")
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
}
// step: retrieve the user context if any
if identity, found := cx.Get(userContextName); found {
id := identity.(*userContext)
cx.Request.Header.Add("X-Auth-UserId", id.id)
cx.Request.Header.Add("X-Auth-Subject", id.preferredName)
cx.Request.Header.Add("X-Auth-Username", id.name)
cx.Request.Header.Add("X-Auth-Email", id.email)
cx.Request.Header.Add("X-Auth-ExpiresIn", id.expiresAt.String())
cx.Request.Header.Add("X-Auth-Token", id.token.Encode())
cx.Request.Header.Add("X-Auth-Roles", strings.Join(id.roles, ","))
}
// step: add the default headers
cx.Request.Header.Add("X-Forwarded-For", cx.Request.RemoteAddr)
cx.Request.Header.Set("X-Forwarded-Agent", prog)
cx.Request.Header.Set("X-Forwarded-Agent-Version", version)
// step: is this connection upgrading?
if isUpgradedConnection(cx.Request) {
log.Debugf("upgrading the connnection to %s", cx.Request.Header.Get(headerUpgrade))
if err := r.tryUpdateConnection(cx); err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed to upgrade the connection")
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
cx.Abort()
return
}
r.proxy.ServeHTTP(cx.Writer, cx.Request)
}
// ---
// The handlers for managing the OAuth authentication flow
// ---
//
// oauthAuthorizationHandler is responsible for performing the redirection to keycloak service
//
func (r *KeycloakProxy) oauthAuthorizationHandler(cx *gin.Context) {
// step: is token verification switched on?
if r.config.SkipTokenVerification {
r.accessForbidden(cx)
return
}
log.WithFields(log.Fields{
"client_ip": cx.ClientIP(),
}).Infof("incoming authorization request")
// step: grab the oauth client
oac, err := r.openIDClient.OAuthClient()
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
}).Errorf("failed to retrieve the oauth client")
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
// step: get the access type required
accessType := ""
if r.config.RefreshSessions {
accessType = "offline"
}
// step: build the redirection url to the authentication server
redirectionURL := oac.AuthCodeURL(cx.Query("state"), accessType, "")
// step: if we have a custom sign in page, lets display that
if r.config.hasSignInPage() {
// add the redirection url
model := make(map[string]string, 0)
for k, v := range r.config.TagData {
model[k] = v
}
model["redirect"] = redirectionURL
cx.HTML(http.StatusOK, path.Base(r.config.SignInPage), model)
return
}
// step: get the redirection url
r.redirectToURL(redirectionURL, cx)
}
//
// oauthCallbackHandler is responsible for handling the response from keycloak
//
// @@TODO need to clean up this method somewhat
func (r *KeycloakProxy) oauthCallbackHandler(cx *gin.Context) {
// step: is token verification switched on?
if r.config.SkipTokenVerification {
r.accessForbidden(cx)
return
}
// step: ensure we have a authorization code to exchange
code := cx.Request.URL.Query().Get("code")
if code == "" {
log.WithFields(log.Fields{"client_ip": cx.ClientIP()}).Error("code parameter not found in callback request")
r.accessForbidden(cx)
return
}
// step: grab the state from request, otherwise default to root url
state := cx.Request.URL.Query().Get("state")
if state == "" {
state = "/"
}
// step: exchange the authorization for a access token
response, err := r.getToken(oauth2.GrantTypeAuthCode, code)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("unable to exchange code for access token")
r.accessForbidden(cx)
return
}
// step: decode and verify the id token
token, identity, err := r.parseToken(response.IDToken)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("unable to parse id token for identity")
r.accessForbidden(cx)
return
}
if err := r.verifyToken(token); err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("unable to verify the id token")
r.accessForbidden(cx)
return
}
// step: attempt to decode the access token?
ac, id, err := r.parseToken(response.AccessToken)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("unable to parse the access token, using id token only")
} else {
token = ac
identity = id
}
log.WithFields(log.Fields{
"email": identity.Email,
"expires": identity.ExpiresAt,
}).Infof("issuing a user session")
// step: create a session from the access token
if err := r.createSession(token, identity.ExpiresAt, cx); err != nil {
log.Errorf("failed to inject the session token, error: %s", err)
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
// step: do we have session data to persist?
if r.config.RefreshSessions {
// step: parse the token
_, ident, err := r.parseToken(response.RefreshToken)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed to parse the refresh token")
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
log.WithFields(log.Fields{
"email": identity.Email,
"expires": identity.ExpiresAt,
}).Infof("retrieved the refresh token for user")
// step: create the state session
state := &sessionState{
refreshToken: response.RefreshToken,
}
maxSession := time.Now().Add(r.config.MaxSession)
switch maxSession.After(ident.ExpiresAt) {
case true:
state.expireOn = ident.ExpiresAt
default:
state.expireOn = maxSession
}
if err := r.createSessionState(state, cx); err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Errorf("failed to inject the session state into request")
cx.AbortWithStatus(http.StatusInternalServerError)
return
}
}
r.redirectToURL(state, cx)
}
//
// healthHandler is a health check handler for the service
//
func (r *KeycloakProxy) healthHandler(cx *gin.Context) {
cx.String(http.StatusOK, "OK")
}