forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
394 lines (373 loc) · 11.1 KB
/
config.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
/*
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 (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"path/filepath"
"regexp"
"strings"
"time"
"gopkg.in/yaml.v2"
"github.com/codegangsta/cli"
)
// newDefaultConfig returns a initialized config
func newDefaultConfig() *Config {
return &Config{
Listen: "127.0.0.1:3000",
RedirectionURL: "http://127.0.0.1:3000",
Upstream: "http://127.0.0.1:8081",
MaxSession: time.Duration(1) * time.Hour,
TagData: make(map[string]string, 0),
ClaimsMatch: make(map[string]string, 0),
CORSConfig: &CORS{
Origins: []string{},
Methods: []string{},
Headers: []string{},
},
}
}
// isValid validates if the config is valid
func (r *Config) isValid() error {
// step: validate the configuration
if r.Upstream == "" {
return fmt.Errorf("you have not specified an upstream endpoint to proxy to")
}
if _, err := url.Parse(r.Upstream); err != nil {
return fmt.Errorf("the upstream endpoint is invalid, %s", err)
}
if r.Listen == "" {
return fmt.Errorf("you have not specified the listening interface")
}
if r.TLSCertificate != "" && r.TLSPrivateKey == "" {
return fmt.Errorf("you have not provided a private key")
}
if r.TLSPrivateKey != "" && r.TLSCertificate == "" {
return fmt.Errorf("you have not provided a certificate file")
}
if r.TLSCertificate != "" && !fileExists(r.TLSCertificate) {
return fmt.Errorf("the tls certificate %s does not exist", r.TLSCertificate)
}
if r.TLSPrivateKey != "" && !fileExists(r.TLSPrivateKey) {
return fmt.Errorf("the tls private key %s does not exist", r.TLSPrivateKey)
}
if r.TLSCaCertificate != "" && !fileExists(r.TLSCaCertificate) {
return fmt.Errorf("the tls ca certificate file %s does not exist", r.TLSCaCertificate)
}
// step: if the skip verification is off, we need the below
if !r.SkipTokenVerification {
if r.DiscoveryURL == "" {
return fmt.Errorf("you have not specified the discovery url")
}
if r.ClientID == "" {
return fmt.Errorf("you have not specified the client id")
}
if r.Secret == "" {
return fmt.Errorf("you have not specified the client secret")
}
if r.RedirectionURL == "" {
return fmt.Errorf("you have not specified the redirection url")
}
if strings.HasSuffix(r.RedirectionURL, "/") {
r.RedirectionURL = strings.TrimSuffix(r.RedirectionURL, "/")
}
if r.EncryptionKey == "" && r.RefreshSessions {
return fmt.Errorf("you have not specified a encryption key for encoding the session state")
}
if r.EncryptionKey != "" && len(r.EncryptionKey) < 32 {
return fmt.Errorf("the encryption key is too short, must be longer than 32 characters")
}
if r.MaxSession == 0 && r.RefreshSessions {
r.MaxSession = time.Duration(6) * time.Hour
}
}
// step: valid the resources
for _, resource := range r.Resources {
if err := resource.isValid(); err != nil {
return err
}
}
// step: validate the claims are validate regex's
for k, claim := range r.ClaimsMatch {
// step: validate the regex
if _, err := regexp.Compile(claim); err != nil {
return fmt.Errorf("the claim matcher: %s for claim: %s is not a valid regex", claim, k)
}
}
return nil
}
// hasSignInPage checks if there is a custom sign in page
func (r *Config) hasSignInPage() bool {
if r.SignInPage != "" {
return true
}
return false
}
// hasForbiddenPage checks if there is a custom forbidden page
func (r *Config) hasForbiddenPage() bool {
if r.ForbiddenPage != "" {
return true
}
return false
}
// readOptions parses the command line options and constructs a config object
func readOptions(cx *cli.Context, config *Config) (err error) {
if cx.IsSet("listen") {
config.Listen = cx.String("listen")
}
if cx.IsSet("secret") {
config.Secret = cx.String("secret")
}
if cx.IsSet("client-id") {
config.ClientID = cx.String("client-id")
}
if cx.IsSet("discovery-url") {
config.DiscoveryURL = cx.String("discovery-url")
}
if cx.IsSet("upstream-url") {
config.Upstream = cx.String("upstream-url")
}
if cx.IsSet("skip-token-verification") {
config.SkipTokenVerification = cx.Bool("skip-token-verification")
}
if cx.IsSet("encryption-key") {
config.EncryptionKey = cx.String("encryption-key")
}
if cx.IsSet("redirection-url") {
config.RedirectionURL = cx.String("redirection-url")
}
if cx.IsSet("tls-cert") {
config.TLSCertificate = cx.String("tls-cert")
}
if cx.IsSet("tls-private-key") {
config.TLSPrivateKey = cx.String("tls-private-key")
}
if cx.IsSet("tls-ca-certificate") {
config.TLSCaCertificate = cx.String("tls-ca-certificate")
}
if cx.IsSet("signin-page") {
config.SignInPage = cx.String("signin-page")
}
if cx.IsSet("forbidden-page") {
config.ForbiddenPage = cx.String("forbidden-page")
}
if cx.IsSet("max-session") {
config.MaxSession = cx.Duration("max-session")
}
if cx.IsSet("proxy-protocol") {
config.ProxyProtocol = cx.Bool("proxy-protocol")
}
if cx.IsSet("refresh-sessions") {
config.RefreshSessions = cx.Bool("refresh-sessions")
}
if cx.IsSet("json-logging") {
config.LogJSONFormat = cx.Bool("json-logging")
}
if cx.IsSet("log-requests") {
config.LogRequests = cx.Bool("log-requests")
}
if cx.IsSet("verbose") {
config.Verbose = cx.Bool("verbose")
}
if cx.IsSet("scope") {
config.Scopes = cx.StringSlice("scope")
}
if cx.IsSet("hostname") {
config.Hostnames = cx.StringSlice("hostname")
}
if cx.IsSet("tag") {
config.TagData, err = decodeKeyPairs(cx.StringSlice("tag"))
if err != nil {
return err
}
}
if cx.IsSet("claim") {
config.ClaimsMatch, err = decodeKeyPairs(cx.StringSlice("claim"))
if err != nil {
return err
}
}
if cx.IsSet("header") {
config.Header, err = decodeKeyPairs(cx.StringSlice("header"))
if err != nil {
return err
}
}
if cx.IsSet("cors-origins") {
config.CORSConfig.Origins = cx.StringSlice("cors-origins")
}
if cx.IsSet("cors-methods") {
config.CORSConfig.Methods = cx.StringSlice("cors-methods")
}
if cx.IsSet("cors-headers") {
config.CORSConfig.Headers = cx.StringSlice("cors-headers")
}
if cx.IsSet("cors-max-age") {
config.CORSConfig.MaxAge = cx.Duration("cors-max-age")
}
if cx.IsSet("resource") {
for _, x := range cx.StringSlice("resource") {
resource, err := decodeResource(x)
if err != nil {
return fmt.Errorf("invalid resource %s, %s", x, err)
}
config.Resources = append(config.Resources, resource)
}
}
return nil
}
// readConfigFile reads and parses the configuration file
func readConfigFile(filename string, config *Config) error {
// step: read in the contents of the file
content, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
// step: attempt to un-marshal the data
if isJson := filepath.Ext(filename) == "json"; isJson {
err = json.Unmarshal(content, config)
} else {
err = yaml.Unmarshal(content, config)
}
if err != nil {
return err
}
return nil
}
// getOptions returns the command line options
func getOptions() []cli.Flag {
defaults := newDefaultConfig()
return []cli.Flag{
cli.StringFlag{
Name: "config",
Usage: "the path to the configuration file for the keycloak proxy",
},
cli.StringFlag{
Name: "listen",
Usage: "the interface the service should be listening on",
Value: defaults.Listen,
},
cli.StringFlag{
Name: "secret",
Usage: "the client secret used to authenticate to the oauth server",
},
cli.StringFlag{
Name: "client-id",
Usage: "the client id used to authenticate to the oauth serves",
},
cli.StringFlag{
Name: "discovery-url",
Usage: "the discovery url to retrieve the openid configuration",
},
cli.StringFlag{
Name: "upstream-url",
Usage: "the url for the upstream endpoint you wish to proxy to",
Value: defaults.Upstream,
},
cli.StringFlag{
Name: "encryption-key",
Usage: "the encryption key used to encrpytion the session state",
},
cli.StringFlag{
Name: "redirection-url",
Usage: "the redirection url, namely the site url, note: " + oauthURL + " will be added to it",
},
cli.StringSliceFlag{
Name: "hostname",
Usage: "a list of hostname which the service will respond to, defaults to all",
},
cli.StringFlag{
Name: "tls-cert",
Usage: "the path to a certificate file used for TLS",
},
cli.StringFlag{
Name: "tls-private-key",
Usage: "the path to the private key for TLS support",
},
cli.StringFlag{
Name: "tls-ca-certificate",
Usage: "the path to the ca certificate used for mutual TLS",
},
cli.StringSliceFlag{
Name: "scope",
Usage: "a variable list of scopes requested when authenticating the user",
},
cli.StringSliceFlag{
Name: "claim",
Usage: "a series of key pair values which must match the claims in the token present e.g. aud=myapp, iss=http://example.com etcd",
},
cli.StringSliceFlag{
Name: "resource",
Usage: "a list of resources 'uri=/admin|methods=GET|roles=role1,role2'",
},
cli.StringFlag{
Name: "signin-page",
Usage: "a custom template displayed for signin",
},
cli.StringFlag{
Name: "forbidden-page",
Usage: "a custom template used for access forbidden",
},
cli.StringSliceFlag{
Name: "tag",
Usage: "a keypair tag which is passed to the templates when render, i.e. title='My Page',site='my name' etc",
},
cli.DurationFlag{
Name: "max-session",
Usage: "if refresh sessions are enabled we can limit their duration via this",
Value: defaults.MaxSession,
},
cli.StringSliceFlag{
Name: "cors-origins",
Usage: "a set of origins to add to the CORS access control (Access-Control-Allow-Origin)",
},
cli.StringSliceFlag{
Name: "cors-headers",
Usage: "a set of headers to add to the CORS access control (Access-Control-Allow-Headers)",
},
cli.StringSliceFlag{
Name: "cors-methods",
Usage: "the method permitted in the access control (Access-Control-Allow-Methods)",
},
cli.DurationFlag{
Name: "cors-max-age",
Usage: "the max age applied to cors headers (Access-Control-Max-Age)",
},
cli.BoolFlag{
Name: "skip-token-verification",
Usage: "testing purposes ONLY, the option allows you to bypass the token verification, expiration and roles are still enforced",
},
cli.BoolFlag{
Name: "proxy-protocol",
Usage: "switches on proxy protocol support on the listen (not supported yet)",
},
cli.BoolFlag{
Name: "refresh-sessions",
Usage: "enables the refreshing of tokens via offline access (defaults false)",
},
cli.BoolTFlag{
Name: "json-logging",
Usage: "switch on json logging rather than text (defaults true)",
},
cli.BoolTFlag{
Name: "log-requests",
Usage: "switch on logging of all incoming requests (defaults true)",
},
cli.BoolFlag{
Name: "verbose",
Usage: "switch on debug / verbose logging",
},
}
}