github.com/blend/go-sdk@v1.20240719.1/certutil/create_server.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - 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  // CreateServer creates a ca cert bundle.
    18  func CreateServer(commonName string, ca *CertBundle, options ...CertOption) (*CertBundle, error) {
    19  	if ca == nil || ca.PrivateKey == nil || len(ca.Certificates) == 0 {
    20  		return nil, ex.New("provided certificate authority bundle is invalid")
    21  	}
    22  
    23  	createOptions := DefaultOptionsServer
    24  	// set the default common name
    25  	createOptions.Subject.CommonName = commonName
    26  	// it is important to reflect the common name here as well
    27  	createOptions.DNSNames = []string{commonName}
    28  
    29  	if err := ResolveCertOptions(&createOptions, options...); err != nil {
    30  		return nil, nil
    31  	}
    32  
    33  	var output CertBundle
    34  	output.PrivateKey = createOptions.PrivateKey
    35  	output.PublicKey = &createOptions.PrivateKey.PublicKey
    36  	der, err := x509.CreateCertificate(rand.Reader, &createOptions.Certificate, &ca.Certificates[0], output.PublicKey, ca.PrivateKey)
    37  	if err != nil {
    38  		return nil, ex.New(err)
    39  	}
    40  	cert, err := x509.ParseCertificate(der)
    41  	if err != nil {
    42  		return nil, ex.New(err)
    43  	}
    44  	output.CertificateDERs = append([][]byte{der}, ca.CertificateDERs...)
    45  	output.Certificates = append([]x509.Certificate{*cert}, ca.Certificates...)
    46  	return &output, nil
    47  }