github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/core/comm/server_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package comm_test
    18  
    19  import (
    20  	"crypto/tls"
    21  	"crypto/x509"
    22  	"errors"
    23  	"fmt"
    24  	"io/ioutil"
    25  	"log"
    26  	"net"
    27  	"path/filepath"
    28  	"sync"
    29  	"testing"
    30  	"time"
    31  
    32  	"github.com/stretchr/testify/assert"
    33  
    34  	"golang.org/x/net/context"
    35  	"google.golang.org/grpc"
    36  	"google.golang.org/grpc/credentials"
    37  
    38  	"github.com/hyperledger/fabric/core/comm"
    39  	testpb "github.com/hyperledger/fabric/core/comm/testdata/grpc"
    40  )
    41  
    42  //Embedded certificates for testing
    43  //These are the prime256v1-openssl-*.pem in testdata
    44  //The self-signed cert expires in 2026
    45  var selfSignedKeyPEM = `-----BEGIN EC PARAMETERS-----
    46  BggqhkjOPQMBBw==
    47  -----END EC PARAMETERS-----
    48  -----BEGIN EC PRIVATE KEY-----
    49  MHcCAQEEIM2rUTflEQ11m5g5yEm2Cer2yI+ziccl1NbSRVh3GUR0oAoGCCqGSM49
    50  AwEHoUQDQgAEu2FEZVSr30Afey6dwcypeg5P+BuYx5JSYdG0/KJIBjWKnzYo7FEm
    51  gMir7GbNh4pqA8KFrJZkPuxMgnEJBZTv+w==
    52  -----END EC PRIVATE KEY-----
    53  `
    54  var selfSignedCertPEM = `-----BEGIN CERTIFICATE-----
    55  MIICRDCCAemgAwIBAgIJALwW//dz2ZBvMAoGCCqGSM49BAMCMH4xCzAJBgNVBAYT
    56  AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2Nv
    57  MRgwFgYDVQQKDA9MaW51eEZvdW5kYXRpb24xFDASBgNVBAsMC0h5cGVybGVkZ2Vy
    58  MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTYxMjA0MjIzMDE4WhcNMjYxMjAyMjIz
    59  MDE4WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UE
    60  BwwNU2FuIEZyYW5jaXNjbzEYMBYGA1UECgwPTGludXhGb3VuZGF0aW9uMRQwEgYD
    61  VQQLDAtIeXBlcmxlZGdlcjESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0C
    62  AQYIKoZIzj0DAQcDQgAEu2FEZVSr30Afey6dwcypeg5P+BuYx5JSYdG0/KJIBjWK
    63  nzYo7FEmgMir7GbNh4pqA8KFrJZkPuxMgnEJBZTv+6NQME4wHQYDVR0OBBYEFAWO
    64  4bfTEr2R6VYzQYrGk/2VWmtYMB8GA1UdIwQYMBaAFAWO4bfTEr2R6VYzQYrGk/2V
    65  WmtYMAwGA1UdEwQFMAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhAIelqGdxPMHmQqRF
    66  zA85vv7JhfMkvZYGPELC7I2K8V7ZAiEA9KcthV3HtDXKNDsA6ULT+qUkyoHRzCzr
    67  A4QaL2VU6i4=
    68  -----END CERTIFICATE-----
    69  `
    70  
    71  var badPEM = `-----BEGIN CERTIFICATE-----
    72  MIICRDCCAemgAwIBAgIJALwW//dz2ZBvMAoGCCqGSM49BAMCMH4xCzAJBgNVBAYT
    73  AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2Nv
    74  MRgwFgYDVQQKDA9MaW51eEZvdW5kYXRpb24xFDASBgNVBAsMC0h5cGVybGVkZ2Vy
    75  MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTYxMjA0MjIzMDE4WhcNMjYxMjAyMjIz
    76  MDE4WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UE
    77  BwwNU2FuIEZyYW5jaXNjbzEYMBYGA1UECgwPTGludXhGb3VuZGF0aW9uMRQwEgYD
    78  VQQLDAtIeXBlcmxlZGdlcjESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0C
    79  -----END CERTIFICATE-----
    80  `
    81  
    82  var pemNoCertificateHeader = `-----BEGIN NOCERT-----
    83  MIICRDCCAemgAwIBAgIJALwW//dz2ZBvMAoGCCqGSM49BAMCMH4xCzAJBgNVBAYT
    84  AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2Nv
    85  MRgwFgYDVQQKDA9MaW51eEZvdW5kYXRpb24xFDASBgNVBAsMC0h5cGVybGVkZ2Vy
    86  MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTYxMjA0MjIzMDE4WhcNMjYxMjAyMjIz
    87  MDE4WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UE
    88  BwwNU2FuIEZyYW5jaXNjbzEYMBYGA1UECgwPTGludXhGb3VuZGF0aW9uMRQwEgYD
    89  VQQLDAtIeXBlcmxlZGdlcjESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0C
    90  AQYIKoZIzj0DAQcDQgAEu2FEZVSr30Afey6dwcypeg5P+BuYx5JSYdG0/KJIBjWK
    91  nzYo7FEmgMir7GbNh4pqA8KFrJZkPuxMgnEJBZTv+6NQME4wHQYDVR0OBBYEFAWO
    92  4bfTEr2R6VYzQYrGk/2VWmtYMB8GA1UdIwQYMBaAFAWO4bfTEr2R6VYzQYrGk/2V
    93  WmtYMAwGA1UdEwQFMAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhAIelqGdxPMHmQqRF
    94  zA85vv7JhfMkvZYGPELC7I2K8V7ZAiEA9KcthV3HtDXKNDsA6ULT+qUkyoHRzCzr
    95  A4QaL2VU6i4=
    96  -----END NOCERT-----
    97  `
    98  
    99  var timeout = time.Second * 1
   100  var testOrgs = []testOrg{}
   101  
   102  func init() {
   103  	//load up crypto material for test orgs
   104  	for i := 1; i <= numOrgs; i++ {
   105  		testOrg, err := loadOrg(i)
   106  		if err != nil {
   107  			log.Fatalf("Failed to load test organizations due to error: %s", err.Error())
   108  		}
   109  		testOrgs = append(testOrgs, testOrg)
   110  	}
   111  }
   112  
   113  //test server to be registered with the GRPCServer
   114  type testServiceServer struct{}
   115  
   116  func (tss *testServiceServer) EmptyCall(context.Context, *testpb.Empty) (*testpb.Empty, error) {
   117  	return new(testpb.Empty), nil
   118  }
   119  
   120  //invoke the EmptyCall RPC
   121  func invokeEmptyCall(address string, dialOptions []grpc.DialOption) (*testpb.Empty, error) {
   122  
   123  	//add DialOptions
   124  	dialOptions = append(dialOptions, grpc.WithBlock())
   125  	dialOptions = append(dialOptions, grpc.WithTimeout(timeout))
   126  	//create GRPC client conn
   127  	clientConn, err := grpc.Dial(address, dialOptions...)
   128  	if err != nil {
   129  		return nil, err
   130  	}
   131  	defer clientConn.Close()
   132  
   133  	//create GRPC client
   134  	client := testpb.NewTestServiceClient(clientConn)
   135  
   136  	ctx := context.Background()
   137  	ctx, cancel := context.WithTimeout(ctx, timeout)
   138  	defer cancel()
   139  
   140  	//invoke service
   141  	empty, err := client.EmptyCall(ctx, new(testpb.Empty))
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  
   146  	return empty, nil
   147  }
   148  
   149  const (
   150  	numOrgs        = 2
   151  	numChildOrgs   = 2
   152  	numClientCerts = 2
   153  	numServerCerts = 2
   154  )
   155  
   156  //string for cert filenames
   157  var (
   158  	orgCAKey        = filepath.Join("testdata", "certs", "Org%d-key.pem")
   159  	orgCACert       = filepath.Join("testdata", "certs", "Org%d-cert.pem")
   160  	orgServerKey    = filepath.Join("testdata", "certs", "Org%d-server%d-key.pem")
   161  	orgServerCert   = filepath.Join("testdata", "certs", "Org%d-server%d-cert.pem")
   162  	orgClientKey    = filepath.Join("testdata", "certs", "Org%d-client%d-key.pem")
   163  	orgClientCert   = filepath.Join("testdata", "certs", "Org%d-client%d-cert.pem")
   164  	childCAKey      = filepath.Join("testdata", "certs", "Org%d-child%d-key.pem")
   165  	childCACert     = filepath.Join("testdata", "certs", "Org%d-child%d-cert.pem")
   166  	childServerKey  = filepath.Join("testdata", "certs", "Org%d-child%d-server%d-key.pem")
   167  	childServerCert = filepath.Join("testdata", "certs", "Org%d-child%d-server%d-cert.pem")
   168  	childClientKey  = filepath.Join("testdata", "certs", "Org%d-child%d-client%d-key.pem")
   169  	childClientCert = filepath.Join("testdata", "certs", "Org%d-child%d-client%d-cert.pem")
   170  )
   171  
   172  type testServer struct {
   173  	address string
   174  	config  comm.SecureServerConfig
   175  }
   176  
   177  type serverCert struct {
   178  	keyPEM  []byte
   179  	certPEM []byte
   180  }
   181  
   182  type testOrg struct {
   183  	rootCA      []byte
   184  	serverCerts []serverCert
   185  	clientCerts []tls.Certificate
   186  	childOrgs   []testOrg
   187  }
   188  
   189  //return *X509.CertPool for the rootCA of the org
   190  func (org *testOrg) rootCertPool() *x509.CertPool {
   191  	certPool := x509.NewCertPool()
   192  	certPool.AppendCertsFromPEM(org.rootCA)
   193  	return certPool
   194  }
   195  
   196  //return testServers for the org
   197  func (org *testOrg) testServers(port int, clientRootCAs [][]byte) []testServer {
   198  
   199  	var testServers = []testServer{}
   200  	clientRootCAs = append(clientRootCAs, org.rootCA)
   201  	//loop through the serverCerts and create testServers
   202  	for i, serverCert := range org.serverCerts {
   203  		testServer := testServer{
   204  			fmt.Sprintf("localhost:%d", port+i),
   205  			comm.SecureServerConfig{
   206  				UseTLS:            true,
   207  				ServerCertificate: serverCert.certPEM,
   208  				ServerKey:         serverCert.keyPEM,
   209  				RequireClientCert: true,
   210  				ClientRootCAs:     clientRootCAs,
   211  			},
   212  		}
   213  		testServers = append(testServers, testServer)
   214  	}
   215  	return testServers
   216  }
   217  
   218  //return trusted clients for the org
   219  func (org *testOrg) trustedClients(serverRootCAs [][]byte) []*tls.Config {
   220  
   221  	var trustedClients = []*tls.Config{}
   222  	//if we have any additional server root CAs add them to the certPool
   223  	certPool := org.rootCertPool()
   224  	for _, serverRootCA := range serverRootCAs {
   225  		certPool.AppendCertsFromPEM(serverRootCA)
   226  	}
   227  
   228  	//loop through the clientCerts and create tls.Configs
   229  	for _, clientCert := range org.clientCerts {
   230  		trustedClient := &tls.Config{
   231  			Certificates: []tls.Certificate{clientCert},
   232  			RootCAs:      certPool,
   233  		}
   234  		trustedClients = append(trustedClients, trustedClient)
   235  	}
   236  	return trustedClients
   237  }
   238  
   239  //createCertPool creates an x509.CertPool from an array of PEM-encoded certificates
   240  func createCertPool(rootCAs [][]byte) (*x509.CertPool, error) {
   241  
   242  	certPool := x509.NewCertPool()
   243  	for _, rootCA := range rootCAs {
   244  		if !certPool.AppendCertsFromPEM(rootCA) {
   245  			return nil, errors.New("Failed to load root certificates")
   246  		}
   247  	}
   248  	return certPool, nil
   249  }
   250  
   251  //utility function to load crypto material for organizations
   252  func loadOrg(parent int) (testOrg, error) {
   253  
   254  	var org = testOrg{}
   255  	//load the CA
   256  	caPEM, err := ioutil.ReadFile(fmt.Sprintf(orgCACert, parent))
   257  	if err != nil {
   258  		return org, err
   259  	}
   260  	//loop through and load servers
   261  	var serverCerts = []serverCert{}
   262  	for i := 1; i <= numServerCerts; i++ {
   263  		keyPEM, err := ioutil.ReadFile(fmt.Sprintf(orgServerKey, parent, i))
   264  		if err != nil {
   265  			return org, err
   266  		}
   267  		certPEM, err := ioutil.ReadFile(fmt.Sprintf(orgServerCert, parent, i))
   268  		if err != nil {
   269  			return org, err
   270  		}
   271  		serverCerts = append(serverCerts, serverCert{keyPEM, certPEM})
   272  	}
   273  	//loop through and load clients
   274  	var clientCerts = []tls.Certificate{}
   275  	for j := 1; j <= numServerCerts; j++ {
   276  		clientCert, err := loadTLSKeyPairFromFile(fmt.Sprintf(orgClientKey, parent, j),
   277  			fmt.Sprintf(orgClientCert, parent, j))
   278  		if err != nil {
   279  			return org, err
   280  		}
   281  		clientCerts = append(clientCerts, clientCert)
   282  	}
   283  	//loop through and load child orgs
   284  	var childOrgs = []testOrg{}
   285  
   286  	for k := 1; k <= numChildOrgs; k++ {
   287  		childOrg, err := loadChildOrg(parent, k)
   288  		if err != nil {
   289  			return org, err
   290  		}
   291  		childOrgs = append(childOrgs, childOrg)
   292  	}
   293  
   294  	return testOrg{caPEM, serverCerts, clientCerts, childOrgs}, nil
   295  }
   296  
   297  //utility function to load crypto material for child organizations
   298  func loadChildOrg(parent, child int) (testOrg, error) {
   299  
   300  	var org = testOrg{}
   301  	//load the CA
   302  	caPEM, err := ioutil.ReadFile(fmt.Sprintf(childCACert, parent, child))
   303  	if err != nil {
   304  		return org, err
   305  	}
   306  	//loop through and load servers
   307  	var serverCerts = []serverCert{}
   308  	for i := 1; i <= numServerCerts; i++ {
   309  		keyPEM, err := ioutil.ReadFile(fmt.Sprintf(childServerKey, parent, child, i))
   310  		if err != nil {
   311  			return org, err
   312  		}
   313  		certPEM, err := ioutil.ReadFile(fmt.Sprintf(childServerCert, parent, child, i))
   314  		if err != nil {
   315  			return org, err
   316  		}
   317  		serverCerts = append(serverCerts, serverCert{keyPEM, certPEM})
   318  	}
   319  	//loop through and load clients
   320  	var clientCerts = []tls.Certificate{}
   321  	for j := 1; j <= numServerCerts; j++ {
   322  		clientCert, err := loadTLSKeyPairFromFile(fmt.Sprintf(childClientKey, parent, child, j),
   323  			fmt.Sprintf(childClientCert, parent, child, j))
   324  		if err != nil {
   325  			return org, err
   326  		}
   327  		clientCerts = append(clientCerts, clientCert)
   328  	}
   329  	return testOrg{caPEM, serverCerts, clientCerts, []testOrg{}}, nil
   330  }
   331  
   332  //loadTLSKeyPairFromFile creates a tls.Certificate from PEM-encoded key and cert files
   333  func loadTLSKeyPairFromFile(keyFile, certFile string) (tls.Certificate, error) {
   334  
   335  	certPEMBlock, err := ioutil.ReadFile(certFile)
   336  	keyPEMBlock, err := ioutil.ReadFile(keyFile)
   337  	cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
   338  
   339  	if err != nil {
   340  		return tls.Certificate{}, err
   341  	}
   342  	return cert, nil
   343  }
   344  
   345  func TestNewGRPCServerInvalidParameters(t *testing.T) {
   346  
   347  	t.Parallel()
   348  	//missing address
   349  	_, err := comm.NewGRPCServer("", comm.SecureServerConfig{UseTLS: false})
   350  	//check for error
   351  	msg := "Missing address parameter"
   352  	assert.EqualError(t, err, msg)
   353  	if err != nil {
   354  		t.Log(err.Error())
   355  	}
   356  
   357  	//missing port
   358  	_, err = comm.NewGRPCServer("abcdef", comm.SecureServerConfig{UseTLS: false})
   359  	//check for error
   360  	msg = "listen tcp: missing port in address abcdef"
   361  	assert.EqualError(t, err, msg)
   362  	if err != nil {
   363  		t.Log(err.Error())
   364  	}
   365  
   366  	//bad port
   367  	_, err = comm.NewGRPCServer("localhost:1BBB", comm.SecureServerConfig{UseTLS: false})
   368  	//check for error
   369  	msgs := [2]string{"listen tcp: lookup tcp/1BBB: nodename nor servname provided, or not known",
   370  		"listen tcp: unknown port tcp/1BBB"} //different error on MacOS and in Docker
   371  
   372  	if assert.Error(t, err, "%s or %s expected", msgs[0], msgs[1]) {
   373  		assert.Contains(t, msgs, err.Error())
   374  	}
   375  	if err != nil {
   376  		t.Log(err.Error())
   377  	}
   378  
   379  	//bad hostname
   380  	_, err = comm.NewGRPCServer("hostdoesnotexist.localdomain:9050",
   381  		comm.SecureServerConfig{UseTLS: false})
   382  	/*
   383  		We cannot check for a specific error message due to the fact that some
   384  		systems will automatically resolve unknown host names to a "search"
   385  		address so we just check to make sure that an error was returned
   386  	*/
   387  	assert.Error(t, err, "%s error expected", msg)
   388  	if err != nil {
   389  		t.Log(err.Error())
   390  	}
   391  
   392  	//address in use
   393  	_, err = comm.NewGRPCServer(":9040", comm.SecureServerConfig{UseTLS: false})
   394  	_, err = comm.NewGRPCServer(":9040", comm.SecureServerConfig{UseTLS: false})
   395  	//check for error
   396  	msg = "listen tcp :9040: bind: address already in use"
   397  	assert.EqualError(t, err, msg)
   398  	if err != nil {
   399  		t.Log(err.Error())
   400  	}
   401  
   402  	//missing serverCertificate
   403  	_, err = comm.NewGRPCServer(":9041",
   404  		comm.SecureServerConfig{UseTLS: true, ServerCertificate: []byte{}})
   405  	//check for error
   406  	msg = "secureConfig must contain both ServerKey and " +
   407  		"ServerCertificate when UseTLS is true"
   408  	assert.EqualError(t, err, msg)
   409  	if err != nil {
   410  		t.Log(err.Error())
   411  	}
   412  
   413  	//missing serverKey
   414  	_, err = comm.NewGRPCServer(":9042",
   415  		comm.SecureServerConfig{UseTLS: true, ServerKey: []byte{}})
   416  	//check for error
   417  	assert.EqualError(t, err, msg)
   418  	if err != nil {
   419  		t.Log(err.Error())
   420  	}
   421  
   422  	//bad serverKey
   423  	_, err = comm.NewGRPCServer(":9043",
   424  		comm.SecureServerConfig{
   425  			UseTLS:            true,
   426  			ServerCertificate: []byte(selfSignedCertPEM),
   427  			ServerKey:         []byte{}})
   428  
   429  	//check for error
   430  	msg = "tls: failed to find any PEM data in key input"
   431  	assert.EqualError(t, err, msg)
   432  	if err != nil {
   433  		t.Log(err.Error())
   434  	}
   435  
   436  	//bad serverCertificate
   437  	_, err = comm.NewGRPCServer(":9044",
   438  		comm.SecureServerConfig{
   439  			UseTLS:            true,
   440  			ServerCertificate: []byte{},
   441  			ServerKey:         []byte(selfSignedKeyPEM)})
   442  	//check for error
   443  	msg = "tls: failed to find any PEM data in certificate input"
   444  	assert.EqualError(t, err, msg)
   445  	if err != nil {
   446  		t.Log(err.Error())
   447  	}
   448  
   449  	//bad clientRootCAs
   450  	/** TODO: revisit after figuring out why MSP does not serialize PEMs with type
   451  	_, err = comm.NewGRPCServer(":9045",
   452  		comm.SecureServerConfig{
   453  			UseTLS:            true,
   454  			ServerCertificate: []byte(selfSignedCertPEM),
   455  			ServerKey:         []byte(selfSignedKeyPEM),
   456  			RequireClientCert: true,
   457  			ClientRootCAs:     [][]byte{[]byte(pemNoCertificateHeader)}})
   458  	//check for error
   459  	msg = "Failed to append client root certificate(s): " +
   460  		"No client root certificates found"
   461  	assert.EqualError(t, err, msg)
   462  	if err != nil {
   463  		t.Log(err.Error())
   464  	}
   465  	*/
   466  
   467  	srv, err := comm.NewGRPCServer(":9046",
   468  		comm.SecureServerConfig{
   469  			UseTLS:            true,
   470  			ServerCertificate: []byte(selfSignedCertPEM),
   471  			ServerKey:         []byte(selfSignedKeyPEM),
   472  			RequireClientCert: true})
   473  	badRootCAs := [][]byte{[]byte(badPEM)}
   474  	err = srv.SetClientRootCAs(badRootCAs)
   475  	//check for error
   476  	msg = "Failed to set client root certificate(s): " +
   477  		"asn1: syntax error: data truncated"
   478  	assert.EqualError(t, err, msg)
   479  	if err != nil {
   480  		t.Log(err.Error())
   481  	}
   482  }
   483  
   484  func TestNewGRPCServer(t *testing.T) {
   485  
   486  	t.Parallel()
   487  	testAddress := "localhost:9053"
   488  	srv, err := comm.NewGRPCServer(testAddress,
   489  		comm.SecureServerConfig{UseTLS: false})
   490  	//check for error
   491  	if err != nil {
   492  		t.Fatalf("Failed to return new GRPC server: %v", err)
   493  	}
   494  
   495  	//make sure our properties are as expected
   496  	//resolve the address
   497  	addr, err := net.ResolveTCPAddr("tcp", testAddress)
   498  	assert.Equal(t, srv.Address(), addr.String())
   499  	assert.Equal(t, srv.Listener().Addr().String(), addr.String())
   500  
   501  	//TlSEnabled should be false
   502  	assert.Equal(t, srv.TLSEnabled(), false)
   503  
   504  	//register the GRPC test server
   505  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   506  
   507  	//start the server
   508  	go srv.Start()
   509  
   510  	defer srv.Stop()
   511  	//should not be needed
   512  	time.Sleep(10 * time.Millisecond)
   513  
   514  	//GRPC client options
   515  	var dialOptions []grpc.DialOption
   516  	dialOptions = append(dialOptions, grpc.WithInsecure())
   517  
   518  	//invoke the EmptyCall service
   519  	_, err = invokeEmptyCall(testAddress, dialOptions)
   520  
   521  	if err != nil {
   522  		t.Fatalf("GRPC client failed to invoke the EmptyCall service on %s: %v",
   523  			testAddress, err)
   524  	} else {
   525  		t.Log("GRPC client successfully invoked the EmptyCall service: " + testAddress)
   526  	}
   527  
   528  }
   529  
   530  func TestNewGRPCServerFromListener(t *testing.T) {
   531  
   532  	t.Parallel()
   533  	testAddress := "localhost:9054"
   534  	//create our listener
   535  	lis, err := net.Listen("tcp", testAddress)
   536  
   537  	if err != nil {
   538  		t.Fatalf("Failed to create listener: %v", err)
   539  	}
   540  
   541  	srv, err := comm.NewGRPCServerFromListener(lis,
   542  		comm.SecureServerConfig{UseTLS: false})
   543  	//check for error
   544  	if err != nil {
   545  		t.Fatalf("Failed to return new GRPC server: %v", err)
   546  	}
   547  
   548  	//make sure our properties are as expected
   549  	//resolve the address
   550  	addr, err := net.ResolveTCPAddr("tcp", testAddress)
   551  	assert.Equal(t, srv.Address(), addr.String())
   552  	assert.Equal(t, srv.Listener().Addr().String(), addr.String())
   553  
   554  	//TlSEnabled should be false
   555  	assert.Equal(t, srv.TLSEnabled(), false)
   556  
   557  	//register the GRPC test server
   558  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   559  
   560  	//start the server
   561  	go srv.Start()
   562  
   563  	defer srv.Stop()
   564  	//should not be needed
   565  	time.Sleep(10 * time.Millisecond)
   566  
   567  	//GRPC client options
   568  	var dialOptions []grpc.DialOption
   569  	dialOptions = append(dialOptions, grpc.WithInsecure())
   570  
   571  	//invoke the EmptyCall service
   572  	_, err = invokeEmptyCall(testAddress, dialOptions)
   573  
   574  	if err != nil {
   575  		t.Fatalf("GRPC client failed to invoke the EmptyCall service on %s: %v",
   576  			testAddress, err)
   577  	} else {
   578  		t.Log("GRPC client successfully invoked the EmptyCall service: " + testAddress)
   579  	}
   580  }
   581  
   582  func TestNewSecureGRPCServer(t *testing.T) {
   583  
   584  	t.Parallel()
   585  	testAddress := "localhost:9055"
   586  	srv, err := comm.NewGRPCServer(testAddress, comm.SecureServerConfig{
   587  		UseTLS:            true,
   588  		ServerCertificate: []byte(selfSignedCertPEM),
   589  		ServerKey:         []byte(selfSignedKeyPEM),
   590  	})
   591  	//check for error
   592  	if err != nil {
   593  		t.Fatalf("Failed to return new GRPC server: %v", err)
   594  	}
   595  
   596  	//make sure our properties are as expected
   597  	//resolve the address
   598  	addr, err := net.ResolveTCPAddr("tcp", testAddress)
   599  	assert.Equal(t, srv.Address(), addr.String())
   600  	assert.Equal(t, srv.Listener().Addr().String(), addr.String())
   601  
   602  	//check the server certificate
   603  	cert, _ := tls.X509KeyPair([]byte(selfSignedCertPEM), []byte(selfSignedKeyPEM))
   604  	assert.Equal(t, srv.ServerCertificate(), cert)
   605  
   606  	//TlSEnabled should be true
   607  	assert.Equal(t, srv.TLSEnabled(), true)
   608  
   609  	//register the GRPC test server
   610  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   611  
   612  	//start the server
   613  	go srv.Start()
   614  
   615  	defer srv.Stop()
   616  	//should not be needed
   617  	time.Sleep(10 * time.Millisecond)
   618  
   619  	//create the client credentials
   620  	certPool := x509.NewCertPool()
   621  
   622  	if !certPool.AppendCertsFromPEM([]byte(selfSignedCertPEM)) {
   623  
   624  		t.Fatal("Failed to append certificate to client credentials")
   625  	}
   626  
   627  	creds := credentials.NewClientTLSFromCert(certPool, "")
   628  
   629  	//GRPC client options
   630  	var dialOptions []grpc.DialOption
   631  	dialOptions = append(dialOptions, grpc.WithTransportCredentials(creds))
   632  
   633  	//invoke the EmptyCall service
   634  	_, err = invokeEmptyCall(testAddress, dialOptions)
   635  
   636  	if err != nil {
   637  		t.Fatalf("GRPC client failed to invoke the EmptyCall service on %s: %v",
   638  			testAddress, err)
   639  	} else {
   640  		t.Log("GRPC client successfully invoked the EmptyCall service: " + testAddress)
   641  	}
   642  }
   643  
   644  func TestNewSecureGRPCServerFromListener(t *testing.T) {
   645  
   646  	t.Parallel()
   647  	testAddress := "localhost:9056"
   648  	//create our listener
   649  	lis, err := net.Listen("tcp", testAddress)
   650  
   651  	if err != nil {
   652  		t.Fatalf("Failed to create listener: %v", err)
   653  	}
   654  
   655  	srv, err := comm.NewGRPCServerFromListener(lis, comm.SecureServerConfig{
   656  		UseTLS:            true,
   657  		ServerCertificate: []byte(selfSignedCertPEM),
   658  		ServerKey:         []byte(selfSignedKeyPEM),
   659  	})
   660  	//check for error
   661  	if err != nil {
   662  		t.Fatalf("Failed to return new GRPC server: %v", err)
   663  	}
   664  
   665  	//make sure our properties are as expected
   666  	//resolve the address
   667  	addr, err := net.ResolveTCPAddr("tcp", testAddress)
   668  	assert.Equal(t, srv.Address(), addr.String())
   669  	assert.Equal(t, srv.Listener().Addr().String(), addr.String())
   670  
   671  	//check the server certificate
   672  	cert, _ := tls.X509KeyPair([]byte(selfSignedCertPEM), []byte(selfSignedKeyPEM))
   673  	assert.Equal(t, srv.ServerCertificate(), cert)
   674  
   675  	//TlSEnabled should be true
   676  	assert.Equal(t, srv.TLSEnabled(), true)
   677  
   678  	//register the GRPC test server
   679  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   680  
   681  	//start the server
   682  	go srv.Start()
   683  
   684  	defer srv.Stop()
   685  	//should not be needed
   686  	time.Sleep(10 * time.Millisecond)
   687  
   688  	//create the client credentials
   689  	certPool := x509.NewCertPool()
   690  
   691  	if !certPool.AppendCertsFromPEM([]byte(selfSignedCertPEM)) {
   692  
   693  		t.Fatal("Failed to append certificate to client credentials")
   694  	}
   695  
   696  	creds := credentials.NewClientTLSFromCert(certPool, "")
   697  
   698  	//GRPC client options
   699  	var dialOptions []grpc.DialOption
   700  	dialOptions = append(dialOptions, grpc.WithTransportCredentials(creds))
   701  
   702  	//invoke the EmptyCall service
   703  	_, err = invokeEmptyCall(testAddress, dialOptions)
   704  
   705  	if err != nil {
   706  		t.Fatalf("GRPC client failed to invoke the EmptyCall service on %s: %v",
   707  			testAddress, err)
   708  	} else {
   709  		t.Log("GRPC client successfully invoked the EmptyCall service: " + testAddress)
   710  	}
   711  }
   712  
   713  //prior tests used self-signed certficates loaded by the GRPCServer and the test client
   714  //here we'll use certificates signed by certificate authorities
   715  func TestWithSignedRootCertificates(t *testing.T) {
   716  
   717  	t.Parallel()
   718  	//use Org1 testdata
   719  	fileBase := "Org1"
   720  	certPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-server1-cert.pem"))
   721  	keyPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-server1-key.pem"))
   722  	caPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-cert.pem"))
   723  
   724  	if err != nil {
   725  		t.Fatalf("Failed to load test certificates: %v", err)
   726  	}
   727  	testAddress := "localhost:9057"
   728  	//create our listener
   729  	lis, err := net.Listen("tcp", testAddress)
   730  
   731  	if err != nil {
   732  		t.Fatalf("Failed to create listener: %v", err)
   733  	}
   734  
   735  	srv, err := comm.NewGRPCServerFromListener(lis, comm.SecureServerConfig{
   736  		UseTLS:            true,
   737  		ServerCertificate: certPEMBlock,
   738  		ServerKey:         keyPEMBlock,
   739  	})
   740  	//check for error
   741  	if err != nil {
   742  		t.Fatalf("Failed to return new GRPC server: %v", err)
   743  	}
   744  
   745  	//register the GRPC test server
   746  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   747  
   748  	//start the server
   749  	go srv.Start()
   750  
   751  	defer srv.Stop()
   752  	//should not be needed
   753  	time.Sleep(10 * time.Millisecond)
   754  
   755  	//create a CertPool for use by the client with the server cert only
   756  	certPoolServer, err := createCertPool([][]byte{certPEMBlock})
   757  	if err != nil {
   758  		t.Fatalf("Failed to load root certificates into pool: %v", err)
   759  	}
   760  	//create the client credentials
   761  	creds := credentials.NewClientTLSFromCert(certPoolServer, "")
   762  
   763  	//GRPC client options
   764  	var dialOptions []grpc.DialOption
   765  	dialOptions = append(dialOptions, grpc.WithTransportCredentials(creds))
   766  
   767  	//invoke the EmptyCall service
   768  	_, err = invokeEmptyCall(testAddress, dialOptions)
   769  
   770  	//client should not be able to connect
   771  	//for now we can only test that we get a timeout error
   772  	assert.EqualError(t, err, grpc.ErrClientConnTimeout.Error())
   773  	t.Logf("assert.EqualError: %s", err.Error())
   774  
   775  	//now use the CA certificate
   776  	certPoolCA := x509.NewCertPool()
   777  	if !certPoolCA.AppendCertsFromPEM(caPEMBlock) {
   778  		t.Fatal("Failed to append certificate to client credentials")
   779  	}
   780  	creds = credentials.NewClientTLSFromCert(certPoolCA, "")
   781  	var dialOptionsCA []grpc.DialOption
   782  	dialOptionsCA = append(dialOptionsCA, grpc.WithTransportCredentials(creds))
   783  
   784  	//invoke the EmptyCall service
   785  	_, err2 := invokeEmptyCall(testAddress, dialOptionsCA)
   786  
   787  	if err2 != nil {
   788  		t.Fatalf("GRPC client failed to invoke the EmptyCall service on %s: %v",
   789  			testAddress, err2)
   790  	} else {
   791  		t.Log("GRPC client successfully invoked the EmptyCall service: " + testAddress)
   792  	}
   793  }
   794  
   795  //here we'll use certificates signed by intermediate certificate authorities
   796  func TestWithSignedIntermediateCertificates(t *testing.T) {
   797  
   798  	t.Parallel()
   799  	//use Org1 testdata
   800  	fileBase := "Org1"
   801  	certPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-child1-server1-cert.pem"))
   802  	keyPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-child1-server1-key.pem"))
   803  	intermediatePEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-child1-cert.pem"))
   804  
   805  	if err != nil {
   806  		t.Fatalf("Failed to load test certificates: %v", err)
   807  	}
   808  	testAddress := "localhost:9058"
   809  	//create our listener
   810  	lis, err := net.Listen("tcp", testAddress)
   811  
   812  	if err != nil {
   813  		t.Fatalf("Failed to create listener: %v", err)
   814  	}
   815  
   816  	srv, err := comm.NewGRPCServerFromListener(lis, comm.SecureServerConfig{
   817  		UseTLS:            true,
   818  		ServerCertificate: certPEMBlock,
   819  		ServerKey:         keyPEMBlock,
   820  	})
   821  	//check for error
   822  	if err != nil {
   823  		t.Fatalf("Failed to return new GRPC server: %v", err)
   824  	}
   825  
   826  	//register the GRPC test server
   827  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   828  
   829  	//start the server
   830  	go srv.Start()
   831  
   832  	defer srv.Stop()
   833  	//should not be needed
   834  	time.Sleep(10 * time.Millisecond)
   835  
   836  	//create a CertPool for use by the client with the server cert only
   837  	certPoolServer, err := createCertPool([][]byte{certPEMBlock})
   838  	if err != nil {
   839  		t.Fatalf("Failed to load root certificates into pool: %v", err)
   840  	}
   841  	//create the client credentials
   842  	creds := credentials.NewClientTLSFromCert(certPoolServer, "")
   843  
   844  	//GRPC client options
   845  	var dialOptions []grpc.DialOption
   846  	dialOptions = append(dialOptions, grpc.WithTransportCredentials(creds))
   847  
   848  	//invoke the EmptyCall service
   849  	_, err = invokeEmptyCall(testAddress, dialOptions)
   850  
   851  	//client should not be able to connect
   852  	//for now we can only test that we get a timeout error
   853  	assert.EqualError(t, err, grpc.ErrClientConnTimeout.Error())
   854  	t.Logf("assert.EqualError: %s", err.Error())
   855  
   856  	//now use the CA certificate
   857  
   858  	//create a CertPool for use by the client with the intermediate root CA
   859  	certPoolCA, err := createCertPool([][]byte{intermediatePEMBlock})
   860  	if err != nil {
   861  		t.Fatalf("Failed to load root certificates into pool: %v", err)
   862  	}
   863  
   864  	creds = credentials.NewClientTLSFromCert(certPoolCA, "")
   865  	var dialOptionsCA []grpc.DialOption
   866  	dialOptionsCA = append(dialOptionsCA, grpc.WithTransportCredentials(creds))
   867  
   868  	//invoke the EmptyCall service
   869  	_, err2 := invokeEmptyCall(testAddress, dialOptionsCA)
   870  
   871  	if err2 != nil {
   872  		t.Fatalf("GRPC client failed to invoke the EmptyCall service on %s: %v",
   873  			testAddress, err2)
   874  	} else {
   875  		t.Log("GRPC client successfully invoked the EmptyCall service: " + testAddress)
   876  	}
   877  }
   878  
   879  //utility function for testing client / server communication using TLS
   880  func runMutualAuth(t *testing.T, servers []testServer, trustedClients, unTrustedClients []*tls.Config) error {
   881  
   882  	//loop through all the test servers
   883  	for i := 0; i < len(servers); i++ {
   884  		//create listener
   885  		lis, err := net.Listen("tcp", servers[i].address)
   886  		if err != nil {
   887  			return err
   888  		}
   889  
   890  		//create GRPCServer
   891  		srv, err := comm.NewGRPCServerFromListener(lis, servers[i].config)
   892  		if err != nil {
   893  			return err
   894  		}
   895  
   896  		//register the GRPC test server and start the GRPCServer
   897  		testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
   898  		go srv.Start()
   899  		defer srv.Stop()
   900  		//should not be needed but just in case
   901  		time.Sleep(10 * time.Millisecond)
   902  
   903  		//loop through all the trusted clients
   904  		for j := 0; j < len(trustedClients); j++ {
   905  			//invoke the EmptyCall service
   906  			_, err = invokeEmptyCall(servers[i].address,
   907  				[]grpc.DialOption{grpc.WithTransportCredentials(credentials.NewTLS(trustedClients[j]))})
   908  			//we expect success from trusted clients
   909  			if err != nil {
   910  				return err
   911  			} else {
   912  				t.Logf("Trusted client%d successfully connected to %s", j, servers[i].address)
   913  			}
   914  		}
   915  		//loop through all the untrusted clients
   916  		for k := 0; k < len(unTrustedClients); k++ {
   917  			//invoke the EmptyCall service
   918  			_, err = invokeEmptyCall(servers[i].address, []grpc.DialOption{grpc.WithTransportCredentials(credentials.NewTLS(unTrustedClients[k]))})
   919  			//we expect failure from untrusted clients
   920  			if err != nil {
   921  				t.Logf("Untrusted client%d was correctly rejected by %s", k, servers[i].address)
   922  			} else {
   923  				return fmt.Errorf("Untrusted client %d should not have been able to connect to %s", k,
   924  					servers[i].address)
   925  			}
   926  		}
   927  	}
   928  
   929  	return nil
   930  }
   931  
   932  func TestMutualAuth(t *testing.T) {
   933  
   934  	t.Parallel()
   935  	var tests = []struct {
   936  		name             string
   937  		servers          []testServer
   938  		trustedClients   []*tls.Config
   939  		unTrustedClients []*tls.Config
   940  	}{
   941  		{
   942  			name:             "ClientAuthRequiredWithSingleOrg",
   943  			servers:          testOrgs[0].testServers(9060, [][]byte{}),
   944  			trustedClients:   testOrgs[0].trustedClients([][]byte{}),
   945  			unTrustedClients: testOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}),
   946  		},
   947  		{
   948  			name:             "ClientAuthRequiredWithChildClientOrg",
   949  			servers:          testOrgs[0].testServers(9070, [][]byte{testOrgs[0].childOrgs[0].rootCA}),
   950  			trustedClients:   testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA}),
   951  			unTrustedClients: testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}),
   952  		},
   953  		{
   954  			name: "ClientAuthRequiredWithMultipleChildClientOrgs",
   955  			servers: testOrgs[0].testServers(9080, append([][]byte{},
   956  				testOrgs[0].childOrgs[0].rootCA, testOrgs[0].childOrgs[1].rootCA)),
   957  			trustedClients: append(append([]*tls.Config{},
   958  				testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})...),
   959  				testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})...),
   960  			unTrustedClients: testOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}),
   961  		},
   962  		{
   963  			name:             "ClientAuthRequiredWithDifferentServerAndClientOrgs",
   964  			servers:          testOrgs[0].testServers(9090, [][]byte{testOrgs[1].rootCA}),
   965  			trustedClients:   testOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}),
   966  			unTrustedClients: testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}),
   967  		},
   968  		{
   969  			name:             "ClientAuthRequiredWithDifferentServerAndChildClientOrgs",
   970  			servers:          testOrgs[1].testServers(9100, [][]byte{testOrgs[0].childOrgs[0].rootCA}),
   971  			trustedClients:   testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[1].rootCA}),
   972  			unTrustedClients: testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[1].rootCA}),
   973  		},
   974  	}
   975  
   976  	for _, test := range tests {
   977  		test := test
   978  		t.Run(test.name, func(t *testing.T) {
   979  			t.Parallel()
   980  			t.Logf("Running test %s ...", test.name)
   981  			testErr := runMutualAuth(t, test.servers, test.trustedClients, test.unTrustedClients)
   982  			if testErr != nil {
   983  				t.Fatalf("%s failed with error: %s", test.name, testErr.Error())
   984  			}
   985  		})
   986  	}
   987  
   988  }
   989  
   990  func TestAppendRemoveWithInvalidBytes(t *testing.T) {
   991  
   992  	// TODO: revisit when msp serialization without PEM type is resolved
   993  	t.Skip()
   994  	t.Parallel()
   995  
   996  	noPEMData := [][]byte{[]byte("badcert1"), []byte("badCert2")}
   997  
   998  	//get the config for one of our Org1 test servers
   999  	serverConfig := testOrgs[0].testServers(9200, [][]byte{})[0].config
  1000  	address := testOrgs[0].testServers(9200, [][]byte{})[0].address
  1001  
  1002  	//create a GRPCServer
  1003  	srv, err := comm.NewGRPCServer(address, serverConfig)
  1004  	if err != nil {
  1005  		t.Fatalf("Failed to create GRPCServer due to: %s", err.Error())
  1006  	}
  1007  
  1008  	//append/remove nonPEMData
  1009  	noCertsFound := "No client root certificates found"
  1010  	err = srv.AppendClientRootCAs(noPEMData)
  1011  	if err == nil {
  1012  		t.Fatalf("Expected error: %s", noCertsFound)
  1013  	}
  1014  	err = srv.RemoveClientRootCAs(noPEMData)
  1015  	if err == nil {
  1016  		t.Fatalf("Expected error: %s", noCertsFound)
  1017  	}
  1018  
  1019  	//apend/remove PEM without CERTIFICATE header
  1020  	err = srv.AppendClientRootCAs([][]byte{[]byte(pemNoCertificateHeader)})
  1021  	if err == nil {
  1022  		t.Fatalf("Expected error: %s", noCertsFound)
  1023  	}
  1024  
  1025  	err = srv.RemoveClientRootCAs([][]byte{[]byte(pemNoCertificateHeader)})
  1026  	if err == nil {
  1027  		t.Fatalf("Expected error: %s", noCertsFound)
  1028  	}
  1029  
  1030  	//append/remove bad PEM data
  1031  	err = srv.AppendClientRootCAs([][]byte{[]byte(badPEM)})
  1032  	if err == nil {
  1033  		t.Fatalf("Expected error parsing bad PEM data")
  1034  	}
  1035  
  1036  	err = srv.RemoveClientRootCAs([][]byte{[]byte(badPEM)})
  1037  	if err == nil {
  1038  		t.Fatalf("Expected error parsing bad PEM data")
  1039  	}
  1040  
  1041  }
  1042  
  1043  func TestAppendClientRootCAs(t *testing.T) {
  1044  
  1045  	t.Parallel()
  1046  	//get the config for one of our Org1 test servers
  1047  	serverConfig := testOrgs[0].testServers(9300, [][]byte{})[0].config
  1048  	address := testOrgs[0].testServers(9300, [][]byte{})[0].address
  1049  
  1050  	//create a GRPCServer
  1051  	srv, err := comm.NewGRPCServer(address, serverConfig)
  1052  	if err != nil {
  1053  		t.Fatalf("Failed to create GRPCServer due to: %s", err.Error())
  1054  	}
  1055  
  1056  	//register the GRPC test server and start the GRPCServer
  1057  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
  1058  	go srv.Start()
  1059  	defer srv.Stop()
  1060  	//should not be needed but just in case
  1061  	time.Sleep(10 * time.Millisecond)
  1062  
  1063  	//try to connect with untrusted clients from Org2 children
  1064  	clientConfig1 := testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1065  	clientConfig2 := testOrgs[1].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1066  	clientConfigs := []*tls.Config{clientConfig1, clientConfig2}
  1067  
  1068  	for i, clientConfig := range clientConfigs {
  1069  		//invoke the EmptyCall service
  1070  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1071  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1072  		//we expect failure as these are currently not trusted clients
  1073  		if err != nil {
  1074  			t.Logf("Untrusted client%d was correctly rejected by %s", i, address)
  1075  		} else {
  1076  			t.Fatalf("Untrusted client %d should not have been able to connect to %s", i,
  1077  				address)
  1078  		}
  1079  	}
  1080  
  1081  	//now append the root CAs for the untrusted clients
  1082  	err = srv.AppendClientRootCAs([][]byte{testOrgs[1].childOrgs[0].rootCA,
  1083  		testOrgs[1].childOrgs[1].rootCA})
  1084  	if err != nil {
  1085  		t.Fatal("Failed to append client root CAs")
  1086  	}
  1087  
  1088  	//now try to connect again
  1089  	for j, clientConfig := range clientConfigs {
  1090  		//invoke the EmptyCall service
  1091  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1092  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1093  		//we expect success as these are now trusted clients
  1094  		if err != nil {
  1095  			t.Fatalf("Now trusted client%d failed to connect to %s with error: %s",
  1096  				j, address, err.Error())
  1097  		} else {
  1098  			t.Logf("Now trusted client%d successfully connected to %s", j, address)
  1099  		}
  1100  	}
  1101  
  1102  }
  1103  
  1104  func TestRemoveClientRootCAs(t *testing.T) {
  1105  
  1106  	t.Parallel()
  1107  	//get the config for one of our Org1 test servers and include client CAs from
  1108  	//Org2 child orgs
  1109  	serverConfig := testOrgs[0].testServers(9301,
  1110  		[][]byte{testOrgs[1].childOrgs[0].rootCA,
  1111  			testOrgs[1].childOrgs[1].rootCA})[0].config
  1112  	address := testOrgs[0].testServers(9301, [][]byte{})[0].address
  1113  
  1114  	//create a GRPCServer
  1115  	srv, err := comm.NewGRPCServer(address, serverConfig)
  1116  	if err != nil {
  1117  		t.Fatalf("Failed to create GRPCServer due to: %s", err.Error())
  1118  	}
  1119  
  1120  	//register the GRPC test server and start the GRPCServer
  1121  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
  1122  	go srv.Start()
  1123  	defer srv.Stop()
  1124  	//should not be needed but just in case
  1125  	time.Sleep(10 * time.Millisecond)
  1126  
  1127  	//try to connect with trusted clients from Org2 children
  1128  	clientConfig1 := testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1129  	clientConfig2 := testOrgs[1].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1130  	clientConfigs := []*tls.Config{clientConfig1, clientConfig2}
  1131  
  1132  	for i, clientConfig := range clientConfigs {
  1133  		//invoke the EmptyCall service
  1134  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1135  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1136  
  1137  		//we expect success as these are trusted clients
  1138  		if err != nil {
  1139  			t.Fatalf("Trusted client%d failed to connect to %s with error: %s",
  1140  				i, address, err.Error())
  1141  		} else {
  1142  			t.Logf("Trusted client%d successfully connected to %s", i, address)
  1143  		}
  1144  	}
  1145  
  1146  	//now remove the root CAs for the untrusted clients
  1147  	err = srv.RemoveClientRootCAs([][]byte{testOrgs[1].childOrgs[0].rootCA,
  1148  		testOrgs[1].childOrgs[1].rootCA})
  1149  	if err != nil {
  1150  		t.Fatal("Failed to remove client root CAs")
  1151  	}
  1152  
  1153  	//now try to connect again
  1154  	for j, clientConfig := range clientConfigs {
  1155  		//invoke the EmptyCall service
  1156  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1157  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1158  		//we expect failure as these are now untrusted clients
  1159  		if err != nil {
  1160  			t.Logf("Now untrusted client%d was correctly rejected by %s", j, address)
  1161  		} else {
  1162  			t.Fatalf("Now untrusted client %d should not have been able to connect to %s", j,
  1163  				address)
  1164  		}
  1165  	}
  1166  
  1167  }
  1168  
  1169  //test for race conditions - test locally using "go test -race -run TestConcurrentAppendRemoveSet"
  1170  func TestConcurrentAppendRemoveSet(t *testing.T) {
  1171  
  1172  	t.Parallel()
  1173  	//get the config for one of our Org1 test servers and include client CAs from
  1174  	//Org2 child orgs
  1175  	serverConfig := testOrgs[0].testServers(9302,
  1176  		[][]byte{testOrgs[1].childOrgs[0].rootCA,
  1177  			testOrgs[1].childOrgs[1].rootCA})[0].config
  1178  	address := testOrgs[0].testServers(9302, [][]byte{})[0].address
  1179  
  1180  	//create a GRPCServer
  1181  	srv, err := comm.NewGRPCServer(address, serverConfig)
  1182  	if err != nil {
  1183  		t.Fatalf("Failed to create GRPCServer due to: %s", err.Error())
  1184  	}
  1185  
  1186  	//register the GRPC test server and start the GRPCServer
  1187  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
  1188  	go srv.Start()
  1189  	defer srv.Stop()
  1190  
  1191  	//need to wait for the following go routines to finish
  1192  	var wg sync.WaitGroup
  1193  
  1194  	wg.Add(1)
  1195  	go func() {
  1196  		defer wg.Done()
  1197  		//now remove the root CAs for the untrusted clients
  1198  		err := srv.RemoveClientRootCAs([][]byte{testOrgs[1].childOrgs[0].rootCA,
  1199  			testOrgs[1].childOrgs[1].rootCA})
  1200  		if err != nil {
  1201  			t.Fatal("Failed to remove client root CAs")
  1202  		}
  1203  
  1204  	}()
  1205  
  1206  	wg.Add(1)
  1207  	go func() {
  1208  		defer wg.Done()
  1209  		//set client root CAs
  1210  		err := srv.SetClientRootCAs([][]byte{testOrgs[1].childOrgs[0].rootCA,
  1211  			testOrgs[1].childOrgs[1].rootCA})
  1212  		if err != nil {
  1213  			t.Fatal("Failed to set client root CAs")
  1214  		}
  1215  
  1216  	}()
  1217  
  1218  	//TODO: enable this after creating a custom type for grpc.TransportCredentials
  1219  	/*
  1220  		clientConfig := testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1221  		wg.Add(1)
  1222  		go func() {
  1223  			defer wg.Done()
  1224  			_, _ = invokeEmptyCall(address, []grpc.DialOption{
  1225  				grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1226  		}()
  1227  	*/
  1228  	wg.Add(1)
  1229  	go func() {
  1230  		defer wg.Done()
  1231  		//now append the root CAs for the untrusted clients
  1232  		err := srv.AppendClientRootCAs([][]byte{testOrgs[1].childOrgs[0].rootCA,
  1233  			testOrgs[1].childOrgs[1].rootCA})
  1234  		if err != nil {
  1235  			t.Fatal("Failed to append client root CAs")
  1236  		}
  1237  	}()
  1238  
  1239  	wg.Add(1)
  1240  	go func() {
  1241  		defer wg.Done()
  1242  		//set client root CAs
  1243  		err := srv.SetClientRootCAs([][]byte{testOrgs[1].childOrgs[0].rootCA,
  1244  			testOrgs[1].childOrgs[1].rootCA})
  1245  		if err != nil {
  1246  			t.Fatal("Failed to set client root CAs")
  1247  		}
  1248  
  1249  	}()
  1250  
  1251  	wg.Wait()
  1252  
  1253  }
  1254  
  1255  func TestSetClientRootCAs(t *testing.T) {
  1256  
  1257  	t.Parallel()
  1258  
  1259  	//get the config for one of our Org1 test servers
  1260  	serverConfig := testOrgs[0].testServers(9303, [][]byte{})[0].config
  1261  	address := testOrgs[0].testServers(9303, [][]byte{})[0].address
  1262  
  1263  	//create a GRPCServer
  1264  	srv, err := comm.NewGRPCServer(address, serverConfig)
  1265  	if err != nil {
  1266  		t.Fatalf("Failed to create GRPCServer due to: %s", err.Error())
  1267  	}
  1268  
  1269  	//register the GRPC test server and start the GRPCServer
  1270  	testpb.RegisterTestServiceServer(srv.Server(), &testServiceServer{})
  1271  	go srv.Start()
  1272  	defer srv.Stop()
  1273  	//should not be needed but just in case
  1274  	time.Sleep(10 * time.Millisecond)
  1275  
  1276  	//set up out test clients
  1277  	//Org1
  1278  	clientConfigOrg1Child1 := testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1279  	clientConfigOrg1Child2 := testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1280  	clientConfigsOrg1Children := []*tls.Config{clientConfigOrg1Child1, clientConfigOrg1Child2}
  1281  	org1ChildRootCAs := [][]byte{testOrgs[0].childOrgs[0].rootCA,
  1282  		testOrgs[0].childOrgs[1].rootCA}
  1283  	//Org2
  1284  	clientConfigOrg2Child1 := testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1285  	clientConfigOrg2Child2 := testOrgs[1].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})[0]
  1286  	clientConfigsOrg2Children := []*tls.Config{clientConfigOrg2Child1, clientConfigOrg2Child2}
  1287  	org2ChildRootCAs := [][]byte{testOrgs[1].childOrgs[0].rootCA,
  1288  		testOrgs[1].childOrgs[1].rootCA}
  1289  
  1290  	//initially set client CAs to Org1 children
  1291  	err = srv.SetClientRootCAs(org1ChildRootCAs)
  1292  	if err != nil {
  1293  		t.Fatalf("SetClientRootCAs failed due to: %s", err.Error())
  1294  	}
  1295  
  1296  	//clientConfigsOrg1Children are currently trusted
  1297  	for i, clientConfig := range clientConfigsOrg1Children {
  1298  		//invoke the EmptyCall service
  1299  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1300  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1301  
  1302  		//we expect success as these are trusted clients
  1303  		if err != nil {
  1304  			t.Fatalf("Trusted client%d failed to connect to %s with error: %s",
  1305  				i, address, err.Error())
  1306  		} else {
  1307  			t.Logf("Trusted client%d successfully connected to %s", i, address)
  1308  		}
  1309  	}
  1310  
  1311  	//clientConfigsOrg2Children are currently not trusted
  1312  	for j, clientConfig := range clientConfigsOrg2Children {
  1313  		//invoke the EmptyCall service
  1314  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1315  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1316  		//we expect failure as these are now untrusted clients
  1317  		if err != nil {
  1318  			t.Logf("Untrusted client%d was correctly rejected by %s", j, address)
  1319  		} else {
  1320  			t.Fatalf("Untrusted client %d should not have been able to connect to %s", j,
  1321  				address)
  1322  		}
  1323  	}
  1324  
  1325  	//now set client CAs to Org2 children
  1326  	err = srv.SetClientRootCAs(org2ChildRootCAs)
  1327  	if err != nil {
  1328  		t.Fatalf("SetClientRootCAs failed due to: %s", err.Error())
  1329  	}
  1330  
  1331  	//now reverse trusted and not trusted
  1332  	//clientConfigsOrg1Children are currently trusted
  1333  	for i, clientConfig := range clientConfigsOrg2Children {
  1334  		//invoke the EmptyCall service
  1335  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1336  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1337  
  1338  		//we expect success as these are trusted clients
  1339  		if err != nil {
  1340  			t.Fatalf("Trusted client%d failed to connect to %s with error: %s",
  1341  				i, address, err.Error())
  1342  		} else {
  1343  			t.Logf("Trusted client%d successfully connected to %s", i, address)
  1344  		}
  1345  	}
  1346  
  1347  	//clientConfigsOrg2Children are currently not trusted
  1348  	for j, clientConfig := range clientConfigsOrg1Children {
  1349  		//invoke the EmptyCall service
  1350  		_, err = invokeEmptyCall(address, []grpc.DialOption{
  1351  			grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))})
  1352  		//we expect failure as these are now untrusted clients
  1353  		if err != nil {
  1354  			t.Logf("Untrusted client%d was correctly rejected by %s", j, address)
  1355  		} else {
  1356  			t.Fatalf("Untrusted client %d should not have been able to connect to %s", j,
  1357  				address)
  1358  		}
  1359  	}
  1360  
  1361  }