github.com/blend/go-sdk@v1.20220411.3/certutil/client_config.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package certutil
     9  
    10  import (
    11  	"crypto/tls"
    12  	"crypto/x509"
    13  
    14  	"github.com/blend/go-sdk/ex"
    15  )
    16  
    17  // NewClientTLSConfig returns a new client tls config.
    18  // This is useful for making mutual tls calls to servers that require it.
    19  func NewClientTLSConfig(clientCert KeyPair, certificateAuthorities []KeyPair) (*tls.Config, error) {
    20  	clientCertPEM, err := clientCert.CertBytes()
    21  	if err != nil {
    22  		return nil, ex.New(err)
    23  	}
    24  	clientKeyPEM, err := clientCert.KeyBytes()
    25  	if err != nil {
    26  		return nil, ex.New(err)
    27  	}
    28  
    29  	if len(clientCertPEM) == 0 {
    30  		return nil, ex.New("invalid key pair; empty cert pem data")
    31  	}
    32  	if len(clientKeyPEM) == 0 {
    33  		return nil, ex.New("invalid key pair; empty key pem data")
    34  	}
    35  	cert, err := tls.X509KeyPair(clientCertPEM, clientKeyPEM)
    36  	if err != nil {
    37  		return nil, ex.New(err)
    38  	}
    39  	config := new(tls.Config)
    40  
    41  	rootCAPool, err := x509.SystemCertPool()
    42  	if err != nil {
    43  		return nil, ex.New(err)
    44  	}
    45  
    46  	for _, caCert := range certificateAuthorities {
    47  		contents, err := caCert.CertBytes()
    48  		if err != nil {
    49  			return nil, ex.New(err)
    50  		}
    51  		if ok := rootCAPool.AppendCertsFromPEM(contents); !ok {
    52  			return nil, ex.New("failed to append ca cert file")
    53  		}
    54  	}
    55  
    56  	config.Certificates = []tls.Certificate{cert}
    57  	config.RootCAs = rootCAPool
    58  	return config, nil
    59  }