Files

61 lines
2.1 KiB
Go

package tlsconfig
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestLoadClientLoadsTrustAndIdentity(t *testing.T) {
caPath, certificatePath, keyPath := writeClientCertificate(t)
configuration, err := LoadClient(ClientConfig{
CAPath: caPath, CertificatePath: certificatePath, PrivateKeyPath: keyPath, ServerName: "collector",
})
require.NoError(t, err)
require.Equal(t, uint16(0x0304), configuration.MinVersion)
require.Equal(t, "collector", configuration.ServerName)
require.Len(t, configuration.Certificates, 1)
require.NotNil(t, configuration.RootCAs)
}
func TestLoadClientRejectsPartialIdentity(t *testing.T) {
caPath, certificatePath, _ := writeClientCertificate(t)
_, err := LoadClient(ClientConfig{CAPath: caPath, CertificatePath: certificatePath, ServerName: "collector"})
require.ErrorContains(t, err, "configured together")
}
func writeClientCertificate(t *testing.T) (string, string, string) {
t.Helper()
directory := t.TempDir()
key, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true, IsCA: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
require.NoError(t, err)
certificate := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
privateKey := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
caPath := filepath.Join(directory, "ca.crt")
certificatePath := filepath.Join(directory, "tls.crt")
keyPath := filepath.Join(directory, "tls.key")
require.NoError(t, os.WriteFile(caPath, certificate, 0o600))
require.NoError(t, os.WriteFile(certificatePath, certificate, 0o600))
require.NoError(t, os.WriteFile(keyPath, privateKey, 0o600))
return caPath, certificatePath, keyPath
}