github.com/hyperledger-labs/bdls@v2.1.1+incompatible/common/crypto/tlsgen/ca_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package tlsgen
     8  
     9  import (
    10  	"context"
    11  	"crypto/tls"
    12  	"crypto/x509"
    13  	"net"
    14  	"testing"
    15  	"time"
    16  
    17  	"github.com/stretchr/testify/assert"
    18  	"google.golang.org/grpc"
    19  	"google.golang.org/grpc/credentials"
    20  )
    21  
    22  func createTLSService(t *testing.T, ca CA, host string) *grpc.Server {
    23  	keyPair, err := ca.NewServerCertKeyPair(host)
    24  	assert.NoError(t, err)
    25  	cert, err := tls.X509KeyPair(keyPair.Cert, keyPair.Key)
    26  	assert.NoError(t, err)
    27  	tlsConf := &tls.Config{
    28  		Certificates: []tls.Certificate{cert},
    29  		ClientAuth:   tls.RequireAndVerifyClientCert,
    30  		ClientCAs:    x509.NewCertPool(),
    31  	}
    32  	tlsConf.ClientCAs.AppendCertsFromPEM(ca.CertBytes())
    33  	return grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConf)))
    34  }
    35  
    36  func TestTLSCA(t *testing.T) {
    37  	// This test checks that the CA can create certificates
    38  	// and corresponding keys that are signed by itself
    39  
    40  	ca, err := NewCA()
    41  	assert.NoError(t, err)
    42  	assert.NotNil(t, ca)
    43  
    44  	srv := createTLSService(t, ca, "127.0.0.1")
    45  	listener, err := net.Listen("tcp", "127.0.0.1:0")
    46  	assert.NoError(t, err)
    47  	go srv.Serve(listener)
    48  	defer srv.Stop()
    49  	defer listener.Close()
    50  
    51  	probeTLS := func(kp *CertKeyPair) error {
    52  		cert, err := tls.X509KeyPair(kp.Cert, kp.Key)
    53  		assert.NoError(t, err)
    54  		tlsCfg := &tls.Config{
    55  			RootCAs:      x509.NewCertPool(),
    56  			Certificates: []tls.Certificate{cert},
    57  		}
    58  		tlsCfg.RootCAs.AppendCertsFromPEM(ca.CertBytes())
    59  		tlsOpts := grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg))
    60  		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    61  		defer cancel()
    62  		conn, err := grpc.DialContext(ctx, listener.Addr().String(), tlsOpts, grpc.WithBlock())
    63  		if err != nil {
    64  			return err
    65  		}
    66  		conn.Close()
    67  		return nil
    68  	}
    69  
    70  	// Good path - use a cert key pair generated from the CA
    71  	// that the TLS server started with
    72  	kp, err := ca.NewClientCertKeyPair()
    73  	assert.NoError(t, err)
    74  	err = probeTLS(kp)
    75  	assert.NoError(t, err)
    76  
    77  	// Bad path - use a cert key pair generated from a foreign CA
    78  	foreignCA, _ := NewCA()
    79  	kp, err = foreignCA.NewClientCertKeyPair()
    80  	assert.NoError(t, err)
    81  	err = probeTLS(kp)
    82  	assert.Error(t, err)
    83  	assert.Contains(t, err.Error(), "context deadline exceeded")
    84  }