github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/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  	"fmt"
    11  	"time"
    12  
    13  	gitjujutesting "github.com/juju/testing"
    14  
    15  	"github.com/juju/juju/cert"
    16  )
    17  
    18  func init() {
    19  	if err := verifyCertificates(); err != nil {
    20  		panic(err)
    21  	}
    22  }
    23  
    24  // CACert and CAKey make up a CA key pair.
    25  // CACertX509 and CAKeyRSA hold their parsed equivalents.
    26  // ServerCert and ServerKey hold a CA-signed server cert/key.
    27  // Certs holds the certificates and keys required to make a secure
    28  // connection to a Mongo database.
    29  var (
    30  	CACert, CAKey = mustNewCA()
    31  
    32  	CACertX509, CAKeyRSA = mustParseCertAndKey(CACert, CAKey)
    33  
    34  	ServerCert, ServerKey = mustNewServer()
    35  
    36  	Certs = serverCerts()
    37  
    38  	// Other valid test certs different from the default.
    39  	OtherCACert, OtherCAKey = mustNewCA()
    40  )
    41  
    42  func verifyCertificates() error {
    43  	_, err := tls.X509KeyPair([]byte(CACert), []byte(CAKey))
    44  	if err != nil {
    45  		return fmt.Errorf("bad CA cert key pair: %v", err)
    46  	}
    47  	_, err = tls.X509KeyPair([]byte(ServerCert), []byte(ServerKey))
    48  	if err != nil {
    49  		return fmt.Errorf("bad server cert key pair: %v", err)
    50  	}
    51  	return cert.Verify(ServerCert, CACert, time.Now())
    52  }
    53  
    54  func mustNewCA() (string, string) {
    55  	cert.KeyBits = 512
    56  	caCert, caKey, err := cert.NewCA("juju testing", "1234-ABCD-IS-NOT-A-REAL-UUID", time.Now().AddDate(10, 0, 0))
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  	return string(caCert), string(caKey)
    61  }
    62  
    63  func mustNewServer() (string, string) {
    64  	cert.KeyBits = 512
    65  	var hostnames []string
    66  	srvCert, srvKey, err := cert.NewServer(CACert, CAKey, time.Now().AddDate(10, 0, 0), hostnames)
    67  	if err != nil {
    68  		panic(err)
    69  	}
    70  	return string(srvCert), string(srvKey)
    71  }
    72  
    73  func mustParseCertAndKey(certPEM, keyPEM string) (*x509.Certificate, *rsa.PrivateKey) {
    74  	cert, key, err := cert.ParseCertAndKey(certPEM, keyPEM)
    75  	if err != nil {
    76  		panic(err)
    77  	}
    78  	return cert, key
    79  }
    80  
    81  func serverCerts() *gitjujutesting.Certs {
    82  	serverCert, serverKey := mustParseCertAndKey(ServerCert, ServerKey)
    83  	return &gitjujutesting.Certs{
    84  		CACert:     CACertX509,
    85  		ServerCert: serverCert,
    86  		ServerKey:  serverKey,
    87  	}
    88  }