github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/security/tls_test.go (about)

     1  // Copyright 2014 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package security_test
    12  
    13  import (
    14  	"crypto/x509"
    15  	"path/filepath"
    16  	"testing"
    17  
    18  	"github.com/cockroachdb/cockroach/pkg/security"
    19  	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
    20  )
    21  
    22  func TestLoadTLSConfig(t *testing.T) {
    23  	defer leaktest.AfterTest(t)()
    24  	config, err := security.LoadServerTLSConfig(
    25  		filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCACert),
    26  		filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCACert),
    27  		filepath.Join(security.EmbeddedCertsDir, security.EmbeddedNodeCert),
    28  		filepath.Join(security.EmbeddedCertsDir, security.EmbeddedNodeKey))
    29  	if err != nil {
    30  		t.Fatalf("Failed to load TLS config: %v", err)
    31  	}
    32  
    33  	if len(config.Certificates) != 1 {
    34  		t.Fatalf("config.Certificates should have 1 cert; found %d", len(config.Certificates))
    35  	}
    36  	cert := config.Certificates[0]
    37  	asn1Data := cert.Certificate[0] // TODO Check len()
    38  
    39  	x509Cert, err := x509.ParseCertificate(asn1Data)
    40  	if err != nil {
    41  		t.Fatalf("Couldn't parse test cert: %v", err)
    42  	}
    43  
    44  	if err = verifyX509Cert(x509Cert, "localhost", config.RootCAs); err != nil {
    45  		t.Errorf("Couldn't verify test cert against server CA: %v", err)
    46  	}
    47  
    48  	if err = verifyX509Cert(x509Cert, "localhost", config.ClientCAs); err != nil {
    49  		t.Errorf("Couldn't verify test cert against client CA: %v", err)
    50  	}
    51  
    52  	if err = verifyX509Cert(x509Cert, "google.com", config.RootCAs); err == nil {
    53  		t.Errorf("Verified test cert for wrong hostname")
    54  	}
    55  }
    56  
    57  func verifyX509Cert(cert *x509.Certificate, dnsName string, roots *x509.CertPool) error {
    58  	verifyOptions := x509.VerifyOptions{
    59  		DNSName: dnsName,
    60  		Roots:   roots,
    61  		KeyUsages: []x509.ExtKeyUsage{
    62  			x509.ExtKeyUsageServerAuth,
    63  			x509.ExtKeyUsageClientAuth,
    64  		},
    65  	}
    66  	_, err := cert.Verify(verifyOptions)
    67  	return err
    68  }