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