github.com/blend/go-sdk@v1.20220411.3/certutil/create_client.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/rand"
    12  	"crypto/x509"
    13  
    14  	"github.com/blend/go-sdk/ex"
    15  )
    16  
    17  /*
    18  CreateClient creates a client cert bundle associated with a given common name.
    19  
    20  The CA must be passed in as a CertBundle.
    21  
    22  Example:
    23  
    24  	ca, err := certutil.NewCertBundle(certutil.KeyPairFromPaths("ca.crt", "ca.key"))
    25  	if err != nil {
    26  		return err
    27  	}
    28  	client, err := CreateClient("foo.bar.com", ca)
    29  */
    30  func CreateClient(commonName string, ca *CertBundle, options ...CertOption) (*CertBundle, error) {
    31  	if ca == nil {
    32  		return nil, ex.New("must provide a ca cert bundle")
    33  	}
    34  
    35  	createOptions := DefaultOptionsClient
    36  	createOptions.Subject.CommonName = commonName
    37  	createOptions.DNSNames = []string{commonName}
    38  
    39  	if err := ResolveCertOptions(&createOptions, options...); err != nil {
    40  		return nil, nil
    41  	}
    42  
    43  	var output CertBundle
    44  	output.PrivateKey = createOptions.PrivateKey
    45  	output.PublicKey = &createOptions.PrivateKey.PublicKey
    46  
    47  	der, err := x509.CreateCertificate(rand.Reader, &createOptions.Certificate, &ca.Certificates[0], output.PublicKey, ca.PrivateKey)
    48  	if err != nil {
    49  		return nil, ex.New(err)
    50  	}
    51  	cert, err := x509.ParseCertificate(der)
    52  	if err != nil {
    53  		return nil, ex.New(err)
    54  	}
    55  	output.CertificateDERs = append([][]byte{der}, ca.CertificateDERs...)
    56  	output.Certificates = append([]x509.Certificate{*cert}, ca.Certificates...)
    57  	return &output, nil
    58  }