Files

51 lines
1.3 KiB
Go

package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"strings"
)
type ClientConfig struct {
CAPath string
CertificatePath string
PrivateKeyPath string
ServerName string
}
func LoadClient(config ClientConfig) (*tls.Config, error) {
if strings.TrimSpace(config.ServerName) == "" {
return nil, errors.New("TLS server name is required")
}
caPEM, err := os.ReadFile(config.CAPath)
if err != nil {
return nil, fmt.Errorf("read server CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return nil, errors.New("server CA does not contain a certificate")
}
var certificates []tls.Certificate
if config.CertificatePath != "" || config.PrivateKeyPath != "" {
if config.CertificatePath == "" || config.PrivateKeyPath == "" {
return nil, errors.New("TLS client certificate and private key must be configured together")
}
certificate, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
if err != nil {
return nil, fmt.Errorf("load client certificate: %w", err)
}
certificates = []tls.Certificate{certificate}
}
return &tls.Config{
MinVersion: tls.VersionTLS13,
RootCAs: roots,
Certificates: certificates,
ServerName: config.ServerName,
}, nil
}