Debian Codegraph @

config/configtls/configtls_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package configtls
5
6 import (
7 "context"
8 "crypto/tls"
9 "crypto/x509"
10 "errors"
11 "fmt"
12 "io"
13 "os"
14 "path/filepath"
15 "strings"
16 "testing"
17 "time"
18
19 "github.com/stretchr/testify/assert"
20 "github.com/stretchr/testify/require"
21
22 "go.opentelemetry.io/collector/config/configopaque"
23 "go.opentelemetry.io/collector/confmap/xconfmap"
24 )
25
26 func TestNewDefaultConfig(t *testing.T) {
27 expectedConfig := Config{}
28 config := NewDefaultConfig()
29 require.Equal(t, expectedConfig, config)
30 }
31
32 func TestNewDefaultClientConfig(t *testing.T) {
33 expectedConfig := ClientConfig{
34 Config: NewDefaultConfig(),
35 }
36 config := NewDefaultClientConfig()
37 require.Equal(t, expectedConfig, config)
38 }
39
40 func TestNewDefaultServerConfig(t *testing.T) {
41 expectedConfig := ServerConfig{
42 Config: NewDefaultConfig(),
43 }
44 config := NewDefaultServerConfig()
45 require.Equal(t, expectedConfig, config)
46 }
47
48 func TestOptionsToConfig(t *testing.T) {
49 tests := []struct {
50 name string
51 options Config
52 expectError string
53 }{
54 {
55 name: "should load system CA",
56 options: Config{CAFile: ""},
57 },
58 {
59 name: "should load custom CA",
60 options: Config{CAFile: filepath.Join("testdata", "ca-1.crt")},
61 },
62 {
63 name: "should load system CA and custom CA",
64 options: Config{IncludeSystemCACertsPool: true, CAFile: filepath.Join("testdata", "ca-1.crt")},
65 },
66 {
67 name: "should fail with invalid CA file path",
68 options: Config{CAFile: filepath.Join("testdata", "not/valid")},
69 expectError: "failed to load CA",
70 },
71 {
72 name: "should fail with invalid CA file content",
73 options: Config{CAFile: filepath.Join("testdata", "testCA-bad.txt")},
74 expectError: "failed to parse cert",
75 },
76 {
77 name: "should load valid TLS settings",
78 options: Config{
79 CAFile: filepath.Join("testdata", "ca-1.crt"),
80 CertFile: filepath.Join("testdata", "server-1.crt"),
81 KeyFile: filepath.Join("testdata", "server-1.key"),
82 },
83 },
84 {
85 name: "should fail with missing TLS KeyFile",
86 options: Config{
87 CAFile: filepath.Join("testdata", "ca-1.crt"),
88 CertFile: filepath.Join("testdata", "server-1.crt"),
89 },
90 expectError: "provide both certificate and key, or neither",
91 },
92 {
93 name: "should fail with invalid TLS KeyFile",
94 options: Config{
95 CAFile: filepath.Join("testdata", "ca-1.crt"),
96 CertFile: filepath.Join("testdata", "server-1.crt"),
97 KeyFile: filepath.Join("testdata", "not/valid"),
98 },
99 expectError: "failed to load TLS cert and key",
100 },
101 {
102 name: "should fail with missing TLS Cert",
103 options: Config{
104 CAFile: filepath.Join("testdata", "ca-1.crt"),
105 KeyFile: filepath.Join("testdata", "server-1.key"),
106 },
107 expectError: "provide both certificate and key, or neither",
108 },
109 {
110 name: "should fail with invalid TLS Cert",
111 options: Config{
112 CAFile: filepath.Join("testdata", "ca-1.crt"),
113 CertFile: filepath.Join("testdata", "not/valid"),
114 KeyFile: filepath.Join("testdata", "server-1.key"),
115 },
116 expectError: "failed to load TLS cert and key",
117 },
118 {
119 name: "should fail with invalid TLS CA",
120 options: Config{
121 CAFile: filepath.Join("testdata", "not/valid"),
122 },
123 expectError: "failed to load CA",
124 },
125 {
126 name: "should fail with invalid CA pool",
127 options: Config{
128 CAFile: filepath.Join("testdata", "testCA-bad.txt"),
129 },
130 expectError: "failed to parse cert",
131 },
132 {
133 name: "should pass with valid CA pool",
134 options: Config{
135 CAFile: filepath.Join("testdata", "ca-1.crt"),
136 },
137 },
138 {
139 name: "should pass with valid min and max version",
140 options: Config{
141 MinVersion: "1.1",
142 MaxVersion: "1.2",
143 },
144 },
145 {
146 name: "should pass with invalid min",
147 options: Config{
148 MinVersion: "1.7",
149 },
150 expectError: "invalid TLS min_",
151 },
152 {
153 name: "should pass with invalid max",
154 options: Config{
155 MaxVersion: "1.7",
156 },
157 expectError: "invalid TLS max_",
158 },
159 {
160 name: "should load custom CA PEM",
161 options: Config{CAPem: readFilePanics("testdata/ca-1.crt")},
162 },
163 {
164 name: "should load valid TLS settings with PEMs",
165 options: Config{
166 CAPem: readFilePanics("testdata/ca-1.crt"),
167 CertPem: readFilePanics("testdata/server-1.crt"),
168 KeyPem: readFilePanics("testdata/server-1.key"),
169 },
170 },
171 {
172 name: "mix Cert file and Key PEM provided",
173 options: Config{
174 CertFile: "testdata/server-1.crt",
175 KeyPem: readFilePanics("testdata/server-1.key"),
176 },
177 },
178 {
179 name: "mix Cert PEM and Key File provided",
180 options: Config{
181 CertPem: readFilePanics("testdata/server-1.crt"),
182 KeyFile: "testdata/server-1.key",
183 },
184 },
185 {
186 name: "should fail with invalid CA PEM",
187 options: Config{CAPem: readFilePanics("testdata/testCA-bad.txt")},
188 expectError: "failed to parse cert",
189 },
190 {
191 name: "should fail CA file and PEM both provided",
192 options: Config{
193 CAFile: "testdata/ca-1.crt",
194 CAPem: readFilePanics("testdata/ca-1.crt"),
195 },
196 expectError: "provide either a CA file or the PEM-encoded string, but not both",
197 },
198 {
199 name: "should fail Cert file and PEM both provided",
200 options: Config{
201 CertFile: "testdata/server-1.crt",
202 CertPem: readFilePanics("testdata/server-1.crt"),
203 KeyFile: "testdata/server-1.key",
204 },
205 expectError: "provide either a certificate or the PEM-encoded string, but not both",
206 },
207 {
208 name: "should fail Key file and PEM both provided",
209 options: Config{
210 CertFile: "testdata/server-1.crt",
211 KeyFile: "testdata/ca-1.crt",
212 KeyPem: readFilePanics("testdata/server-1.key"),
213 },
214 expectError: "provide either a key or the PEM-encoded string, but not both",
215 },
216 {
217 name: "should fail to load valid TLS settings with bad Cert PEM",
218 options: Config{
219 CAPem: readFilePanics("testdata/ca-1.crt"),
220 CertPem: readFilePanics("testdata/testCA-bad.txt"),
221 KeyPem: readFilePanics("testdata/server-1.key"),
222 },
223 expectError: "failed to load TLS cert and key PEMs",
224 },
225 {
226 name: "should fail to load valid TLS settings with bad Key PEM",
227 options: Config{
228 CAPem: readFilePanics("testdata/ca-1.crt"),
229 CertPem: readFilePanics("testdata/server-1.crt"),
230 KeyPem: readFilePanics("testdata/testCA-bad.txt"),
231 },
232 expectError: "failed to load TLS cert and key PEMs",
233 },
234 {
235 name: "should fail with missing TLS KeyPem",
236 options: Config{
237 CAPem: readFilePanics("testdata/ca-1.crt"),
238 CertPem: readFilePanics("testdata/server-1.crt"),
239 },
240 expectError: "provide both certificate and key, or neither",
241 },
242 {
243 name: "should fail with missing TLS Cert PEM",
244 options: Config{
245 CAPem: readFilePanics("testdata/ca-1.crt"),
246 KeyPem: readFilePanics("testdata/server-1.key"),
247 },
248 expectError: "provide both certificate and key, or neither",
249 },
250 }
251
252 for _, test := range tests {
253 t.Run(test.name, func(t *testing.T) {
254 cfg, err := test.options.loadTLSConfig()
255 if test.expectError != "" {
256 assert.ErrorContains(t, err, test.expectError)
257 } else {
258 require.NoError(t, err)
259 assert.NotNil(t, cfg)
260 }
261 })
262 }
263 }
264
265 func readFilePanics(filePath string) configopaque.String {
266 fileContents, err := os.ReadFile(filepath.Clean(filePath))
267 if err != nil {
268 panic(fmt.Sprintf("failed to read file %s: %v", filePath, err))
269 }
270
271 return configopaque.String(fileContents)
272 }
273
274 func TestLoadTLSClientConfigError(t *testing.T) {
275 tlsSetting := ClientConfig{
276 Config: Config{
277 CertFile: "doesnt/exist",
278 KeyFile: "doesnt/exist",
279 },
280 }
281 _, err := tlsSetting.LoadTLSConfig(context.Background())
282 assert.Error(t, err)
283 }
284
285 func TestLoadTLSClientConfig(t *testing.T) {
286 tlsSetting := ClientConfig{
287 Insecure: true,
288 }
289 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
290 require.NoError(t, err)
291 assert.Nil(t, tlsCfg)
292
293 tlsSetting = ClientConfig{}
294 tlsCfg, err = tlsSetting.LoadTLSConfig(context.Background())
295 require.NoError(t, err)
296 assert.NotNil(t, tlsCfg)
297
298 tlsSetting = ClientConfig{
299 InsecureSkipVerify: true,
300 }
301 tlsCfg, err = tlsSetting.LoadTLSConfig(context.Background())
302 require.NoError(t, err)
303 assert.NotNil(t, tlsCfg)
304 assert.True(t, tlsCfg.InsecureSkipVerify)
305 }
306
307 func TestLoadTLSServerConfigError(t *testing.T) {
308 tlsSetting := ServerConfig{
309 Config: Config{
310 CertFile: "doesnt/exist",
311 KeyFile: "doesnt/exist",
312 },
313 }
314 _, err := tlsSetting.LoadTLSConfig(context.Background())
315 require.Error(t, err)
316
317 tlsSetting = ServerConfig{
318 ClientCAFile: "doesnt/exist",
319 }
320 _, err = tlsSetting.LoadTLSConfig(context.Background())
321 assert.Error(t, err)
322 }
323
324 func TestLoadTLSServerConfig(t *testing.T) {
325 tlsSetting := ServerConfig{}
326 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
327 require.NoError(t, err)
328 assert.NotNil(t, tlsCfg)
329 }
330
331 func TestLoadTLSServerConfigReload(t *testing.T) {
332 tmpCaPath := createTempClientCaFile(t)
333
334 overwriteClientCA(t, tmpCaPath, "ca-1.crt")
335
336 tlsSetting := ServerConfig{
337 ClientCAFile: tmpCaPath,
338 ReloadClientCAFile: true,
339 }
340
341 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
342 require.NoError(t, err)
343 assert.NotNil(t, tlsCfg)
344
345 firstClient, err := tlsCfg.GetConfigForClient(nil)
346 require.NoError(t, err)
347
348 overwriteClientCA(t, tmpCaPath, "ca-2.crt")
349
350 assert.EventuallyWithT(t, func(t *assert.CollectT) {
351 secondClient, err := tlsCfg.GetConfigForClient(nil)
352 require.NoError(t, err)
353 assert.NotEqual(t, firstClient.ClientCAs, secondClient.ClientCAs)
354 }, 5*time.Second, 10*time.Millisecond)
355 }
356
357 func TestLoadTLSServerConfigFailingReload(t *testing.T) {
358 tmpCaPath := createTempClientCaFile(t)
359
360 overwriteClientCA(t, tmpCaPath, "ca-1.crt")
361
362 tlsSetting := ServerConfig{
363 ClientCAFile: tmpCaPath,
364 ReloadClientCAFile: true,
365 }
366
367 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
368 require.NoError(t, err)
369 assert.NotNil(t, tlsCfg)
370
371 firstClient, err := tlsCfg.GetConfigForClient(nil)
372 require.NoError(t, err)
373
374 overwriteClientCA(t, tmpCaPath, "testCA-bad.txt")
375
376 assert.Eventually(t, func() bool {
377 _, loadError := tlsCfg.GetConfigForClient(nil)
378 return loadError == nil
379 }, 5*time.Second, 10*time.Millisecond)
380
381 secondClient, err := tlsCfg.GetConfigForClient(nil)
382 require.NoError(t, err)
383
384 assert.Equal(t, firstClient.ClientCAs, secondClient.ClientCAs)
385 }
386
387 func TestLoadTLSServerConfigFailingInitialLoad(t *testing.T) {
388 tmpCaPath := createTempClientCaFile(t)
389
390 overwriteClientCA(t, tmpCaPath, "testCA-bad.txt")
391
392 tlsSetting := ServerConfig{
393 ClientCAFile: tmpCaPath,
394 ReloadClientCAFile: true,
395 }
396
397 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
398 require.Error(t, err)
399 assert.Nil(t, tlsCfg)
400 }
401
402 func TestLoadTLSServerConfigWrongPath(t *testing.T) {
403 tmpCaPath := createTempClientCaFile(t)
404
405 tlsSetting := ServerConfig{
406 ClientCAFile: tmpCaPath + "wrong-path",
407 ReloadClientCAFile: true,
408 }
409
410 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
411 require.Error(t, err)
412 assert.Nil(t, tlsCfg)
413 }
414
415 func TestLoadTLSServerConfigFailing(t *testing.T) {
416 tmpCaPath := createTempClientCaFile(t)
417
418 overwriteClientCA(t, tmpCaPath, "ca-1.crt")
419
420 tlsSetting := ServerConfig{
421 ClientCAFile: tmpCaPath,
422 ReloadClientCAFile: true,
423 }
424
425 tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())
426 require.NoError(t, err)
427 assert.NotNil(t, tlsCfg)
428
429 firstClient, err := tlsCfg.GetConfigForClient(nil)
430 require.NoError(t, err)
431 assert.NotNil(t, firstClient)
432
433 err = os.Remove(tmpCaPath)
434 require.NoError(t, err)
435
436 firstClient, err = tlsCfg.GetConfigForClient(nil)
437 require.NoError(t, err)
438 assert.NotNil(t, firstClient)
439 }
440
441 func overwriteClientCA(t *testing.T, targetFilePath, testdataFileName string) {
442 targetFile, err := os.OpenFile(filepath.Clean(targetFilePath), os.O_RDWR, 0o600)
443 require.NoError(t, err)
444
445 testdataFilePath := filepath.Join("testdata", testdataFileName)
446 testdataFile, err := os.OpenFile(filepath.Clean(testdataFilePath), os.O_RDONLY, 0o200)
447 require.NoError(t, err)
448
449 _, err = io.Copy(targetFile, testdataFile)
450 assert.NoError(t, err)
451
452 assert.NoError(t, targetFile.Close())
453 assert.NoError(t, testdataFile.Close())
454 }
455
456 func createTempClientCaFile(t *testing.T) string {
457 tmpCa, err := os.CreateTemp(t.TempDir(), "ca-tmp.crt")
458 require.NoError(t, err)
459 tmpCaPath, err := filepath.Abs(tmpCa.Name())
460 assert.NoError(t, err)
461 assert.NoError(t, tmpCa.Close())
462 return tmpCaPath
463 }
464
465 func TestEagerlyLoadCertificate(t *testing.T) {
466 options := Config{
467 CertFile: filepath.Join("testdata", "client-1.crt"),
468 KeyFile: filepath.Join("testdata", "client-1.key"),
469 }
470 cfg, err := options.loadTLSConfig()
471 require.NoError(t, err)
472 assert.NotNil(t, cfg)
473 cert, err := cfg.GetCertificate(&tls.ClientHelloInfo{})
474 require.NoError(t, err)
475 assert.NotNil(t, cert)
476 pCert, err := x509.ParseCertificate(cert.Certificate[0])
477 require.NoError(t, err)
478 assert.NotNil(t, pCert)
479 assert.ElementsMatch(t, []string{"example1"}, pCert.DNSNames)
480 }
481
482 func TestCertificateReload(t *testing.T) {
483 tests := []struct {
484 name string
485 reloadInterval time.Duration
486 wait time.Duration
487 cert2 string
488 key2 string
489 dns1 string
490 dns2 string
491 errText string
492 }{
493 {
494 name: "Should reload the certificate after reload-interval",
495 reloadInterval: 100 * time.Microsecond,
496 wait: 100 * time.Microsecond,
497 cert2: "client-2.crt",
498 key2: "client-2.key",
499 dns1: "example1",
500 dns2: "example2",
501 },
502 {
503 name: "Should return same cert if called before reload-interval",
504 reloadInterval: 100 * time.Millisecond,
505 wait: 100 * time.Microsecond,
506 cert2: "client-2.crt",
507 key2: "client-2.key",
508 dns1: "example1",
509 dns2: "example1",
510 },
511 {
512 name: "Should always return same cert if reload-interval is 0",
513 reloadInterval: 0,
514 wait: 100 * time.Microsecond,
515 cert2: "client-2.crt",
516 key2: "client-2.key",
517 dns1: "example1",
518 dns2: "example1",
519 },
520 {
521 name: "Should return an error if reloading fails",
522 reloadInterval: 100 * time.Microsecond,
523 wait: 100 * time.Microsecond,
524 cert2: "testCA-bad.txt",
525 key2: "client-2.key",
526 dns1: "example1",
527 errText: "failed to load TLS cert and key: failed to load TLS cert and key PEMs: tls: failed to find any PEM data in certificate input",
528 },
529 }
530
531 for _, test := range tests {
532 t.Run(test.name, func(t *testing.T) {
533 // Copy certs into a temp dir so we can safely modify them
534 tempDir := t.TempDir()
535 certFile, err := os.CreateTemp(tempDir, "cert")
536 require.NoError(t, err)
537 defer certFile.Close()
538
539 keyFile, err := os.CreateTemp(tempDir, "key")
540 require.NoError(t, err)
541 defer keyFile.Close()
542
543 fdc, err := os.Open(filepath.Join("testdata", "client-1.crt"))
544 require.NoError(t, err)
545 _, err = io.Copy(certFile, fdc)
546 require.NoError(t, err)
547 require.NoError(t, fdc.Close())
548
549 fdk, err := os.Open(filepath.Join("testdata", "client-1.key"))
550 require.NoError(t, err)
551 _, err = io.Copy(keyFile, fdk)
552 assert.NoError(t, err)
553 assert.NoError(t, fdk.Close())
554
555 options := Config{
556 CertFile: certFile.Name(),
557 KeyFile: keyFile.Name(),
558 ReloadInterval: test.reloadInterval,
559 }
560 cfg, err := options.loadTLSConfig()
561 require.NoError(t, err)
562 assert.NotNil(t, cfg)
563
564 // Assert that we loaded the original certificate
565 cert, err := cfg.GetCertificate(&tls.ClientHelloInfo{})
566 require.NoError(t, err)
567 assert.NotNil(t, cert)
568 pCert, err := x509.ParseCertificate(cert.Certificate[0])
569 require.NoError(t, err)
570 assert.NotNil(t, pCert)
571 assert.Equal(t, test.dns1, pCert.DNSNames[0])
572
573 // Change the certificate
574 assert.NoError(t, certFile.Truncate(0))
575 assert.NoError(t, keyFile.Truncate(0))
576 _, err = certFile.Seek(0, 0)
577 require.NoError(t, err)
578 _, err = keyFile.Seek(0, 0)
579 require.NoError(t, err)
580
581 fdc2, err := os.Open(filepath.Join("testdata", test.cert2))
582 require.NoError(t, err)
583 _, err = io.Copy(certFile, fdc2)
584 assert.NoError(t, err)
585 assert.NoError(t, fdc2.Close())
586
587 fdk2, err := os.Open(filepath.Join("testdata", test.key2))
588 require.NoError(t, err)
589 _, err = io.Copy(keyFile, fdk2)
590 assert.NoError(t, err)
591 assert.NoError(t, fdk2.Close())
592
593 // Wait ReloadInterval to ensure a reload will happen
594 time.Sleep(test.wait)
595
596 // Assert that we loaded the new certificate
597 cert, err = cfg.GetCertificate(&tls.ClientHelloInfo{})
598 if test.errText == "" {
599 require.NoError(t, err)
600 assert.NotNil(t, cert)
601 pCert, err = x509.ParseCertificate(cert.Certificate[0])
602 require.NoError(t, err)
603 assert.NotNil(t, pCert)
604 assert.Equal(t, test.dns2, pCert.DNSNames[0])
605 } else {
606 assert.EqualError(t, err, test.errText)
607 }
608 })
609 }
610 }
611
612 func TestMinMaxTLSVersions(t *testing.T) {
613 tests := []struct {
614 name string
615 minVersion string
616 maxVersion string
617 outMinVersion uint16
618 outMaxVersion uint16
619 errorTxt string
620 }{
621 {name: `TLS Config ["", ""] to give [TLS1.2, 0]`, minVersion: "", maxVersion: "", outMinVersion: tls.VersionTLS12, outMaxVersion: 0},
622 {name: `TLS Config ["", "1.3"] to give [TLS1.2, TLS1.3]`, minVersion: "", maxVersion: "1.3", outMinVersion: tls.VersionTLS12, outMaxVersion: tls.VersionTLS13},
623 {name: `TLS Config ["1.2", ""] to give [TLS1.2, 0]`, minVersion: "1.2", maxVersion: "", outMinVersion: tls.VersionTLS12, outMaxVersion: 0},
624 {name: `TLS Config ["1.3", "1.3"] to give [TLS1.3, TLS1.3]`, minVersion: "1.3", maxVersion: "1.3", outMinVersion: tls.VersionTLS13, outMaxVersion: tls.VersionTLS13},
625 {name: `TLS Config ["1.0", "1.1"] to give [TLS1.0, TLS1.1]`, minVersion: "1.0", maxVersion: "1.1", outMinVersion: tls.VersionTLS10, outMaxVersion: tls.VersionTLS11},
626 {name: `TLS Config ["asd", ""] to give [Error]`, minVersion: "asd", maxVersion: "", errorTxt: `invalid TLS min_version: unsupported TLS version: "asd"`},
627 {name: `TLS Config ["", "asd"] to give [Error]`, minVersion: "", maxVersion: "asd", errorTxt: `invalid TLS max_version: unsupported TLS version: "asd"`},
628 {name: `TLS Config ["0.4", ""] to give [Error]`, minVersion: "0.4", maxVersion: "", errorTxt: `invalid TLS min_version: unsupported TLS version: "0.4"`},
629
630 // Allowing this, however, expecting downstream TLS handshake will throw an error
631 {name: `TLS Config ["1.2", "1.1"] to give [TLS1.2, TLS1.1]`, minVersion: "1.2", maxVersion: "1.1", outMinVersion: tls.VersionTLS12, outMaxVersion: tls.VersionTLS11},
632 }
633
634 for _, test := range tests {
635 t.Run(test.name, func(t *testing.T) {
636 setting := Config{
637 MinVersion: test.minVersion,
638 MaxVersion: test.maxVersion,
639 }
640
641 config, err := setting.loadTLSConfig()
642
643 if test.errorTxt == "" {
644 assert.Equal(t, config.MinVersion, test.outMinVersion)
645 assert.Equal(t, config.MaxVersion, test.outMaxVersion)
646 } else {
647 assert.EqualError(t, err, test.errorTxt)
648 }
649 })
650 }
651 }
652
653 func TestConfigValidate(t *testing.T) {
654 tests := []struct {
655 name string
656 tlsConfig Config
657 errorTxt string
658 }{
659 {name: `TLS Config ["", ""] to be valid`, tlsConfig: Config{MinVersion: "", MaxVersion: ""}},
660 {name: `TLS Config ["", "1.3"] to be valid`, tlsConfig: Config{MinVersion: "", MaxVersion: "1.3"}},
661 {name: `TLS Config ["1.2", ""] to be valid`, tlsConfig: Config{MinVersion: "1.2", MaxVersion: ""}},
662 {name: `TLS Config ["1.3", "1.3"] to be valid`, tlsConfig: Config{MinVersion: "1.3", MaxVersion: "1.3"}},
663 {name: `TLS Config ["1.0", "1.1"] to be valid`, tlsConfig: Config{MinVersion: "1.0", MaxVersion: "1.1"}},
664 {name: `TLS Config ["asd", ""] to give [Error]`, tlsConfig: Config{MinVersion: "asd", MaxVersion: ""}, errorTxt: `invalid TLS min_version: unsupported TLS version: "asd"`},
665 {name: `TLS Config ["", "asd"] to give [Error]`, tlsConfig: Config{MinVersion: "", MaxVersion: "asd"}, errorTxt: `invalid TLS max_version: unsupported TLS version: "asd"`},
666 {name: `TLS Config ["0.4", ""] to give [Error]`, tlsConfig: Config{MinVersion: "0.4", MaxVersion: ""}, errorTxt: `invalid TLS min_version: unsupported TLS version: "0.4"`},
667 {name: `TLS Config ["1.2", "1.1"] to give [Error]`, tlsConfig: Config{MinVersion: "1.2", MaxVersion: "1.1"}, errorTxt: `invalid TLS configuration: min_version cannot be greater than max_version`},
668 {name: `TLS Config with both CA File and PEM`, tlsConfig: Config{CAFile: "test", CAPem: "test"}, errorTxt: `provide either a CA file or the PEM-encoded string, but not both`},
669 {name: `TLS Config with cert file but no key`, tlsConfig: Config{CertFile: "cert.pem"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},
670 {name: `TLS Config with key file but no cert`, tlsConfig: Config{KeyFile: "key.pem"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},
671 {name: `TLS Config with cert PEM but no key`, tlsConfig: Config{CertPem: "cert-pem"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},
672 {name: `TLS Config with key PEM but no cert`, tlsConfig: Config{KeyPem: "key-pem"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},
673 {name: `TLS Config with both cert file and cert PEM`, tlsConfig: Config{CertFile: "cert.pem", CertPem: "cert-pem", KeyFile: "key.pem"}, errorTxt: `provide either certificate file or PEM, but not both`},
674 {name: `TLS Config with both key file and key PEM`, tlsConfig: Config{CertFile: "cert.pem", KeyFile: "key.pem", KeyPem: "key-pem"}, errorTxt: `provide either key file or PEM, but not both`},
675 {name: `TLS Config with cert file and key PEM`, tlsConfig: Config{CertFile: "cert.pem", KeyPem: "key-pem"}},
676 {name: `TLS Config with cert PEM and key file`, tlsConfig: Config{CertPem: "cert-pem", KeyFile: "key.pem"}},
677 {name: `TLS Config with valid cert and key files`, tlsConfig: Config{CertFile: "cert.pem", KeyFile: "key.pem"}},
678 {name: `TLS Config with valid cert and key PEM`, tlsConfig: Config{CertPem: "cert-pem", KeyPem: "key-pem"}},
679 }
680
681 for _, test := range tests {
682 t.Run(test.name, func(t *testing.T) {
683 err := test.tlsConfig.Validate()
684
685 if test.errorTxt == "" {
686 assert.NoError(t, err)
687 } else {
688 assert.EqualError(t, err, test.errorTxt)
689 }
690 })
691 }
692 }
693
694 func TestCipherSuites(t *testing.T) {
695 tests := []struct {
696 name string
697 tlsSetting Config
698 wantErr string
699 result []uint16
700 }{
701 {
702 name: "no suites set",
703 tlsSetting: Config{},
704 result: nil,
705 },
706 {
707 name: "one cipher suite set",
708 tlsSetting: Config{
709 CipherSuites: []string{"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"},
710 },
711 result: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
712 },
713 {
714 name: "invalid cipher suite set",
715 tlsSetting: Config{
716 CipherSuites: []string{"FOO"},
717 },
718 wantErr: `invalid TLS cipher suite: "FOO"`,
719 },
720 {
721 name: "multiple invalid cipher suites set",
722 tlsSetting: Config{
723 CipherSuites: []string{"FOO", "BAR"},
724 },
725 wantErr: `invalid TLS cipher suite: "FOO"
726 invalid TLS cipher suite: "BAR"`,
727 },
728 }
729
730 for _, test := range tests {
731 t.Run(test.name, func(t *testing.T) {
732 config, err := test.tlsSetting.loadTLSConfig()
733 if test.wantErr != "" {
734 assert.EqualError(t, err, test.wantErr)
735 } else {
736 require.NoError(t, err)
737 assert.Equal(t, test.result, config.CipherSuites)
738 }
739 })
740 }
741 }
742
743 func TestSystemCertPool(t *testing.T) {
744 anError := errors.New("my error")
745 tests := []struct {
746 name string
747 tlsConfig Config
748 wantErr error
749 systemCertFn func() (*x509.CertPool, error)
750 }{
751 {
752 name: "not using system cert pool",
753 tlsConfig: Config{
754 IncludeSystemCACertsPool: false,
755 CAFile: filepath.Join("testdata", "ca-1.crt"),
756 },
757 wantErr: nil,
758 systemCertFn: x509.SystemCertPool,
759 },
760 {
761 name: "using system cert pool",
762 tlsConfig: Config{
763 IncludeSystemCACertsPool: true,
764 CAFile: filepath.Join("testdata", "ca-1.crt"),
765 },
766 wantErr: nil,
767 systemCertFn: x509.SystemCertPool,
768 },
769 {
770 name: "error loading system cert pool",
771 tlsConfig: Config{
772 IncludeSystemCACertsPool: true,
773 CAFile: filepath.Join("testdata", "ca-1.crt"),
774 },
775 wantErr: anError,
776 systemCertFn: func() (*x509.CertPool, error) {
777 return nil, anError
778 },
779 },
780 {
781 name: "nil system cert pool",
782 tlsConfig: Config{
783 IncludeSystemCACertsPool: true,
784 CAFile: filepath.Join("testdata", "ca-1.crt"),
785 },
786 wantErr: nil,
787 systemCertFn: func() (*x509.CertPool, error) {
788 return nil, nil
789 },
790 },
791 }
792 for _, test := range tests {
793 t.Run(test.name, func(t *testing.T) {
794 oldSystemCertPool := systemCertPool
795 systemCertPool = test.systemCertFn
796 defer func() {
797 systemCertPool = oldSystemCertPool
798 }()
799
800 serverConfig := ServerConfig{
801 Config: test.tlsConfig,
802 }
803 c, err := serverConfig.LoadTLSConfig(context.Background())
804 if test.wantErr != nil {
805 require.ErrorContains(t, err, test.wantErr.Error())
806 } else {
807 assert.NotNil(t, c.RootCAs)
808 }
809
810 clientConfig := ClientConfig{
811 Config: test.tlsConfig,
812 }
813 c, err = clientConfig.LoadTLSConfig(context.Background())
814 if test.wantErr != nil {
815 assert.ErrorContains(t, err, test.wantErr.Error())
816 } else {
817 assert.NotNil(t, c.RootCAs)
818 }
819 })
820 }
821 }
822
823 func TestSystemCertPool_loadCert(t *testing.T) {
824 anError := errors.New("my error")
825 tests := []struct {
826 name string
827 tlsConfig Config
828 wantErr error
829 systemCertFn func() (*x509.CertPool, error)
830 }{
831 {
832 name: "not using system cert pool",
833 tlsConfig: Config{
834 IncludeSystemCACertsPool: false,
835 },
836 wantErr: nil,
837 systemCertFn: x509.SystemCertPool,
838 },
839 {
840 name: "using system cert pool",
841 tlsConfig: Config{
842 IncludeSystemCACertsPool: true,
843 },
844 wantErr: nil,
845 systemCertFn: x509.SystemCertPool,
846 },
847 {
848 name: "error loading system cert pool",
849 tlsConfig: Config{
850 IncludeSystemCACertsPool: true,
851 },
852 wantErr: anError,
853 systemCertFn: func() (*x509.CertPool, error) {
854 return nil, anError
855 },
856 },
857 {
858 name: "nil system cert pool",
859 tlsConfig: Config{
860 IncludeSystemCACertsPool: true,
861 },
862 wantErr: nil,
863 systemCertFn: func() (*x509.CertPool, error) {
864 return nil, nil
865 },
866 },
867 }
868 for _, test := range tests {
869 t.Run(test.name, func(t *testing.T) {
870 oldSystemCertPool := systemCertPool
871 systemCertPool = test.systemCertFn
872 defer func() {
873 systemCertPool = oldSystemCertPool
874 }()
875 certPool, err := test.tlsConfig.loadCert(filepath.Join("testdata", "ca-1.crt"))
876 if test.wantErr != nil {
877 assert.Equal(t, test.wantErr, err)
878 } else {
879 assert.NotNil(t, certPool)
880 }
881 })
882 }
883 }
884
885 func TestCurvePreferences(t *testing.T) {
886 type testCase struct {
887 name string
888 preferences []string
889 expectedCurveIDs []tls.CurveID
890 expectedErr string
891 }
892
893 tests := []testCase{
894 {
895 name: "P521",
896 preferences: []string{"P521"},
897 expectedCurveIDs: []tls.CurveID{tls.CurveP521},
898 },
899 {
900 name: "P-256",
901 preferences: []string{"P256"},
902 expectedCurveIDs: []tls.CurveID{tls.CurveP256},
903 },
904 {
905 name: "multiple",
906 preferences: []string{"P256", "P521"},
907 expectedCurveIDs: []tls.CurveID{tls.CurveP256, tls.CurveP521},
908 },
909 {
910 name: "invalid-curve",
911 preferences: []string{"P25223236"},
912 expectedCurveIDs: []tls.CurveID{},
913 expectedErr: "invalid curve type",
914 },
915 }
916
917 // X25519 curves are not supported when GODEBUG=fips140=only is set, so we
918 // detect if it is and conditionally add test cases for those curves.
919 if !strings.Contains(os.Getenv("GODEBUG"), "fips140=only") {
920 tests = append(tests,
921 testCase{
922 name: "X25519MLKEM768",
923 preferences: []string{"X25519MLKEM768"},
924 expectedCurveIDs: []tls.CurveID{tls.X25519MLKEM768},
925 },
926 testCase{
927 name: "X25519",
928 preferences: []string{"X25519"},
929 expectedCurveIDs: []tls.CurveID{tls.X25519},
930 },
931 )
932 }
933
934 for _, test := range tests {
935 t.Run(test.name, func(t *testing.T) {
936 tlsSetting := ClientConfig{
937 Config: Config{
938 CurvePreferences: test.preferences,
939 },
940 }
941 config, err := tlsSetting.LoadTLSConfig(context.Background())
942 if test.expectedErr == "" {
943 require.NoError(t, err)
944 require.ElementsMatchf(t, test.expectedCurveIDs, config.CurvePreferences, "expected %v, got %v", test.expectedCurveIDs, config.CurvePreferences)
945 } else {
946 require.ErrorContains(t, err, test.expectedErr)
947 }
948 })
949 }
950 }
951
952 func TestServerConfigValidate(t *testing.T) {
953 tests := []struct {
954 name string
955 serverConfig ServerConfig
956 errorTxt string
957 }{
958 {
959 name: "server config without certificates",
960 serverConfig: ServerConfig{},
961 errorTxt: "TLS configuration must include both certificate and key for server connections",
962 },
963 {
964 name: "server config with cert file but no key",
965 serverConfig: ServerConfig{
966 Config: Config{
967 CertFile: "cert.pem",
968 },
969 },
970 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
971 },
972 {
973 name: "server config with key file but no cert",
974 serverConfig: ServerConfig{
975 Config: Config{
976 KeyFile: "key.pem",
977 },
978 },
979 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
980 },
981 {
982 name: "server config with cert PEM but no key",
983 serverConfig: ServerConfig{
984 Config: Config{
985 CertPem: "cert-pem",
986 },
987 },
988 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
989 },
990 {
991 name: "server config with key PEM but no cert",
992 serverConfig: ServerConfig{
993 Config: Config{
994 KeyPem: "key-pem",
995 },
996 },
997 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
998 },
999 {
1000 name: "server config with both cert file and cert PEM",
1001 serverConfig: ServerConfig{
1002 Config: Config{
1003 CertFile: "cert.pem",
1004 CertPem: "cert-pem",
1005 KeyFile: "key.pem",
1006 },
1007 },
1008 errorTxt: "config: provide either certificate file or PEM, but not both",
1009 },
1010 {
1011 name: "server config with both key file and key PEM",
1012 serverConfig: ServerConfig{
1013 Config: Config{
1014 CertFile: "cert.pem",
1015 KeyFile: "key.pem",
1016 KeyPem: "key-pem",
1017 },
1018 },
1019 errorTxt: "config: provide either key file or PEM, but not both",
1020 },
1021 {
1022 name: "valid server config with cert and key files",
1023 serverConfig: ServerConfig{
1024 Config: Config{
1025 CertFile: "cert.pem",
1026 KeyFile: "key.pem",
1027 },
1028 },
1029 },
1030 {
1031 name: "valid server config with cert and key PEM",
1032 serverConfig: ServerConfig{
1033 Config: Config{
1034 CertPem: "cert-pem",
1035 KeyPem: "key-pem",
1036 },
1037 },
1038 },
1039 {
1040 name: "valid server config with mixed cert file and key PEM",
1041 serverConfig: ServerConfig{
1042 Config: Config{
1043 CertFile: "cert.pem",
1044 KeyPem: "key-pem",
1045 },
1046 },
1047 },
1048 }
1049
1050 for _, test := range tests {
1051 t.Run(test.name, func(t *testing.T) {
1052 err := xconfmap.Validate(test.serverConfig)
1053
1054 if test.errorTxt == "" {
1055 assert.NoError(t, err)
1056 } else {
1057 assert.ErrorContains(t, err, test.errorTxt)
1058 }
1059 })
1060 }
1061 }
1062
1063 func TestClientConfigValidate(t *testing.T) {
1064 tests := []struct {
1065 name string
1066 clientConfig ClientConfig
1067 errorTxt string
1068 }{
1069 {
1070 name: "valid empty client config",
1071 clientConfig: ClientConfig{},
1072 },
1073 {
1074 name: "valid client config with insecure connection",
1075 clientConfig: ClientConfig{
1076 Insecure: true,
1077 },
1078 },
1079 {
1080 name: "valid client config with cert and key files",
1081 clientConfig: ClientConfig{
1082 Config: Config{
1083 CertFile: "cert.pem",
1084 KeyFile: "key.pem",
1085 },
1086 },
1087 },
1088 {
1089 name: "valid client config with mixed cert file and key PEM",
1090 clientConfig: ClientConfig{
1091 Config: Config{
1092 CertFile: "cert.pem",
1093 KeyPem: "key-pem",
1094 },
1095 },
1096 },
1097 {
1098 name: "client config with only cert file",
1099 clientConfig: ClientConfig{
1100 Config: Config{
1101 CertFile: "cert.pem",
1102 },
1103 },
1104 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
1105 },
1106 {
1107 name: "client config with only key file",
1108 clientConfig: ClientConfig{
1109 Config: Config{
1110 KeyFile: "key.pem",
1111 },
1112 },
1113 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
1114 },
1115 {
1116 name: "client config with only cert PEM",
1117 clientConfig: ClientConfig{
1118 Config: Config{
1119 CertPem: "cert-pem",
1120 },
1121 },
1122 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
1123 },
1124 {
1125 name: "client config with only key PEM",
1126 clientConfig: ClientConfig{
1127 Config: Config{
1128 KeyPem: "key-pem",
1129 },
1130 },
1131 errorTxt: "config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)",
1132 },
1133 }
1134
1135 for _, test := range tests {
1136 t.Run(test.name, func(t *testing.T) {
1137 err := xconfmap.Validate(test.clientConfig)
1138
1139 if test.errorTxt == "" {
1140 assert.NoError(t, err)
1141 } else {
1142 assert.ErrorContains(t, err, test.errorTxt)
1143 }
1144 })
1145 }
1146 }