/
cfg.go
408 lines (361 loc) · 11.1 KB
/
cfg.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
package cfg
import (
"errors"
"flag"
"io/ioutil"
"math/rand"
"net"
"os"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/google"
"github.com/spf13/viper"
)
// config vouch jwt cookie configuration
type config struct {
LogLevel string `mapstructure:"logLevel"`
Listen string `mapstructure:"listen"`
Port int `mapstructure:"port"`
Domains []string `mapstructure:"domains"`
WhiteList []string `mapstructure:"whitelist"`
AllowAllUsers bool `mapstructure:"allowAllUsers"`
PublicAccess bool `mapstructure:"publicAccess"`
JWT struct {
MaxAge int `mapstructure:"maxAge"`
Issuer string `mapstructure:"issuer"`
Secret string `mapstructure:"secret"`
Compress bool `mapstructure:"compress"`
}
Cookie struct {
Name string `mapstructure:"name"`
Domain string `mapstructure:"domain"`
Secure bool `mapstructure:"secure"`
HTTPOnly bool `mapstructure:"httpOnly"`
}
Headers struct {
JWT string `mapstructure:"jwt"`
User string `mapstructure:"user"`
QueryString string `mapstructure:"querystring"`
Redirect string `mapstructure:"redirect"`
Success string `mapstructure:"success"`
}
DB struct {
File string `mapstructure:"file"`
}
Session struct {
Name string `mapstructure:"name"`
}
TestURL string `mapstructure:"test_url"`
TestURLs []string `mapstructure:"test_urls"`
Testing bool `mapstructure:"testing"`
WebApp bool `mapstructure:"webapp"`
}
// oauth config items endoint for access
type oauthConfig struct {
Provider string `mapstructure:"provider"`
ClientID string `mapstructure:"client_id"`
ClientSecret string `mapstructure:"client_secret"`
AuthURL string `mapstructure:"auth_url"`
TokenURL string `mapstructure:"token_url"`
RedirectURL string `mapstructure:"callback_url"`
RedirectURLs []string `mapstructure:"callback_urls"`
Scopes []string `mapstructure:"scopes"`
UserInfoURL string `mapstructure:"user_info_url"`
PreferredDomain string `mapstructre:"preferredDomain"`
}
// OAuthProviders holds the stings for
type OAuthProviders struct {
Google string
GitHub string
IndieAuth string
OIDC string
}
type branding struct {
LCName string // lower case
UCName string // upper case
CcName string // camel case
OldLCName string // lasso
URL string // https://github.com/vouch/vouch-proxy
}
var (
// Branding that's our name
Branding = branding{"vouch", "VOUCH", "Vouch", "lasso", "https://github.com/vouch/vouch-proxy"}
// Cfg the main exported config variable
Cfg config
// GenOAuth exported OAuth config variable
// TODO: I think GenOAuth and OAuthConfig can be combined!
// perhaps by https://golang.org/doc/effective_go.html#embedding
GenOAuth *oauthConfig
// OAuthClient is the configured client which will call the provider
// this actually carries the oauth2 client ala oauthclient.Client(oauth2.NoContext, providerToken)
OAuthClient *oauth2.Config
// OAuthopts authentication options
OAuthopts oauth2.AuthCodeOption
// Providers static strings to test against
Providers = &OAuthProviders{
Google: "google",
GitHub: "github",
IndieAuth: "indieauth",
OIDC: "oidc",
}
)
// RequiredOptions must have these fields set for minimum viable config
var RequiredOptions = []string{"oauth.provider", "oauth.client_id"}
func init() {
// from config file
ParseConfig()
// can pass loglevel on the command line
var ll = flag.String("loglevel", Cfg.LogLevel, "enable debug log output")
var port = flag.Int("port", -1, "port")
var help = flag.Bool("help", false, "show usage")
flag.Parse()
if *help {
flag.PrintDefaults()
os.Exit(1)
}
if *ll == "debug" {
log.SetLevel(log.DebugLevel)
log.Debug("logLevel set to debug")
}
setDefaults()
if *port != -1 {
Cfg.Port = *port
}
errT := BasicTest()
if errT != nil {
// log.Fatalf(errT.Error())
panic(errT)
}
var listen = Cfg.Listen + ":" + strconv.Itoa(Cfg.Port)
if !isTCPPortAvailable(listen) {
log.Fatal(errors.New("check the port availability (is " + Branding.CcName + " already running?)"))
}
log.Debug(viper.AllSettings())
}
// ParseConfig parse the config file
func ParseConfig() {
log.Debug("opening config")
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(os.Getenv(Branding.UCName+"_ROOT") + "config")
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
log.Fatalf("Fatal error config file: %s", err.Error())
panic(err)
}
UnmarshalKey(Branding.LCName, &Cfg)
if len(Cfg.Domains) == 0 {
// then lets check for "lasso"
var oldConfig config
UnmarshalKey(Branding.OldLCName, &oldConfig)
if len(oldConfig.Domains) != 0 {
log.Errorf(`
IMPORTANT!
please update your config file to change '%s:' to '%s:' as per %s
`, Branding.OldLCName, Branding.LCName, Branding.URL)
Cfg = oldConfig
}
}
// don't log the secret!
// log.Debugf("secret: %s", string(Cfg.JWT.Secret))
}
// UnmarshalKey populate struct from contents of cfg tree at key
func UnmarshalKey(key string, rawVal interface{}) error {
return viper.UnmarshalKey(key, rawVal)
}
// Get string value for key
func Get(key string) string {
return viper.GetString(key)
}
// BasicTest just a quick sanity check to see if the config is sound
func BasicTest() error {
for _, opt := range RequiredOptions {
if !viper.IsSet(opt) {
return errors.New("configuration option " + opt + " is not set in config")
}
}
return nil
}
// setDefaults set default options for some items
func setDefaults() {
// this should really be done by Viper up in parseConfig but..
// nested defaults is currently *broken*
// https://github.com/spf13/viper/issues/309
// viper.SetDefault("listen", "0.0.0.0")
// viper.SetDefault(Cfg.Port, 9090)
// viper.SetDefault("Headers.SSO", "X-"+Branding.CcName+"-Token")
// viper.SetDefault("Headers.Redirect", "X-"+Branding.CcName+"-Requested-URI")
// viper.SetDefault("Cookie.Name", "Vouch")
// logging
if !viper.IsSet(Branding.LCName + ".logLevel") {
Cfg.LogLevel = "info"
}
// network defaults
if !viper.IsSet(Branding.LCName + ".listen") {
Cfg.Listen = "0.0.0.0"
}
if !viper.IsSet(Branding.LCName + ".port") {
Cfg.Port = 9090
}
if !viper.IsSet(Branding.LCName + ".allowAllUsers") {
Cfg.AllowAllUsers = false
}
if !viper.IsSet(Branding.LCName + ".publicAccess") {
Cfg.PublicAccess = false
}
// jwt defaults
if !viper.IsSet(Branding.LCName + ".jwt.secret") {
Cfg.JWT.Secret = getOrGenerateJWTSecret()
}
if !viper.IsSet(Branding.LCName + ".jwt.issuer") {
Cfg.JWT.Issuer = Branding.CcName
}
if !viper.IsSet(Branding.LCName + ".jwt.maxAge") {
Cfg.JWT.MaxAge = 240
}
if !viper.IsSet(Branding.LCName + ".jwt.compress") {
Cfg.JWT.Compress = true
}
// cookie defaults
if !viper.IsSet(Branding.LCName + ".cookie.name") {
Cfg.Cookie.Name = "VouchCookie"
}
if !viper.IsSet(Branding.LCName + ".cookie.secure") {
Cfg.Cookie.Secure = false
}
if !viper.IsSet(Branding.LCName + ".cookie.httpOnly") {
Cfg.Cookie.HTTPOnly = true
}
// headers defaults
if !viper.IsSet(Branding.LCName + ".headers.jwt") {
Cfg.Headers.JWT = "X-" + Branding.CcName + "-Token"
}
if !viper.IsSet(Branding.LCName + ".headers.querystring") {
Cfg.Headers.QueryString = "access_token"
}
if !viper.IsSet(Branding.LCName + ".headers.redirect") {
Cfg.Headers.Redirect = "X-" + Branding.CcName + "-Requested-URI"
}
if !viper.IsSet(Branding.LCName + ".headers.user") {
Cfg.Headers.User = "X-" + Branding.CcName + "-User"
}
if !viper.IsSet(Branding.LCName + ".headers.success") {
Cfg.Headers.Success = "X-" + Branding.CcName + "-Success"
}
// db defaults
if !viper.IsSet(Branding.LCName + ".db.file") {
Cfg.DB.File = "data/" + Branding.LCName + "_bolt.db"
}
// session HERE
if !viper.IsSet(Branding.LCName + ".session.name") {
Cfg.Session.Name = Branding.LCName + "Session"
}
// testing convenience variable
if !viper.IsSet(Branding.LCName + ".testing") {
Cfg.Testing = false
}
if viper.IsSet(Branding.LCName + ".test_url") {
Cfg.TestURLs = append(Cfg.TestURLs, Cfg.TestURL)
}
// TODO: proably change this name, maybe set the domain/port the webapp runs on
if !viper.IsSet(Branding.LCName + ".webapp") {
Cfg.WebApp = false
}
// OAuth defaults and client configuration
err := UnmarshalKey("oauth", &GenOAuth)
if err == nil {
if GenOAuth.Provider == Providers.Google {
setDefaultsGoogle()
// setDefaultsGoogle also configures the OAuthClient
} else if GenOAuth.Provider == Providers.GitHub {
setDefaultsGitHub()
configureOAuthClient()
} else {
configureOAuthClient()
}
}
}
func setDefaultsGoogle() {
log.Info("configuring Google OAuth")
GenOAuth.UserInfoURL = "https://www.googleapis.com/oauth2/v3/userinfo"
OAuthClient = &oauth2.Config{
ClientID: GenOAuth.ClientID,
ClientSecret: GenOAuth.ClientSecret,
Scopes: []string{
// You have to select a scope from
// https://developers.google.com/identity/protocols/googlescopes#google_sign-in
"https://www.googleapis.com/auth/userinfo.email",
},
Endpoint: google.Endpoint,
}
if GenOAuth.PreferredDomain != "" {
log.Infof("setting Google OAuth preferred login domain param 'hd' to %s", GenOAuth.PreferredDomain)
OAuthopts = oauth2.SetAuthURLParam("hd", GenOAuth.PreferredDomain)
}
}
func setDefaultsGitHub() {
// log.Info("configuring GitHub OAuth")
if GenOAuth.AuthURL == "" {
GenOAuth.AuthURL = github.Endpoint.AuthURL
}
if GenOAuth.TokenURL == "" {
GenOAuth.TokenURL = github.Endpoint.TokenURL
}
if GenOAuth.UserInfoURL == "" {
GenOAuth.UserInfoURL = "https://api.github.com/user?access_token="
}
if len(GenOAuth.Scopes) == 0 {
GenOAuth.Scopes = []string{"user"}
}
}
func configureOAuthClient() {
log.Infof("configuring %s OAuth with Endpoint %s", GenOAuth.Provider, GenOAuth.AuthURL)
OAuthClient = &oauth2.Config{
ClientID: GenOAuth.ClientID,
ClientSecret: GenOAuth.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: GenOAuth.AuthURL,
TokenURL: GenOAuth.TokenURL,
},
RedirectURL: GenOAuth.RedirectURL,
Scopes: GenOAuth.Scopes,
}
}
var secretFile = os.Getenv("VOUCH_ROOT") + "config/secret"
// a-z A-Z 0-9 except no l, o, O
const charRunes = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ012346789"
const secretLen = 18
func getOrGenerateJWTSecret() string {
b, err := ioutil.ReadFile(secretFile)
if err == nil {
log.Info("jwt.secret read from " + secretFile)
} else {
// then generate a new secret and store it in the file
log.Debug(err)
log.Info("jwt.secret not found in " + secretFile)
log.Warn("generating random jwt.secret and storing it in " + secretFile)
rand.Seed(time.Now().UnixNano())
b := make([]byte, secretLen)
for i := range b {
b[i] = charRunes[rand.Intn(len(charRunes))]
}
err := ioutil.WriteFile(secretFile, b, 0600)
if err != nil {
log.Debug(err)
}
}
return string(b)
}
func isTCPPortAvailable(listen string) bool {
log.Debug("checking availability of tcp port: " + listen)
conn, err := net.Listen("tcp", listen)
if err != nil {
log.Error(err)
return false
}
conn.Close()
return true
}