package objstore
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
)
func NewTLSConfig (cfg *TLSConfig ) (*tls .Config , error ) {
tlsConfig := &tls .Config {InsecureSkipVerify : cfg .InsecureSkipVerify }
if len (cfg .CAFile ) > 0 {
b , err := readCAFile (cfg .CAFile )
if err != nil {
return nil , err
}
if !updateRootCA (tlsConfig , b ) {
return nil , fmt .Errorf ("unable to use specified CA cert %s" , cfg .CAFile )
}
}
if len (cfg .ServerName ) > 0 {
tlsConfig .ServerName = cfg .ServerName
}
if len (cfg .CertFile ) > 0 && len (cfg .KeyFile ) == 0 {
return nil , fmt .Errorf ("client cert file %q specified without client key file" , cfg .CertFile )
} else if len (cfg .KeyFile ) > 0 && len (cfg .CertFile ) == 0 {
return nil , fmt .Errorf ("client key file %q specified without client cert file" , cfg .KeyFile )
} else if len (cfg .CertFile ) > 0 && len (cfg .KeyFile ) > 0 {
if _ , err := cfg .getClientCertificate (nil ); err != nil {
return nil , err
}
tlsConfig .GetClientCertificate = cfg .getClientCertificate
}
return tlsConfig , nil
}
func readCAFile(f string ) ([]byte , error ) {
data , err := os .ReadFile (f )
if err != nil {
return nil , fmt .Errorf ("unable to load specified CA cert %s: %s" , f , err )
}
return data , nil
}
func updateRootCA(cfg *tls .Config , b []byte ) bool {
caCertPool := x509 .NewCertPool ()
if !caCertPool .AppendCertsFromPEM (b ) {
return false
}
cfg .RootCAs = caCertPool
return true
}
func (c *TLSConfig ) getClientCertificate (*tls .CertificateRequestInfo ) (*tls .Certificate , error ) {
cert , err := tls .LoadX509KeyPair (c .CertFile , c .KeyFile )
if err != nil {
return nil , fmt .Errorf ("unable to use specified client cert (%s) & key (%s): %s" , c .CertFile , c .KeyFile , err )
}
return &cert , nil
}
type TLSConfig struct {
CAFile string `yaml:"ca_file"`
CertFile string `yaml:"cert_file"`
KeyFile string `yaml:"key_file"`
ServerName string `yaml:"server_name"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .