github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/testing/cert.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package testing
     5  
     6  import (
     7  	"crypto/rsa"
     8  	"crypto/tls"
     9  	"crypto/x509"
    10  	"math/rand"
    11  
    12  	mgotesting "github.com/juju/mgo/v3/testing"
    13  	utilscert "github.com/juju/utils/v3/cert"
    14  )
    15  
    16  // CACert and CAKey make up a CA key pair.
    17  // CACertX509 and CAKeyRSA hold their parsed equivalents.
    18  // ServerCert and ServerKey hold a CA-signed server cert/key.
    19  // Certs holds the certificates and keys required to make a secure
    20  // connection to a Mongo database.
    21  var (
    22  	CACert, CAKey, ServerCert, ServerKey = chooseGeneratedCA()
    23  
    24  	CACertX509, CAKeyRSA = mustParseCertAndKey(CACert, CAKey)
    25  
    26  	ServerTLSCert = mustParseServerCert(ServerCert, ServerKey)
    27  
    28  	Certs = serverCerts()
    29  
    30  	// Other valid test certs different from the default.
    31  	OtherCACert, OtherCAKey        = chooseGeneratedOtherCA()
    32  	OtherCACertX509, OtherCAKeyRSA = mustParseCertAndKey(OtherCACert, OtherCAKey)
    33  )
    34  
    35  func chooseGeneratedCA() (string, string, string, string) {
    36  	index := rand.Intn(len(generatedCA))
    37  	if len(generatedCA) != len(generatedServer) {
    38  		// This should never happen.
    39  		panic("generatedCA and generatedServer have mismatched length")
    40  	}
    41  	ca := generatedCA[index]
    42  	server := generatedServer[index]
    43  	return ca.certPEM, ca.keyPEM, server.certPEM, server.keyPEM
    44  }
    45  
    46  func chooseGeneratedOtherCA() (string, string) {
    47  	index := rand.Intn(len(otherCA))
    48  	ca := otherCA[index]
    49  	return ca.certPEM, ca.keyPEM
    50  }
    51  
    52  func mustParseServerCert(srvCert string, srvKey string) *tls.Certificate {
    53  	tlsCert, err := tls.X509KeyPair([]byte(srvCert), []byte(srvKey))
    54  	if err != nil {
    55  		panic(err)
    56  	}
    57  	x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
    58  	if err != nil {
    59  		panic(err)
    60  	}
    61  	tlsCert.Leaf = x509Cert
    62  	return &tlsCert
    63  }
    64  
    65  func mustParseCertAndKey(certPEM, keyPEM string) (*x509.Certificate, *rsa.PrivateKey) {
    66  	cert, key, err := utilscert.ParseCertAndKey(certPEM, keyPEM)
    67  	if err != nil {
    68  		panic(err)
    69  	}
    70  	return cert, key
    71  }
    72  
    73  func serverCerts() *mgotesting.Certs {
    74  	serverCert, serverKey := mustParseCertAndKey(ServerCert, ServerKey)
    75  	return &mgotesting.Certs{
    76  		CACert:     CACertX509,
    77  		ServerCert: serverCert,
    78  		ServerKey:  serverKey,
    79  	}
    80  }