|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package tls |
| 5 | + |
| 6 | +import ( |
| 7 | + "crypto/tls" |
| 8 | + "path/filepath" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/require" |
| 12 | +) |
| 13 | + |
| 14 | +func TestCreateConfig(t *testing.T) { |
| 15 | + tests := []struct { |
| 16 | + name string |
| 17 | + caCertFile *string |
| 18 | + clientCertFile *string |
| 19 | + clientKeyFile *string |
| 20 | + wantErrContains string |
| 21 | + want func(*tls.Config, *testing.T) |
| 22 | + }{ |
| 23 | + { |
| 24 | + name: "no-input", |
| 25 | + want: func(result *tls.Config, t *testing.T) { |
| 26 | + require.Nil(t, result.Certificates) |
| 27 | + require.Nil(t, result.RootCAs) |
| 28 | + }, |
| 29 | + }, |
| 30 | + { |
| 31 | + name: "only-cacert-provided", |
| 32 | + caCertFile: ptr(filepath.Join("..", "..", "testdata", "ca.crt")), |
| 33 | + want: func(result *tls.Config, t *testing.T) { |
| 34 | + require.Nil(t, result.Certificates) |
| 35 | + require.NotNil(t, result.RootCAs) |
| 36 | + }, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "nonexistent-cacert-file", |
| 40 | + caCertFile: ptr("nowhere.crt"), |
| 41 | + wantErrContains: "open nowhere.crt:", |
| 42 | + }, |
| 43 | + { |
| 44 | + name: "nonexistent-clientcert-file", |
| 45 | + clientCertFile: ptr("nowhere.crt"), |
| 46 | + clientKeyFile: ptr("nowhere.crt"), |
| 47 | + wantErrContains: "could not use client certificate: open nowhere.crt:", |
| 48 | + }, |
| 49 | + { |
| 50 | + name: "bad-cacert-file", |
| 51 | + caCertFile: ptr(filepath.Join("..", "..", "testdata", "bad_cert.crt")), |
| 52 | + wantErrContains: "could not create certificate authority chain from certificate", |
| 53 | + }, |
| 54 | + } |
| 55 | + |
| 56 | + for _, tt := range tests { |
| 57 | + t.Run(tt.name, func(t *testing.T) { |
| 58 | + got, err := CreateConfig(tt.caCertFile, tt.clientCertFile, tt.clientKeyFile) |
| 59 | + |
| 60 | + if tt.wantErrContains != "" { |
| 61 | + require.Contains(t, err.Error(), tt.wantErrContains) |
| 62 | + } else { |
| 63 | + require.NoError(t, err) |
| 64 | + tt.want(got, t) |
| 65 | + } |
| 66 | + }) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func ptr[T any](v T) *T { |
| 71 | + return &v |
| 72 | +} |
0 commit comments