forked from qvest-digital/loginsrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
239 lines (210 loc) · 7.93 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
package login
import (
"errors"
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/tarent/loginsrv/logging"
"github.com/tarent/loginsrv/oauth2"
)
var jwtDefaultSecret string
func init() {
rand.Seed(time.Now().UTC().UnixNano())
jwtDefaultSecret = randStringBytes(32)
}
// DefaultConfig for the loginsrv handler
func DefaultConfig() *Config {
return &Config{
Host: "localhost",
Port: "6789",
LogLevel: "info",
JwtSecret: jwtDefaultSecret,
JwtAlgo: "HS512",
JwtExpiry: 24 * time.Hour,
JwtRefreshes: 0,
SuccessURL: "/",
Redirect: true,
RedirectQueryParameter: "backTo",
RedirectCheckReferer: true,
RedirectHostFile: "",
LogoutURL: "",
LoginPath: "/login",
CookieName: "jwt_token",
CookieHTTPOnly: true,
CookieSecure: true,
Backends: Options{},
Oauth: Options{},
GracePeriod: 5 * time.Second,
UserFile: "",
}
}
const envPrefix = "LOGINSRV_"
// Config for the loginsrv handler
type Config struct {
Host string
Port string
LogLevel string
TextLogging bool
JwtSecret string
JwtAlgo string
JwtExpiry time.Duration
JwtRefreshes int
SuccessURL string
Redirect bool
RedirectQueryParameter string
RedirectCheckReferer bool
RedirectHostFile string
LogoutURL string
Template string
LoginPath string
CookieName string
CookieExpiry time.Duration
CookieDomain string
CookieHTTPOnly bool
CookieSecure bool
Backends Options
Oauth Options
GracePeriod time.Duration
UserFile string
}
// Options is the configuration structure for oauth and backend provider
// key is the providername, value is a options map.
type Options map[string]map[string]string
// addOauthOpts adds the options for a provider in the form of key=value,key=value,..
func (c *Config) addOauthOpts(providerName, optsKvList string) error {
opts, err := parseOptions(optsKvList)
if err != nil {
return err
}
c.Oauth[providerName] = opts
return nil
}
// addBackendOpts adds the options for a provider in the form of key=value,key=value,..
func (c *Config) addBackendOpts(providerName, optsKvList string) error {
opts, err := parseOptions(optsKvList)
if err != nil {
return err
}
c.Backends[providerName] = opts
return nil
}
// ConfigureFlagSet adds all flags to the supplied flag set
func (c *Config) ConfigureFlagSet(f *flag.FlagSet) {
f.StringVar(&c.Host, "host", c.Host, "The host to listen on")
f.StringVar(&c.Port, "port", c.Port, "The port to listen on")
f.StringVar(&c.LogLevel, "log-level", c.LogLevel, "The log level")
f.BoolVar(&c.TextLogging, "text-logging", c.TextLogging, "Log in text format instead of json")
f.StringVar(&c.JwtSecret, "jwt-secret", c.JwtSecret, "The secret to sign the jwt token")
f.StringVar(&c.JwtAlgo, "jwt-algo", c.JwtAlgo, "The singing algorithm to use (ES256, ES384, ES512, HS512, HS256, HS384, HS512)")
f.DurationVar(&c.JwtExpiry, "jwt-expiry", c.JwtExpiry, "The expiry duration for the jwt token, e.g. 2h or 3h30m")
f.IntVar(&c.JwtRefreshes, "jwt-refreshes", c.JwtRefreshes, "The maximum amount of jwt refreshes. 0 by Default")
f.StringVar(&c.CookieName, "cookie-name", c.CookieName, "The name of the jwt cookie")
f.BoolVar(&c.CookieHTTPOnly, "cookie-http-only", c.CookieHTTPOnly, "Set the cookie with the http only flag")
f.BoolVar(&c.CookieSecure, "cookie-secure", c.CookieSecure, "Set the cookie with the secure flag")
f.DurationVar(&c.CookieExpiry, "cookie-expiry", c.CookieExpiry, "The expiry duration for the cookie, e.g. 2h or 3h30m. Default is browser session")
f.StringVar(&c.CookieDomain, "cookie-domain", c.CookieDomain, "The optional domain parameter for the cookie")
f.StringVar(&c.SuccessURL, "success-url", c.SuccessURL, "The url to redirect after login")
f.BoolVar(&c.Redirect, "redirect", c.Redirect, "Allow dynamic overwriting of the the success by query parameter")
f.StringVar(&c.RedirectQueryParameter, "redirect-query-parameter", c.RedirectQueryParameter, "URL parameter for the redirect target")
f.BoolVar(&c.RedirectCheckReferer, "redirect-check-referer", c.RedirectCheckReferer, "When redirecting check that the referer is the same domain")
f.StringVar(&c.RedirectHostFile, "redirect-host-file", c.RedirectHostFile, "A file containing a list of domains that redirects are allowed to, one domain per line")
f.StringVar(&c.LogoutURL, "logout-url", c.LogoutURL, "The url or path to redirect after logout")
f.StringVar(&c.Template, "template", c.Template, "An alternative template for the login form")
f.StringVar(&c.LoginPath, "login-path", c.LoginPath, "The path of the login resource")
f.DurationVar(&c.GracePeriod, "grace-period", c.GracePeriod, "Graceful shutdown grace period")
f.StringVar(&c.UserFile, "user-file", c.UserFile, "A YAML file with user specific data for the tokens")
// the -backends is deprecated, but we support it for backwards compatibility
deprecatedBackends := setFunc(func(optsKvList string) error {
logging.Logger.Warn("DEPRECATED: '-backend' is no longer supported. Please set the backends by explicit parameters")
opts, err := parseOptions(optsKvList)
if err != nil {
return err
}
pName, ok := opts["provider"]
if !ok {
return errors.New("missing provider name provider=...")
}
delete(opts, "provider")
c.Backends[pName] = opts
return nil
})
f.Var(deprecatedBackends, "backend", "Deprecated, please use the explicit flags")
// One option for each oauth provider
for _, pName := range oauth2.ProviderList() {
func(pName string) {
setter := setFunc(func(optsKvList string) error {
return c.addOauthOpts(pName, optsKvList)
})
f.Var(setter, pName, "Oauth config in the form: client_id=..,client_secret=..[,scope=..,][redirect_uri=..]")
}(pName)
}
// One option for each backend provider
for _, pName := range ProviderList() {
func(pName string) {
setter := setFunc(func(optsKvList string) error {
return c.addBackendOpts(pName, optsKvList)
})
desc, _ := GetProviderDescription(pName)
f.Var(setter, pName, desc.HelpText)
}(pName)
}
}
// ReadConfig from the commandline args
func ReadConfig() *Config {
c, err := readConfig(flag.CommandLine, os.Args[1:])
if err != nil {
// should never happen, because of flag default policy ExitOnError
panic(err)
}
return c
}
func readConfig(f *flag.FlagSet, args []string) (*Config, error) {
config := DefaultConfig()
config.ConfigureFlagSet(f)
// fist use the environment settings
f.VisitAll(func(f *flag.Flag) {
if val, isPresent := os.LookupEnv(envName(f.Name)); isPresent {
f.Value.Set(val)
}
})
// prefer flags over environment settings
err := f.Parse(args)
if err != nil {
return nil, err
}
return config, err
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func randStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func envName(flagName string) string {
return envPrefix + strings.Replace(strings.ToUpper(flagName), "-", "_", -1)
}
func parseOptions(b string) (map[string]string, error) {
opts := map[string]string{}
pairs := strings.Split(b, ",")
for _, p := range pairs {
pair := strings.SplitN(p, "=", 2)
if len(pair) != 2 {
return nil, fmt.Errorf("provider configuration has to be in form 'key1=value1,key2=..', but was %v", p)
}
opts[pair[0]] = pair[1]
}
return opts, nil
}
// Helper type to wrap a function closure with the Value interface
type setFunc func(optsKvList string) error
func (f setFunc) Set(value string) error {
return f(value)
}
func (f setFunc) String() string {
return "setFunc"
}