github.com/yacovm/fabric@v2.0.0-alpha.0.20191128145320-c5d4087dc723+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 "fmt" 14 "math/rand" 15 "net" 16 "testing" 17 "time" 18 19 "github.com/stretchr/testify/assert" 20 "google.golang.org/grpc" 21 "google.golang.org/grpc/credentials" 22 ) 23 24 func createTLSService(t *testing.T, ca CA, host string) *grpc.Server { 25 keyPair, err := ca.NewServerCertKeyPair(host) 26 assert.NoError(t, err) 27 cert, err := tls.X509KeyPair(keyPair.Cert, keyPair.Key) 28 assert.NoError(t, err) 29 tlsConf := &tls.Config{ 30 Certificates: []tls.Certificate{cert}, 31 ClientAuth: tls.RequireAndVerifyClientCert, 32 ClientCAs: x509.NewCertPool(), 33 } 34 tlsConf.ClientCAs.AppendCertsFromPEM(ca.CertBytes()) 35 return grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConf))) 36 } 37 38 func TestTLSCA(t *testing.T) { 39 // This test checks that the CA can create certificates 40 // and corresponding keys that are signed by itself 41 42 rand.Seed(time.Now().UnixNano()) 43 randomPort := 1234 + rand.Intn(1234) // some random port 44 45 ca, err := NewCA() 46 assert.NoError(t, err) 47 assert.NotNil(t, ca) 48 49 endpoint := fmt.Sprintf("127.0.0.1:%d", randomPort) 50 srv := createTLSService(t, ca, "127.0.0.1") 51 l, err := net.Listen("tcp", endpoint) 52 assert.NoError(t, err) 53 go srv.Serve(l) 54 defer srv.Stop() 55 defer l.Close() 56 57 probeTLS := func(kp *CertKeyPair) error { 58 cert, err := tls.X509KeyPair(kp.Cert, kp.Key) 59 assert.NoError(t, err) 60 tlsCfg := &tls.Config{ 61 RootCAs: x509.NewCertPool(), 62 Certificates: []tls.Certificate{cert}, 63 } 64 tlsCfg.RootCAs.AppendCertsFromPEM(ca.CertBytes()) 65 tlsOpts := grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg)) 66 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 67 defer cancel() 68 conn, err := grpc.DialContext(ctx, fmt.Sprintf("127.0.0.1:%d", randomPort), tlsOpts, grpc.WithBlock()) 69 if err != nil { 70 return err 71 } 72 conn.Close() 73 return nil 74 } 75 76 // Good path - use a cert key pair generated from the CA 77 // that the TLS server started with 78 kp, err := ca.NewClientCertKeyPair() 79 assert.NoError(t, err) 80 err = probeTLS(kp) 81 assert.NoError(t, err) 82 83 // Bad path - use a cert key pair generated from a foreign CA 84 foreignCA, _ := NewCA() 85 kp, err = foreignCA.NewClientCertKeyPair() 86 assert.NoError(t, err) 87 err = probeTLS(kp) 88 assert.Error(t, err) 89 assert.Contains(t, err.Error(), "context deadline exceeded") 90 }