-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.go
More file actions
556 lines (469 loc) · 14.5 KB
/
module.go
File metadata and controls
556 lines (469 loc) · 14.5 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package caddystoragevalkey
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"os"
"strconv"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/certmagic"
"github.com/valkey-io/valkey-go"
)
const (
ID_MODULE_STATE = "caddy.storage.valkey"
)
type StorageValkeyModule struct {
Url string `json:"url,omitempty"`
InitAddress []string `json:"address,omitempty"`
ReplicaAddress []string `json:"replica,omitempty"`
SelectDb int `json:"db,omitempty"`
ShuffleInit bool `json:"shuffle_init,omitempty"`
SentinelMasterSet string `json:"sentinel_master_set,omitempty"`
LockMajority int `json:"lock_majority,omitempty"`
DisableClientCache bool `json:"disable_client_cache,omitempty"`
SendToReplicas string `json:"send_to_replicas,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
TlsInsecure bool `json:"tls_insecure,omitempty"`
TlsMinVersion string `json:"tls_min_version,omitempty"`
TlsCaCert string `json:"tls_ca_cert,omitempty"`
TlsClientCert string `json:"tls_client_cert,omitempty"`
TlsClientKey string `json:"tls_client_key,omitempty"`
storage *CaddyStorageValkey
}
func init() {
caddy.RegisterModule(StorageValkeyModule{})
}
func (StorageValkeyModule) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: ID_MODULE_STATE,
New: func() caddy.Module { return new(StorageValkeyModule) },
}
}
func (m *StorageValkeyModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
for nesting := d.Nesting(); d.NextBlock(nesting); {
configKey := d.Val()
var configVal []string
if d.NextArg() {
// configuration item with single parameter
configVal = append(configVal, d.Val())
} else {
// configuration item with nested parameter list
for nesting := d.Nesting(); d.NextBlock(nesting); {
configVal = append(configVal, d.Val())
}
}
// There are no valid configurations where configVal slice is empty
if len(configVal) == 0 {
return d.Errf("no value supplied for configuraton key '%s'", configKey)
}
switch configKey {
case "url":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `url`")
}
m.Url = configVal[0]
}
case "address":
m.InitAddress = configVal
case "replica":
m.ReplicaAddress = configVal
case "db":
{
selectDb, err := parseConfigValToInt(configVal)
if err != nil {
return d.WrapErr(err)
}
m.SelectDb = int(selectDb)
}
case "shuffle_init":
{
shuffleInit, err := parseConfigValToBool(configVal)
if err != nil {
return d.WrapErr(err)
}
m.ShuffleInit = shuffleInit
}
case "sentinel_master_set":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `sentinel_master_set`")
}
m.SentinelMasterSet = configVal[0]
}
case "lock_majority":
{
lockMajority, err := parseConfigValToInt(configVal)
if err != nil {
return d.WrapErr(err)
}
if lockMajority < 1 {
return d.Err("impossible value for `lock_majority` (value > 0 required)")
}
m.LockMajority = int(lockMajority)
}
case "disable_client_cache":
{
disableClientCache, err := parseConfigValToBool(configVal)
if err != nil {
return d.WrapErr(err)
}
m.DisableClientCache = disableClientCache
}
case "send_to_replicas":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `send_to_replica`")
}
m.SendToReplicas = configVal[0]
}
case "username":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `username`")
}
m.Username = configVal[0]
}
case "password":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `password`")
}
m.Password = configVal[0]
}
case "tls_insecure":
{
tlsInsecure, err := parseConfigValToBool(configVal)
if err != nil {
return d.WrapErr(err)
}
m.TlsInsecure = tlsInsecure
}
case "tls_min_version":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `tls_min_version`")
}
m.TlsMinVersion = configVal[0]
}
case "tls_ca_cert":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `tls_ca_cert`")
}
m.TlsCaCert = configVal[0]
}
case "tls_client_cert":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `tls_client_cert`")
}
m.TlsClientCert = configVal[0]
}
case "tls_client_key":
{
if len(configVal) > 1 {
return d.Err("expected only a single value for `tls_client_key`")
}
m.TlsClientKey = configVal[0]
}
default:
// Unknown key for this config
d.ArgErr()
}
}
}
return nil
}
func parseConfigValToInt(configVal []string) (int, error) {
if len(configVal) != 1 {
return 0, errors.New("can only accept single value as integer")
}
// NOTE: Because int is "at-least 32bits", we only parse 32bits
val, err := strconv.ParseInt(configVal[0], 10, 32)
if err != nil {
return 0, err
}
return int(val), nil
}
func parseConfigValToBool(configVal []string) (bool, error) {
if len(configVal) != 1 {
return false, errors.New("can only accept single value as bool")
}
val, err := strconv.ParseBool(configVal[0])
if err != nil {
return false, err
}
return val, nil
}
func isFilePath(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return !info.IsDir()
}
func checkPemStringOrFilepath(val string) (bool, error) {
if cert, _ := pem.Decode([]byte(val)); cert == nil {
if !isFilePath(val) {
return false, errors.New("value is no certificate or filepath")
}
}
return true, nil
}
func validatePemStringOrFilepathOption(val string) bool {
// Not setting the options is valid
if len(val) == 0 {
return true
}
// Check if it is a PEM string or filepath
ok, err := checkPemStringOrFilepath(val)
return ok && err == nil
}
func (m *StorageValkeyModule) Provision(ctx caddy.Context) error {
// Replace placeholders in relevant configuration options with their actual values
repl := caddy.NewReplacer()
m.Url = repl.ReplaceAll(m.Url, "")
m.Username = repl.ReplaceAll(m.Username, "")
m.Password = repl.ReplaceAll(m.Password, "")
m.TlsCaCert = repl.ReplaceAll(m.TlsCaCert, "")
m.TlsClientCert = repl.ReplaceAll(m.TlsClientCert, "")
m.TlsClientKey = repl.ReplaceAll(m.TlsClientKey, "")
for i := range m.InitAddress {
m.InitAddress[i] = repl.ReplaceAll(m.InitAddress[i], "")
}
for i := range m.ReplicaAddress {
m.ReplicaAddress[i] = repl.ReplaceAll(m.ReplicaAddress[i], "")
}
// Apply defaults where required
if m.LockMajority < 1 {
m.LockMajority = 2
}
// Create a new client options object based on the parsed config
var clientOptions *valkey.ClientOption
if m.Url != "" {
optionsFromUrl, err := valkey.ParseURL(m.Url)
if err != nil {
return err
}
clientOptions = &optionsFromUrl
} else {
clientOptions = &valkey.ClientOption{
InitAddress: m.InitAddress,
SelectDB: m.SelectDb,
}
}
// Check whether any TLS option has been set
isTlsConfigured := (m.TlsInsecure ||
len(m.TlsMinVersion) > 0 ||
len(m.TlsCaCert) > 0 ||
len(m.TlsClientCert) > 0 ||
len(m.TlsClientKey) > 0)
if isTlsConfigured {
// Initialize client TLS config if not present
// NOTE: It can be present when we parse the URL and it has the TLS mentioned
if clientOptions.TLSConfig == nil {
clientOptions.TLSConfig = &tls.Config{
InsecureSkipVerify: m.TlsInsecure,
}
} else {
clientOptions.TLSConfig.InsecureSkipVerify = m.TlsInsecure
}
// Set min version, or fallback to default
if len(m.TlsMinVersion) > 0 {
switch m.TlsMinVersion {
case "tlsv1.2":
clientOptions.TLSConfig.MinVersion = tls.VersionTLS12
case "tlsv1.3":
clientOptions.TLSConfig.MinVersion = tls.VersionTLS13
default:
return errors.New("invalid value for `tls_min_version`")
}
} else {
// Default is TLS v1.2
clientOptions.TLSConfig.MinVersion = tls.VersionTLS12
}
// Initialize CA Certificate if present
if len(m.TlsCaCert) > 0 {
caCertPool := x509.NewCertPool()
if certData, _ := pem.Decode([]byte(m.TlsCaCert)); certData != nil {
if cert, err := x509.ParseCertificate(certData.Bytes); err == nil {
caCertPool.AddCert(cert)
} else {
return errors.New("failed to add `tls_ca_cert` PEM string to certificate pool")
}
} else if isFilePath(m.TlsCaCert) {
cert, err := os.ReadFile(m.TlsCaCert)
if err != nil {
return err
}
if ok := caCertPool.AppendCertsFromPEM(cert); !ok {
return errors.New("failed to add `tls_ca_cert` file content to certificate pool")
}
} else {
return errors.New("failed to add `tls_ca_cert` is no PEM string or filepath")
}
clientOptions.TLSConfig.RootCAs = caCertPool
}
// Configure client certificate
if len(m.TlsClientCert) > 0 || len(m.TlsClientKey) > 0 {
// SMall sanity check
if len(m.TlsClientCert) > 0 && len(m.TlsClientKey) == 0 {
return errors.New("both client certificate and key need to be provided, key is missing")
} else if len(m.TlsClientCert) == 0 && len(m.TlsClientKey) > 0 {
return errors.New("both client certificate and key need to be provided, certificate is missing")
}
var certPem []byte
var keyPem []byte
// NOTE: The following two blocks have been copied in order to keep the verbose error messages
if certData, _ := pem.Decode([]byte(m.TlsClientCert)); certData != nil {
certPem = []byte(m.TlsClientCert)
} else if isFilePath(m.TlsClientCert) {
rawCert, err := os.ReadFile(m.TlsClientCert)
if err != nil {
return err
}
if certData, _ := pem.Decode(rawCert); certData != nil {
certPem = rawCert
} else {
return errors.New("invalid PEM in `tls_client_cert` file")
}
} else {
return errors.New("failed to add `tls_client_cert` is no PEM string or filepath")
}
if keyData, _ := pem.Decode([]byte(m.TlsClientKey)); keyData != nil {
keyPem = []byte(m.TlsClientKey)
} else if isFilePath(m.TlsClientKey) {
rawKey, err := os.ReadFile(m.TlsClientKey)
if err != nil {
return err
}
if keyData, _ := pem.Decode(rawKey); keyData != nil {
keyPem = rawKey
} else {
return errors.New("invalid PEM in `tls_client_key` file")
}
} else {
return errors.New("failed to add `tls_client_key` is no PEM string or filepath")
}
// Build certificate out of keypair
clientCertificate, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return err
}
// Given we have a client certificate, we require and verify everything for security purposes
clientOptions.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
clientOptions.TLSConfig.Certificates = []tls.Certificate{clientCertificate}
}
}
// Set username and password connection details
if len(m.Username) > 0 {
clientOptions.Username = m.Username
}
if len(m.Password) > 0 {
clientOptions.Password = m.Password
}
// Add replica addresses when entries present
if len(m.ReplicaAddress) > 0 {
clientOptions.Standalone.ReplicaAddress = m.ReplicaAddress
clientOptions.SendToReplicas = func(cmd valkey.Completed) bool {
return false
}
}
// Transfer Disable Client Cache option
clientOptions.DisableCache = m.DisableClientCache
// Set SendToReplicas readonly strategy if present
if m.SendToReplicas == "readonly" {
clientOptions.SendToReplicas = func(cmd valkey.Completed) bool {
return cmd.IsReadOnly()
}
}
// Create caddy valkey storage specific options
options := CaddyStorageValkeyOptions{
LockMajority: m.LockMajority,
}
// Provision a new storage instance
valkeyStorage, err := NewCaddyStorageValkey(*clientOptions, options)
if err != nil {
return err
}
m.storage = valkeyStorage
return nil
}
func (m *StorageValkeyModule) Validate() error {
// NOTE: The majority of checking will be done by creating a new valkey client.
// Verify no other client option is set when the URL has been set
isUrlSet := (m.Url != "")
if len(m.InitAddress) > 0 && isUrlSet {
return errors.New("setting the `address` and `url` option is not allowed")
}
if len(m.Username) > 0 && isUrlSet {
return errors.New("setting the `username` and `url` option is not allowed")
}
if len(m.Password) > 0 && isUrlSet {
return errors.New("setting the `password` and `url` option is not allowed")
}
// NOTE: I'm aware that setting the db option can be set to zero, but this is the default
// and doesn't change the behavior in any way. The workaround is not worth it.
if m.SelectDb != 0 && isUrlSet {
return errors.New("setting the `db` and `url` option is not allowed")
}
// Check for sensible value on lock majority
if m.LockMajority < 1 {
return errors.New("impossible value for `lock_majority` option (value > 0 required)")
}
// Check SendToReplicas for valid strategy
switch m.SendToReplicas {
case "", "none":
// This is the default option which equals to none/no command to replica
break
case "readonly":
// This option sends readonly commands to the replica
break
default:
return errors.New("invalid value for `send_to_replicas`")
}
// Verify TLS min version
switch m.TlsMinVersion {
case "", "tlsv1.2":
// This is the default option
break
case "tlsv1.3":
break
default:
return errors.New("invalid value for `tls_min_version`")
}
// Verify TLS options are PEM or filepaths
if !validatePemStringOrFilepathOption(m.TlsCaCert) {
return errors.New("given value is no PEM string or filepath for key `tls_ca_cert`")
}
if !validatePemStringOrFilepathOption(m.TlsClientCert) {
return errors.New("given value is no PEM string or filepath for key `tls_client_cert`")
}
if !validatePemStringOrFilepathOption(m.TlsClientKey) {
return errors.New("given value is no PEM string or filepath for key `tls_client_key`")
}
return nil
}
func (m StorageValkeyModule) Cleanup() error {
if m.storage != nil {
m.storage.Close()
}
return nil
}
func (m *StorageValkeyModule) CertMagicStorage() (certmagic.Storage, error) {
return m.storage, nil
}
// Interface guards
var (
_ caddy.Module = (*StorageValkeyModule)(nil)
_ caddy.Provisioner = (*StorageValkeyModule)(nil)
_ caddy.CleanerUpper = (*StorageValkeyModule)(nil)
_ caddy.Validator = (*StorageValkeyModule)(nil)
_ caddyfile.Unmarshaler = (*StorageValkeyModule)(nil)
_ caddy.StorageConverter = (*StorageValkeyModule)(nil)
)