| 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: "clientkey-without-clientcert", |
| 51 |
clientKeyFile: ptr("nowhere.key"), |
| 52 |
wantErrContains: "client key was provided but no client certificate was provided", |
| 53 |
}, |
| 54 |
{ |
| 55 |
name: "bad-cacert-file", |
| 56 |
caCertFile: ptr(filepath.Join("..", "..", "testdata", "bad_cert.crt")), |
| 57 |
wantErrContains: "could not create certificate authority chain from certificate", |
| 58 |
}, |
| 59 |
} |
| 60 |
|
| 61 |
for _, tt := range tests { |
| 62 |
t.Run(tt.name, func(t *testing.T) { |
| 63 |
got, err := CreateConfig(tt.caCertFile, tt.clientCertFile, tt.clientKeyFile) |
| 64 |
|
| 65 |
if tt.wantErrContains != "" { |
| 66 |
require.Contains(t, err.Error(), tt.wantErrContains) |
| 67 |
} else { |
| 68 |
require.NoError(t, err) |
| 69 |
tt.want(got, t) |
| 70 |
} |
| 71 |
}) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
func ptr[T any](v T) *T { |
| 76 |
return &v |
| 77 |
} |