-
Notifications
You must be signed in to change notification settings - Fork 0
/
servecmd.go
407 lines (348 loc) · 10.5 KB
/
servecmd.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
package cmd
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"github.com/chutommy/eetgateway/pkg/ca"
"github.com/chutommy/eetgateway/pkg/fscr"
"github.com/chutommy/eetgateway/pkg/gateway"
"github.com/chutommy/eetgateway/pkg/keystore"
"github.com/chutommy/eetgateway/pkg/server"
"github.com/fsnotify/fsnotify"
"github.com/go-redis/redis/v8"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"io/ioutil"
slog "log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
const (
configPathFlag = "config"
)
func initServeCmd() {
configDir, err := osConfigDir()
if err != nil {
panic(err)
}
configPath := filepath.Join(configDir, configFile)
serveCmd.Flags().StringP(configPathFlag, "c", configPath, "path to config file")
}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Initialize the EET Gateway API server",
Args: cobra.NoArgs,
RunE: serveCmdRunE,
}
func serveCmdRunE(cmd *cobra.Command, _ []string) error {
configPath, err := cmd.Flags().GetString(configPathFlag)
if err != nil {
return fmt.Errorf("retrieve 'path' flag: %w", err)
}
// configuration
setDefaultConfig()
loadConfigFromENV()
err = loadConfigFromFile(configPath)
if err != nil {
return fmt.Errorf("load config from file: %w", err)
}
setupLogger()
log.Info().
Str("entity", "Config Service").
Str("action", "loading configuration").
Str("from", "environment variables").
Send()
log.Info().
Str("entity", "Config Service").
Str("action", "loading configuration").
Str("status", "configuration set").
Str("path", configPath).
Send()
log.Info().
Str("entity", "EET Gateway").
Str("action", "initiating").
Send()
defer log.Info().
Str("entity", "EET Gateway").
Str("action", "exiting").
Send()
caSvc, err := newCASvc()
if err != nil {
return fmt.Errorf("start CA service: %w", err)
}
client, err := newFSCRClient()
if err != nil {
return fmt.Errorf("start FSCR client: %w", err)
}
ks, err := newKeystoreSvc()
if err != nil {
return fmt.Errorf("start keystore client: %w", err)
}
gSvc := newGatewaySvc(client, caSvc, ks)
h := server.NewHTTPHandler(gSvc)
httpServer, err := newHTTPServer(h)
if err != nil {
return fmt.Errorf("create http server: %w", err)
}
srv := server.NewService(httpServer)
runServer(srv)
return nil
}
func newHTTPServer(h server.Handler) (*http.Server, error) {
httpServer := &http.Server{
Addr: viper.GetString(serverAddr),
ReadTimeout: viper.GetDuration(serverReadTimeout),
ReadHeaderTimeout: viper.GetDuration(serverReadHeaderTimeout),
WriteTimeout: viper.GetDuration(serverWriteTimeout),
IdleTimeout: viper.GetDuration(serverIdleTimeout),
MaxHeaderBytes: viper.GetInt(serverMaxHeaderBytes),
Handler: h.HTTPHandler(),
ErrorLog: slog.New(ioutil.Discard, "", 0),
}
if viper.GetBool(serverTLSEnable) {
cert, err := tls.LoadX509KeyPair(viper.GetString(serverTLSCertificate), viper.GetString(serverTLSPrivateKey))
if err != nil {
return nil, fmt.Errorf("load SSL certificate: %w", err)
}
httpServer.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0)
httpServer.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
}
}
if viper.GetBool(serverMutualTLSEnable) {
pool := x509.NewCertPool()
for _, v := range viper.GetStringSlice(serverMutualTLSClientCAs) {
data, err := ioutil.ReadFile(v)
if err != nil {
return nil, fmt.Errorf("read file %s: %w", v, err)
}
b, _ := pem.Decode(data)
cert, err := x509.ParseCertificate(b.Bytes)
if err != nil {
return nil, fmt.Errorf("parse client CA certificate %s: %w", v, err)
}
pool.AddCert(cert)
}
httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
httpServer.TLSConfig.ClientCAs = pool
}
return httpServer, nil
}
func runServer(srv server.Service) {
log.Info().
Str("entity", "HTTP Server").
Str("action", "listening").
Str("status", "online").
Dur("shutdownTimeout", viper.GetDuration(serverShutdownTimeout)).
Send()
err := srv.ListenAndServe(viper.GetBool(serverTLSEnable), viper.GetDuration(serverShutdownTimeout))
log.Info().
Str("entity", "HTTP Server").
Str("action", "shutting down").
Str("status", "offline").
Err(err).
Send()
}
func newGatewaySvc(client fscr.Client, caSvc fscr.CAService, ks keystore.Service) gateway.Service {
log.Info().
Str("entity", "HTTP Server").
Str("action", "starting").
Str("addr", viper.GetString(serverAddr)).
Dur("idleTimeout", viper.GetDuration(serverIdleTimeout)).
Dur("writeTimeout", viper.GetDuration(serverWriteTimeout)).
Dur("readTimeout", viper.GetDuration(serverReadTimeout)).
Dur("readHeaderTimeout", viper.GetDuration(serverReadHeaderTimeout)).
Int("maxHeaderBytes", viper.GetInt(serverMaxHeaderBytes)).
Send()
return gateway.NewService(client, caSvc, ks)
}
func newKeystoreSvc() (keystore.Service, error) {
log.Info().
Str("entity", "KeyStore Client").
Str("action", "starting").
Str("network", viper.GetString(redisNetwork)).
Str("addr", viper.GetString(redisAddr)).
Int("db", viper.GetInt(redisDB)).
Int("minIdleConns", viper.GetInt(redisMinIdleConns)).
Send()
opt := &redis.Options{
Network: viper.GetString(redisNetwork),
Addr: viper.GetString(redisAddr),
Username: viper.GetString(redisUsername),
Password: viper.GetString(redisPassword),
DB: viper.GetInt(redisDB),
PoolSize: viper.GetInt(redisPoolSize),
MinIdleConns: viper.GetInt(redisMinIdleConns),
IdleTimeout: viper.GetDuration(redisIdleTimeout),
DialTimeout: viper.GetDuration(redisDialTimeout),
ReadTimeout: viper.GetDuration(redisReadTimeout),
WriteTimeout: viper.GetDuration(redisWriteTimeout),
PoolTimeout: viper.GetDuration(redisPoolTimeout),
IdleCheckFrequency: viper.GetDuration(redisIdleCheckFrequency),
}
if viper.GetBool(redisTLSEnable) {
cert, err := tls.LoadX509KeyPair(viper.GetString(redisTLSCertificate), viper.GetString(redisTLSPrivateKey))
if err != nil {
return nil, fmt.Errorf("load redis TLS keypair: %w", err)
}
pool := x509.NewCertPool()
for _, v := range viper.GetStringSlice(redisTLSRootCAs) {
data, err := ioutil.ReadFile(v)
if err != nil {
return nil, fmt.Errorf("read file %s: %w", v, err)
}
b, _ := pem.Decode(data)
cert, err := x509.ParseCertificate(b.Bytes)
if err != nil {
return nil, fmt.Errorf("parse root CA certificate %s: %w", v, err)
}
pool.AddCert(cert)
}
opt.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: viper.GetString(redisTLSServerName),
RootCAs: pool,
ClientSessionCache: tls.NewLRUClientSessionCache(64),
MinVersion: tls.VersionTLS12,
}
}
ks := keystore.NewRedisService(redis.NewClient(opt))
if err := ks.Ping(context.Background()); err != nil {
return nil, fmt.Errorf("ping keystore: %w", err)
}
return ks, nil
}
func newFSCRClient() (fscr.Client, error) {
url, mode := fscrURL()
log.Info().
Str("entity", "FSCR Client").
Str("action", "starting").
Str("url", url).
Str("requestTimeout", viper.GetDuration(eetRequestTimeout).String()).
Str("mode", mode).
Send()
c := fscr.NewClient(&http.Client{
Timeout: viper.GetDuration(eetRequestTimeout),
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
ServerName: "eet.cz",
ClientAuth: tls.NoClientCert,
ClientSessionCache: tls.NewLRUClientSessionCache(64),
MinVersion: tls.VersionTLS13,
},
},
}, url)
if err := c.Ping(); err != nil {
return nil, fmt.Errorf("ping FSCR: %w", err)
}
return c, nil
}
func fscrURL() (string, string) {
url := fscr.PlaygroundURL
mode := "playground"
if viper.GetBool(eetProductionMode) {
url = fscr.ProductionURL
mode = "production"
}
return url, mode
}
func newCASvc() (fscr.CAService, error) {
mode, roots, err := getCARoots()
if err != nil {
return nil, fmt.Errorf("fetch CA roots and mode")
}
dsigPool := x509.NewCertPool()
if ok := dsigPool.AppendCertsFromPEM(ca.ICACertificate); !ok {
return nil, fmt.Errorf("append to dsig certificate pool")
}
log.Info().
Str("entity", "Certificate Authority Service").
Str("action", "starting").
Str("mode", mode).
Send()
return fscr.NewCAService(roots, dsigPool), nil
}
func getCARoots() (string, []*x509.Certificate, error) {
mode := "playground"
roots, err := ca.PlaygroundRoots()
if err != nil {
return "", nil, fmt.Errorf("retrieve playground roots: %w", err)
}
if viper.GetBool(eetProductionMode) {
mode = "production"
roots, err = ca.ProductionRoots()
if err != nil {
return "", nil, fmt.Errorf("retrieve production roots: %w", err)
}
}
return mode, roots, nil
}
func loadConfigFromFile(path string) error {
ext := filepath.Ext(path)
name := strings.TrimSuffix(filepath.Base(path), ext)
dir := filepath.Dir(path)
viper.SetConfigName(name)
viper.SetConfigType(ext[1:])
viper.AddConfigPath(dir)
if err := viper.ReadInConfig(); err != nil {
var vErr viper.ConfigFileNotFoundError
if errors.As(err, &vErr) {
setupLogger()
log.Info().
Str("entity", "Config Service").
Str("action", "loading configuration").
Str("status", "config file not found (skipping)").
Str("path", path).
Send()
} else {
return fmt.Errorf("read config file: %w", vErr)
}
} else {
watchConfig()
}
return nil
}
func loadConfigFromENV() {
viper.SetEnvPrefix("EETG")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
}
func watchConfig() {
viper.OnConfigChange(func(e fsnotify.Event) {
log.Info().
Str("entity", "Config Service").
Str("action", "watching config file").
Str("status", "config file changed").
Str("operation", e.Op.String()).
Str("path", e.Name).
Str("note", "restart server to take effect").
Send()
})
viper.WatchConfig()
}
func setupLogger() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
zerolog.DurationFieldUnit = time.Second
if viper.GetBool(apiQuietMode) {
log.Logger = zerolog.Nop()
} else {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
}