-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
274 lines (234 loc) · 7.92 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
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/sirupsen/logrus"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/providers/posflag"
"github.com/spf13/pflag"
)
const defaultPrefix = "NUTS_"
const defaultDelimiter = "."
const configFileFlag = "configfile"
const defaultConfigFile = "server.config.yaml"
const defaultHTTPPort = 1304
const defaultNutsNodeAddress = "http://localhost:8081"
const defaultCustomerFile = "customers.json"
const defaultLogLevel = "info"
// defaultHAPIFHIRServer configures usage of the HAPI FHIR Server (https://hapifhir.io/)
var defaultHAPIFHIRServer = FHIRServer{
Address: "http://localhost:8080/fhir",
Type: "hapi",
}
func defaultConfig() Config {
return Config{
HTTPPort: defaultHTTPPort,
NutsNodeAddress: defaultNutsNodeAddress,
Verbosity: defaultLogLevel,
FHIR: FHIR{
Server: defaultHAPIFHIRServer,
},
CustomersFile: defaultCustomerFile,
Credentials: Credentials{Password: "demo"},
DBConnectionString: "demo-ehr.db?cache=shared",
LoadTestPatients: false,
NutsNodeKeyPath: "",
}
}
type Config struct {
Credentials Credentials `koanf:"credentials"`
TLS TLSConfig `koanf:"tls"`
Verbosity string `koanf:"verbosity"`
HTTPPort int `koanf:"port"`
NutsNodeAddress string `koanf:"nutsnodeaddr"`
NutsPIPAddress string `koanf:"nutspipaddr"`
FHIR FHIR `koanf:"fhir"`
SharedCarePlanning SharedCarePlanning `koanf:"sharedcareplanning"`
CustomersFile string `koanf:"customersfile"`
Branding Branding `koanf:"branding"`
// Database connection string, accepts all options for the sqlite3 driver
// https://github.com/mattn/go-sqlite3#connection-string
DBConnectionString string `koanf:"dbConnectionString"`
// Load a set of test patients on startup. Should be disabled for permanent data stores.
LoadTestPatients bool `koanf:"loadTestPatients"`
// If set, this key wil be used to sign JWTs. If not set, a new one is generated on each start up.
// Developer tip: set the sessionPemKey so the session keeps valid after a server reboot.
SessionPemKey string `koanf:"sessionPemKey"`
sessionKey *ecdsa.PrivateKey
// NutsNodeKeyPath sets the path for the private key file used to sign JWTs and enable
// access to a protected nuts node endpoint. This value is ignored when set empty.
NutsNodeKeyPath string `koanf:"nutsnodekeypath"`
// NutsNodeAPIAudience sets the 'aud' in the token generation, must match with Nuts node settings.
NutsNodeAPIAudience string `koanf:"nutsnodeapiaudience"`
}
type SharedCarePlanning struct {
CarePlanService CarePlanService `koanf:"careplanservice"`
}
func (p SharedCarePlanning) Enabled() bool {
return p.CarePlanService.FHIRBaseURL != ""
}
type CarePlanService struct {
FHIRBaseURL string `koanf:"url"`
}
type FHIR struct {
Server FHIRServer `koanf:"server"`
}
type FHIRServer struct {
Type string `koanf:"type"`
Address string `koanf:"address"`
}
func (server FHIRServer) SupportsMultiTenancy() bool {
return server.Type == "hapi-multi-tenant"
}
type Credentials struct {
Password string `koanf:"password" json:"-"` // json omit tag to avoid having it printed in server log
}
type TLSConfig struct {
Client TLSClientConfig `koanf:"client"`
}
type TLSClientConfig struct {
CertificateFile string `koanf:"certificate"`
KeyFile string `koanf:"key"`
}
func (c TLSClientConfig) IsConfigured() bool {
return len(c.CertificateFile) > 0 && len(c.KeyFile) > 0
}
func (c TLSClientConfig) Load() (*tls.Config, error) {
clientCertificate, err := tls.LoadX509KeyPair(c.CertificateFile, c.KeyFile)
if err != nil {
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{clientCertificate},
// If you copy this code, do NOT copy the line below, because it effectively disables checking the
// trustworthiness of the server certificate. But it allows Demo EHR to have less config.
InsecureSkipVerify: true,
}, err
}
type Branding struct {
// Logo defines a path that points to a file on disk to be used as logo, to be displayed in the application.
Logo string `koanf:"logo"`
}
func (c Credentials) Empty() bool {
return len(c.Password) == 0
}
func generateSessionKey() (*ecdsa.PrivateKey, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
logrus.Printf("failed to generate private key: %s", err)
return nil, err
}
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, err
}
block := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}
if err := pem.Encode(log.Writer(), &block); err != nil {
return nil, err
}
return key, nil
}
func (c Config) Print(writer io.Writer) error {
if _, err := fmt.Fprintln(writer, "========== CONFIG: =========="); err != nil {
return err
}
var pr Config = c
if pr.SessionPemKey != "" {
// Don't print the private key.
pr.SessionPemKey = "Redacted"
}
data, _ := json.MarshalIndent(pr, "", " ")
if _, err := fmt.Println(writer, string(data)); err != nil {
return err
}
if _, err := fmt.Fprintln(writer, "========= END CONFIG ========="); err != nil {
return err
}
return nil
}
func loadConfig() Config {
flagset := loadFlagSet(os.Args[1:])
var k = koanf.New(".")
// Prepare koanf for parsing the config file
configFilePath := resolveConfigFile(flagset)
// Check if the file exists
if _, err := os.Stat(configFilePath); err == nil {
logrus.Infof("Loading config from file: %s", configFilePath)
if err := k.Load(file.Provider(configFilePath), yaml.Parser()); err != nil {
logrus.Fatalf("error while loading config from file: %v", err)
}
} else {
logrus.Infof("Using default config because no file was found at: %s", configFilePath)
}
// load env flags, can't return error
_ = k.Load(envProvider(), nil)
config := defaultConfig()
// Unmarshal values of the config file into the config struct, potentially replacing default values
if err := k.Unmarshal("", &config); err != nil {
log.Fatalf("error while unmarshalling config: %v", err)
}
if len(config.SessionPemKey) > 0 {
log.Print("sessionPemKey set, trying to parse it...")
block, _ := pem.Decode([]byte(config.SessionPemKey))
if block == nil || block.Type != "EC PRIVATE KEY" {
log.Fatalf("unable to parse sessionPemKey as PEM")
}
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
log.Fatalf("unable to parse sessionPemKey as EC Private key: %v", err)
}
config.sessionKey = key
} else {
sessionKey, err := generateSessionKey()
if err != nil {
log.Fatalf("unable to generate session key: %v", err)
}
config.sessionKey = sessionKey
}
return config
}
func loadFlagSet(args []string) *pflag.FlagSet {
f := pflag.NewFlagSet("config", pflag.ContinueOnError)
f.String(configFileFlag, defaultConfigFile, "Nuts config file")
f.Usage = func() {
fmt.Println(f.FlagUsages())
os.Exit(0)
}
err := f.Parse(args)
if err != nil {
panic(err)
}
return f
}
// resolveConfigFile resolves the path of the config file using the following sources:
// 1. commandline params (using the given flags)
// 2. environment vars,
// 3. default location.
func resolveConfigFile(flagset *pflag.FlagSet) string {
k := koanf.New(defaultDelimiter)
// load env flags, can't return error
_ = k.Load(envProvider(), nil)
// load cmd flags, without a parser, no error can be returned
_ = k.Load(posflag.Provider(flagset, defaultDelimiter, k), nil)
configFile := k.String(configFileFlag)
return configFile
}
func envProvider() *env.Env {
return env.Provider(defaultPrefix, defaultDelimiter, func(s string) string {
return strings.Replace(strings.ToLower(
strings.TrimPrefix(s, defaultPrefix)), "_", defaultDelimiter, -1)
})
}