-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
353 lines (312 loc) · 8.32 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
package main
import (
"errors"
"fmt"
"math"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/willemschots/househunt/internal/auth"
"github.com/willemschots/househunt/internal/email"
"github.com/willemschots/househunt/internal/email/postmark"
"github.com/willemschots/househunt/internal/krypto"
"github.com/willemschots/househunt/internal/web"
)
// httpConfig is the configuration for the HTTP server.
type httpConfig struct {
addr string
readTimeout time.Duration
writeTimeout time.Duration
idleTimeout time.Duration
shutdownTimeout time.Duration
// cookieKeys are the pairs of keys used to authenticate and encrypt cookies.
// see https://pkg.go.dev/github.com/gorilla/sessions for more information on how these
// are interpreted.
cookieKeys []krypto.Key
server web.ServerConfig
viewDir string // viewDir provides a directory to load templates from. If empty, the embedded templates are used.
}
// dbConfig is the database configuration.
type dbConfig struct {
file string
migrate bool
encryptionKeys []krypto.Key
blindIndexSalt krypto.Key
}
type emailConfig struct {
driver string
service email.ServiceConfig
postmark postmark.Settings
}
// config is the configuration for the server command.
type config struct {
http httpConfig
db dbConfig
auth auth.ServiceConfig
email emailConfig
}
// defaultConfig returns a config with sane default values.
func defaultConfig() config {
baseURL := must(url.Parse("http://localhost:8888"))
return config{
http: httpConfig{
addr: ":8888",
readTimeout: time.Second * 5,
writeTimeout: time.Second * 10,
idleTimeout: time.Second * 120,
shutdownTimeout: time.Second * 15,
server: web.ServerConfig{
SecureCookie: true,
},
viewDir: "",
},
db: dbConfig{
file: "househunt.db",
migrate: true,
},
auth: auth.ServiceConfig{
WorkerTimeout: time.Second * 30,
TokenExpiry: time.Minute * 30,
},
email: emailConfig{
driver: "log",
service: email.ServiceConfig{
BaseURL: baseURL,
},
postmark: postmark.Settings{
APIURL: must(url.Parse("https://api.postmarkapp.com/email")),
MessageStream: "outbound",
},
},
}
}
type envVariable struct {
// required indicates if that an env variable must be provided by the user.
required bool
// mapFunc maps the env variable value to the config struct.
mapFunc func(v string, c *config) error
}
// envMap maps environment variable names to fields in the config struct.
var envMap = map[string]envVariable{
"BASE_URL": {
mapFunc: func(v string, c *config) error {
return confURL(v, c.email.service.BaseURL)
},
},
"HTTP_ADDR": {
mapFunc: func(v string, c *config) error {
c.http.addr = v
return nil
},
},
"HTTP_READ_TIMEOUT": {
mapFunc: func(v string, c *config) error {
return confDuration(v, &c.http.readTimeout, 0, math.MaxInt64)
},
},
"HTTP_WRITE_TIMEOUT": {
mapFunc: func(v string, c *config) error {
return confDuration(v, &c.http.writeTimeout, 0, math.MaxInt64)
},
},
"HTTP_IDLE_TIMEOUT": {
mapFunc: func(v string, c *config) error {
return confDuration(v, &c.http.idleTimeout, 0, math.MaxInt64)
},
},
"HTTP_SHUTDOWN_TIMEOUT": {
mapFunc: func(v string, c *config) error {
return confDuration(v, &c.http.shutdownTimeout, 0, math.MaxInt64)
},
},
"HTTP_COOKIE_KEYS": {
required: true,
mapFunc: func(v string, c *config) error {
return confSliceOf(v, &c.http.cookieKeys, krypto.ParseKey, 2, math.MaxInt64)
},
},
"HTTP_SECURE_COOKIE": {
mapFunc: func(v string, c *config) error {
return confBool(v, &c.http.server.SecureCookie)
},
},
"HTTP_CSRF_KEY": {
required: true,
mapFunc: func(v string, c *config) error {
return confCryptoKey(v, &c.http.server.CSRFKey)
},
},
"HTTP_VIEW_DIR": {
mapFunc: func(v string, c *config) error {
return confString(v, &c.http.viewDir, 0, math.MaxInt64)
},
},
"DB_FILENAME": {
mapFunc: func(v string, c *config) error {
return confString(v, &c.db.file, 1, math.MaxInt64)
},
},
"DB_MIGRATE": {
mapFunc: func(v string, c *config) error {
return confBool(v, &c.db.migrate)
},
},
"DB_BLIND_INDEX_SALT": {
required: true,
mapFunc: func(v string, c *config) error {
return confCryptoKey(v, &c.db.blindIndexSalt)
},
},
"DB_ENCRYPTION_KEYS": {
required: true,
mapFunc: func(v string, c *config) error {
return confSliceOf(v, &c.db.encryptionKeys, krypto.ParseKey, 2, math.MaxInt64)
},
},
"AUTH_WORKER_TIMEOUT": {
mapFunc: func(v string, c *config) error {
return confDuration(v, &c.auth.WorkerTimeout, 0, math.MaxInt64)
},
},
"AUTH_TOKEN_EXPIRY": {
mapFunc: func(v string, c *config) error {
return confDuration(v, &c.auth.TokenExpiry, 0, math.MaxInt64)
},
},
"EMAIL_DRIVER": {
mapFunc: func(v string, c *config) error {
c.email.driver = v // validated later on.
return nil
},
},
"EMAIL_FROM": {
required: true,
mapFunc: func(v string, c *config) error {
return confEmailAddress(v, &c.email.service.From)
},
},
"POSTMARK_API_URL": {
mapFunc: func(v string, c *config) error {
return confURL(v, c.email.postmark.APIURL)
},
},
"POSTMARK_MESSAGE_STREAM": {
mapFunc: func(v string, c *config) error {
c.email.postmark.MessageStream = v
return nil
},
},
"POSTMARK_SERVER_TOKEN": {
mapFunc: func(v string, c *config) error {
return confSecret(v, &c.email.postmark.ServerToken)
},
},
}
// configFromEnv returns a config with values from the environment. It falls
// back to default values for any missing environment variables.
//
// It does a best effort to validate provided values, so that mistakes are
// caught ASAP. However, there is no guarantee that the returned config
// is valid and will work.
func configFromEnv() (config, error) {
c := defaultConfig()
var errSum error
for key, envVar := range envMap {
val, ok := os.LookupEnv(key)
if !ok {
if envVar.required {
errSum = errors.Join(errSum, fmt.Errorf("missing required env variable %s", key))
}
continue
}
if err := envVar.mapFunc(val, &c); err != nil {
errSum = errors.Join(errSum, fmt.Errorf("invalid env variable %s: %w", key, err))
}
}
return c, errSum
}
// confDuration attempts to parse v into tgt as an URL.
func confURL(v string, tgt *url.URL) error {
u, err := url.Parse(v)
if err != nil {
return err
}
if u.Scheme == "" || u.Host == "" {
return fmt.Errorf("URL %s is missing scheme or host", v)
}
*tgt = *u
return nil
}
// confDuration attempts to parse v into tgt and checks if the result is in
// the provided range (inclusive).
func confDuration(v string, tgt *time.Duration, min, max time.Duration) error {
dur, err := time.ParseDuration(v)
if err != nil {
return err
}
if dur < min || dur > max {
return fmt.Errorf("duration %s not in range [%s, %s] (inclusive)", dur, min, max)
}
*tgt = dur
return nil
}
func confString(v string, tgt *string, minLen, maxLen int) error {
if len(v) < minLen || len(v) > maxLen {
return fmt.Errorf("string length %d not in range [%d, %d] (inclusive)", len(v), minLen, maxLen)
}
*tgt = v
return nil
}
// confDuration attempts to parse v into tgt as a bool.
func confBool(v string, tgt *bool) error {
b, err := strconv.ParseBool(v)
if err != nil {
return err
}
*tgt = b
return nil
}
// confCryptoKey attempts to parse v into tgt as a crypto key.
func confCryptoKey(v string, tgt *krypto.Key) error {
k, err := krypto.ParseKey(v)
if err != nil {
return err
}
*tgt = k
return nil
}
// confSecret attempts to parse v into tgt as a secret
func confSecret(v string, tgt *krypto.Secret) error {
*tgt = krypto.NewSecret(v)
return nil
}
// confDuration attempts to parse v into tgt as an email address.
func confEmailAddress(v string, tgt *email.Address) error {
email, err := email.ParseAddress(v)
if err != nil {
return err
}
*tgt = email
return nil
}
func confSliceOf[T any](v string, tgt *[]T, elemFunc func(string) (T, error), minLen, maxLen int) error {
for i, elem := range strings.Split(v, ",") {
parsed, err := elemFunc(elem)
if err != nil {
return fmt.Errorf("failed to parse element %d: %w", i, err)
}
*tgt = append(*tgt, parsed)
}
if len(v) < minLen || len(v) > maxLen {
return fmt.Errorf("slice length %d not in range [%d, %d] (inclusive)", len(v), minLen, maxLen)
}
return nil
}
func must[T any](t T, err error) T {
if err != nil {
panic(err)
}
return t
}