github.com/avenga/couper@v1.12.2/handler/transport/tls.go (about) 1 package transport 2 3 import ( 4 "crypto/tls" 5 6 "github.com/avenga/couper/config" 7 "github.com/avenga/couper/config/reader" 8 "github.com/avenga/couper/errors" 9 coupertls "github.com/avenga/couper/internal/tls" 10 ) 11 12 // ReadCertificates parses an optional CA certificate or a client certificate / key pair. 13 // It is valid to have just the client pair without the CA certificate since the system 14 // Root CAs or the related Couper cli option MAY configure the related transport too. 15 func ReadCertificates(conf *config.BackendTLS) (tls.Certificate, tls.Certificate, error) { 16 fail := func(err error) (tls.Certificate, tls.Certificate, error) { 17 return tls.Certificate{}, tls.Certificate{}, err 18 } 19 20 if conf == nil { 21 return fail(nil) 22 } 23 24 hasCA := conf.ServerCertificate != "" || conf.ServerCertificateFile != "" 25 hasClient := conf.ClientCertificate != "" || conf.ClientCertificateFile != "" 26 hasClientKey := conf.ClientPrivateKey != "" || conf.ClientPrivateKeyFile != "" 27 28 if !hasCA && !hasClient { 29 return fail(nil) 30 } 31 32 if hasClient && !hasClientKey { 33 return fail(errors.Configuration.Message("tls: missing client private key")) 34 } 35 36 var caCertificate, clientCertificate tls.Certificate 37 38 caCert, err := reader.ReadFromAttrFile("tls", conf.ServerCertificate, conf.ServerCertificateFile) 39 if err != nil && hasCA { 40 return fail(err) 41 } 42 43 clientCert, err := reader.ReadFromAttrFile("tls", conf.ClientCertificate, conf.ClientCertificateFile) 44 if err != nil && hasClient { 45 return fail(err) 46 } 47 48 clientKey, err := reader.ReadFromAttrFile("tls", conf.ClientPrivateKey, conf.ClientPrivateKeyFile) 49 if err != nil && (conf.ClientPrivateKey != "" || conf.ClientPrivateKeyFile != "") { 50 return fail(err) 51 } 52 53 if len(caCert) > 0 { 54 caCertificate, err = coupertls.ParseCertificate(caCert, nil) 55 if err != nil { 56 return fail(err) 57 } 58 } 59 60 if len(clientCert) > 0 { 61 clientCertificate, err = coupertls.ParseCertificate(clientCert, clientKey) 62 } 63 64 return caCertificate, clientCertificate, err 65 }