forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
222 lines (185 loc) · 5.94 KB
/
server.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
/*
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 (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sync"
log "github.com/Sirupsen/logrus"
"github.com/gambol99/go-oidc/oidc"
"github.com/gin-gonic/gin"
)
// KeycloakProxy is the server component
type KeycloakProxy struct {
config *Config
// the gin service
router *gin.Engine
// the oidc provider config
openIDConfig oidc.ClientConfig
// the oidc client
openIDClient *oidc.Client
// the proxy client
proxy *httputil.ReverseProxy
// the upstream endpoint
upstreamURL *url.URL
}
// newKeycloakProxy create's a new keycloak proxy from configuration
func newKeycloakProxy(cfg *Config) (*KeycloakProxy, error) {
// step: set the logging level
if cfg.LogJSONFormat {
log.SetFormatter(&log.JSONFormatter{})
}
if cfg.Verbose {
log.SetLevel(log.DebugLevel)
}
log.Infof("starting %s, version: %s, author: %s", prog, version, author)
// step: parse the upstream endpoint
upstreamURL, err := url.Parse(cfg.Upstream)
if err != nil {
return nil, err
}
// step: initialize the reverse http proxy
reverse, err := initializeReverseProxy(upstreamURL)
if err != nil {
return nil, err
}
// step: create a proxy service
service := &KeycloakProxy{
config: cfg,
proxy: reverse,
upstreamURL: upstreamURL,
}
// step: initialize the openid client
if cfg.SkipTokenVerification {
log.Infof("TESTING ONLY CONFIG - the verification of the token have been disabled")
} else {
client, clientCfg, err := initializeOpenID(cfg.DiscoveryURL, cfg.ClientID, cfg.Secret, cfg.RedirectionURL, cfg.Scopes)
if err != nil {
return nil, err
}
service.openIDConfig = clientCfg
service.openIDClient = client
}
// step: initialize the gin router
router := gin.New()
service.router = router
// step: load the templates
service.initializeTemplates()
for _, resource := range cfg.Resources {
log.Infof("protecting resources under uri: %s", resource)
}
for name, value := range cfg.ClaimsMatch {
log.Infof("the token must container the claim: %s, required: %s", name, value)
}
router.Use(gin.Recovery())
// step: are we logging the traffic?
if cfg.LogRequests {
router.Use(service.loggingHandler())
}
// step: if gin release production
if os.Getenv("GIN_MODE") == "release" {
log.Infof("enabling the security handler for release mode")
router.Use(service.securityHandler())
}
router.Use(service.entrypointHandler(), service.authenticationHandler(), service.admissionHandler())
router.GET(authorizationURL, service.oauthAuthorizationHandler)
router.GET(callbackURL, service.oauthCallbackHandler)
router.GET(healthURL, service.healthHandler)
router.Use(service.proxyHandler())
return service, nil
}
// initializeTemplates loads the custom template
func (r *KeycloakProxy) initializeTemplates() {
var list []string
if r.config.SignInPage != "" {
log.Debugf("loading the custom sign in page: %s", r.config.SignInPage)
list = append(list, r.config.SignInPage)
}
if r.config.ForbiddenPage != "" {
log.Debugf("loading the custom sign forbidden page: %s", r.config.ForbiddenPage)
list = append(list, r.config.ForbiddenPage)
}
if len(list) > 0 {
r.router.LoadHTMLFiles(list...)
}
}
// Run starts the proxy service
func (r *KeycloakProxy) Run() error {
go func() {
log.Infof("keycloak proxy service starting on %s", r.config.Listen)
var err error
if r.config.TLSCertificate == "" {
err = r.router.Run(r.config.Listen)
} else {
err = r.router.RunTLS(r.config.Listen, r.config.TLSCertificate, r.config.TLSPrivateKey)
}
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatalf("failed to start the service")
}
}()
return nil
}
// redirectToURL redirects the user and aborts the context
func (r KeycloakProxy) redirectToURL(url string, cx *gin.Context) {
cx.Redirect(http.StatusTemporaryRedirect, url)
cx.Abort()
}
// accessForbidden redirects the user to the forbidden page
func (r KeycloakProxy) accessForbidden(cx *gin.Context) {
// step: do we have a custom forbidden page
if r.config.hasForbiddenPage() {
cx.HTML(http.StatusForbidden, r.config.ForbiddenPage, r.config.TagData)
return
}
cx.AbortWithStatus(http.StatusForbidden)
}
// redirectToAuthorization redirects the user to authorization handler
func (r KeycloakProxy) redirectToAuthorization(cx *gin.Context) {
// step: add a state referrer to the authorization page
authQuery := fmt.Sprintf("?state=%s", cx.Request.URL.String())
// step: if verification is switched off, we can't authorization
if r.config.SkipTokenVerification {
log.Errorf("refusing to redirection to authorization endpoint, skip token verification switched on")
r.accessForbidden(cx)
return
}
r.redirectToURL(authorizationURL+authQuery, cx)
}
// tryUpdateConnection attempt to upgrade the connection to a http pdy stream
func (r *KeycloakProxy) tryUpdateConnection(cx *gin.Context) error {
// step: dial the endpoint
tlsConn, err := tryDialEndpoint(r.upstreamURL)
if err != nil {
return err
}
defer tlsConn.Close()
// step: we need to hijack the underlining client connection
clientConn, _, err := cx.Writer.(http.Hijacker).Hijack()
if err != nil {
}
defer clientConn.Close()
// step: write the request to upstream
if err = cx.Request.Write(tlsConn); err != nil {
return err
}
// step: copy the date between client and upstream endpoint
var wg sync.WaitGroup
wg.Add(2)
go transferBytes(tlsConn, clientConn, &wg)
go transferBytes(clientConn, tlsConn, &wg)
wg.Wait()
return nil
}