github.com/lzy4123/fabric@v2.1.1+incompatible/internal/pkg/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 "bytes" 11 "context" 12 "crypto/tls" 13 "crypto/x509" 14 "fmt" 15 "io" 16 "io/ioutil" 17 "log" 18 "net" 19 "path/filepath" 20 "sync/atomic" 21 "testing" 22 "time" 23 24 "github.com/hyperledger/fabric/common/crypto/tlsgen" 25 "github.com/hyperledger/fabric/internal/pkg/comm" 26 "github.com/hyperledger/fabric/internal/pkg/comm/testpb" 27 "github.com/pkg/errors" 28 "github.com/stretchr/testify/assert" 29 "google.golang.org/grpc" 30 "google.golang.org/grpc/codes" 31 "google.golang.org/grpc/credentials" 32 "google.golang.org/grpc/status" 33 ) 34 35 // Embedded certificates for testing 36 // The self-signed cert expires in 2028 37 var selfSignedKeyPEM = `-----BEGIN EC PRIVATE KEY----- 38 MHcCAQEEIMLemLh3+uDzww1pvqP6Xj2Z0Kc6yqf3RxyfTBNwRuuyoAoGCCqGSM49 39 AwEHoUQDQgAEDB3l94vM7EqKr2L/vhqU5IsEub0rviqCAaWGiVAPp3orb/LJqFLS 40 yo/k60rhUiir6iD4S4pb5TEb2ouWylQI3A== 41 -----END EC PRIVATE KEY----- 42 ` 43 var selfSignedCertPEM = `-----BEGIN CERTIFICATE----- 44 MIIBdDCCARqgAwIBAgIRAKCiW5r6W32jGUn+l9BORMAwCgYIKoZIzj0EAwIwEjEQ 45 MA4GA1UEChMHQWNtZSBDbzAeFw0xODA4MjExMDI1MzJaFw0yODA4MTgxMDI1MzJa 46 MBIxEDAOBgNVBAoTB0FjbWUgQ28wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQM 47 HeX3i8zsSoqvYv++GpTkiwS5vSu+KoIBpYaJUA+neitv8smoUtLKj+TrSuFSKKvq 48 IPhLilvlMRvai5bKVAjco1EwTzAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYI 49 KwYBBQUHAwEwDAYDVR0TAQH/BAIwADAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8A 50 AAEwCgYIKoZIzj0EAwIDSAAwRQIgOaYc3pdGf2j0uXRyvdBJq2PlK9FkgvsUjXOT 51 bQ9fWRkCIQCr1FiRRzapgtrnttDn3O2fhLlbrw67kClzY8pIIN42Qw== 52 -----END CERTIFICATE----- 53 ` 54 55 var badPEM = `-----BEGIN CERTIFICATE----- 56 MIICRDCCAemgAwIBAgIJALwW//dz2ZBvMAoGCCqGSM49BAMCMH4xCzAJBgNVBAYT 57 AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2Nv 58 MRgwFgYDVQQKDA9MaW51eEZvdW5kYXRpb24xFDASBgNVBAsMC0h5cGVybGVkZ2Vy 59 MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTYxMjA0MjIzMDE4WhcNMjYxMjAyMjIz 60 MDE4WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UE 61 BwwNU2FuIEZyYW5jaXNjbzEYMBYGA1UECgwPTGludXhGb3VuZGF0aW9uMRQwEgYD 62 VQQLDAtIeXBlcmxlZGdlcjESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0C 63 -----END CERTIFICATE----- 64 ` 65 66 var pemNoCertificateHeader = `-----BEGIN NOCERT----- 67 MIICRDCCAemgAwIBAgIJALwW//dz2ZBvMAoGCCqGSM49BAMCMH4xCzAJBgNVBAYT 68 AlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2Nv 69 MRgwFgYDVQQKDA9MaW51eEZvdW5kYXRpb24xFDASBgNVBAsMC0h5cGVybGVkZ2Vy 70 MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTYxMjA0MjIzMDE4WhcNMjYxMjAyMjIz 71 MDE4WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UE 72 BwwNU2FuIEZyYW5jaXNjbzEYMBYGA1UECgwPTGludXhGb3VuZGF0aW9uMRQwEgYD 73 VQQLDAtIeXBlcmxlZGdlcjESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0C 74 AQYIKoZIzj0DAQcDQgAEu2FEZVSr30Afey6dwcypeg5P+BuYx5JSYdG0/KJIBjWK 75 nzYo7FEmgMir7GbNh4pqA8KFrJZkPuxMgnEJBZTv+6NQME4wHQYDVR0OBBYEFAWO 76 4bfTEr2R6VYzQYrGk/2VWmtYMB8GA1UdIwQYMBaAFAWO4bfTEr2R6VYzQYrGk/2V 77 WmtYMAwGA1UdEwQFMAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhAIelqGdxPMHmQqRF 78 zA85vv7JhfMkvZYGPELC7I2K8V7ZAiEA9KcthV3HtDXKNDsA6ULT+qUkyoHRzCzr 79 A4QaL2VU6i4= 80 -----END NOCERT----- 81 ` 82 83 var testOrgs = []testOrg{} 84 85 func init() { 86 //load up crypto material for test orgs 87 for i := 1; i <= numOrgs; i++ { 88 testOrg, err := loadOrg(i) 89 if err != nil { 90 log.Fatalf("Failed to load test organizations due to error: %s", err.Error()) 91 } 92 testOrgs = append(testOrgs, testOrg) 93 } 94 } 95 96 // test servers to be registered with the GRPCServer 97 type emptyServiceServer struct{} 98 99 func (ess *emptyServiceServer) EmptyCall(context.Context, *testpb.Empty) (*testpb.Empty, error) { 100 return new(testpb.Empty), nil 101 } 102 103 func (esss *emptyServiceServer) EmptyStream(stream testpb.EmptyService_EmptyStreamServer) error { 104 for { 105 _, err := stream.Recv() 106 if err == io.EOF { 107 return nil 108 } 109 if err != nil { 110 return err 111 } 112 if err := stream.Send(&testpb.Empty{}); err != nil { 113 return err 114 } 115 116 } 117 } 118 119 // invoke the EmptyCall RPC 120 func invokeEmptyCall(address string, dialOptions ...grpc.DialOption) (*testpb.Empty, error) { 121 ctx, cancel := context.WithTimeout(context.Background(), testTimeout) 122 defer cancel() 123 //create GRPC client conn 124 clientConn, err := grpc.DialContext(ctx, address, dialOptions...) 125 if err != nil { 126 return nil, err 127 } 128 defer clientConn.Close() 129 130 //create GRPC client 131 client := testpb.NewEmptyServiceClient(clientConn) 132 133 //invoke service 134 empty, err := client.EmptyCall(context.Background(), new(testpb.Empty)) 135 if err != nil { 136 return nil, err 137 } 138 139 return empty, nil 140 } 141 142 // invoke the EmptyStream RPC 143 func invokeEmptyStream(address string, dialOptions ...grpc.DialOption) (*testpb.Empty, error) { 144 ctx, cancel := context.WithTimeout(context.Background(), testTimeout) 145 defer cancel() 146 //create GRPC client conn 147 clientConn, err := grpc.DialContext(ctx, address, dialOptions...) 148 if err != nil { 149 return nil, err 150 } 151 defer clientConn.Close() 152 153 stream, err := testpb.NewEmptyServiceClient(clientConn).EmptyStream(ctx) 154 if err != nil { 155 return nil, err 156 } 157 158 var msg *testpb.Empty 159 var streamErr error 160 161 waitc := make(chan struct{}) 162 go func() { 163 for { 164 in, err := stream.Recv() 165 if err == io.EOF { 166 close(waitc) 167 return 168 } 169 if err != nil { 170 streamErr = err 171 close(waitc) 172 return 173 } 174 msg = in 175 } 176 }() 177 178 // TestServerInterceptors adds an interceptor that does not call the target 179 // StreamHandler and returns an error so Send can return with an io.EOF since 180 // the server side has already terminated. Whether or not we get an error 181 // depends on timing. 182 err = stream.Send(&testpb.Empty{}) 183 if err != nil && err != io.EOF { 184 return nil, fmt.Errorf("stream send failed: %s", err) 185 } 186 187 stream.CloseSend() 188 <-waitc 189 return msg, streamErr 190 } 191 192 const ( 193 numOrgs = 2 194 numChildOrgs = 2 195 numServerCerts = 2 196 ) 197 198 // string for cert filenames 199 var ( 200 orgCACert = filepath.Join("testdata", "certs", "Org%d-cert.pem") 201 orgServerKey = filepath.Join("testdata", "certs", "Org%d-server%d-key.pem") 202 orgServerCert = filepath.Join("testdata", "certs", "Org%d-server%d-cert.pem") 203 orgClientKey = filepath.Join("testdata", "certs", "Org%d-client%d-key.pem") 204 orgClientCert = filepath.Join("testdata", "certs", "Org%d-client%d-cert.pem") 205 childCACert = filepath.Join("testdata", "certs", "Org%d-child%d-cert.pem") 206 childServerKey = filepath.Join("testdata", "certs", "Org%d-child%d-server%d-key.pem") 207 childServerCert = filepath.Join("testdata", "certs", "Org%d-child%d-server%d-cert.pem") 208 childClientKey = filepath.Join("testdata", "certs", "Org%d-child%d-client%d-key.pem") 209 childClientCert = filepath.Join("testdata", "certs", "Org%d-child%d-client%d-cert.pem") 210 ) 211 212 type testServer struct { 213 config comm.ServerConfig 214 } 215 216 type serverCert struct { 217 keyPEM []byte 218 certPEM []byte 219 } 220 221 type testOrg struct { 222 rootCA []byte 223 serverCerts []serverCert 224 clientCerts []tls.Certificate 225 childOrgs []testOrg 226 } 227 228 // return *X509.CertPool for the rootCA of the org 229 func (org *testOrg) rootCertPool() *x509.CertPool { 230 certPool := x509.NewCertPool() 231 certPool.AppendCertsFromPEM(org.rootCA) 232 return certPool 233 } 234 235 // return testServers for the org 236 func (org *testOrg) testServers(clientRootCAs [][]byte) []testServer { 237 clientRootCAs = append(clientRootCAs, org.rootCA) 238 239 // loop through the serverCerts and create testServers 240 var testServers = []testServer{} 241 for _, serverCert := range org.serverCerts { 242 testServer := testServer{ 243 comm.ServerConfig{ 244 ConnectionTimeout: 250 * time.Millisecond, 245 SecOpts: comm.SecureOptions{ 246 UseTLS: true, 247 Certificate: serverCert.certPEM, 248 Key: serverCert.keyPEM, 249 RequireClientCert: true, 250 ClientRootCAs: clientRootCAs, 251 }, 252 }, 253 } 254 testServers = append(testServers, testServer) 255 } 256 return testServers 257 } 258 259 // return trusted clients for the org 260 func (org *testOrg) trustedClients(serverRootCAs [][]byte) []*tls.Config { 261 // if we have any additional server root CAs add them to the certPool 262 certPool := org.rootCertPool() 263 for _, serverRootCA := range serverRootCAs { 264 certPool.AppendCertsFromPEM(serverRootCA) 265 } 266 267 // loop through the clientCerts and create tls.Configs 268 var trustedClients = []*tls.Config{} 269 for _, clientCert := range org.clientCerts { 270 trustedClient := &tls.Config{ 271 Certificates: []tls.Certificate{clientCert}, 272 RootCAs: certPool, 273 } 274 trustedClients = append(trustedClients, trustedClient) 275 } 276 return trustedClients 277 } 278 279 // createCertPool creates an x509.CertPool from an array of PEM-encoded certificates 280 func createCertPool(rootCAs [][]byte) (*x509.CertPool, error) { 281 certPool := x509.NewCertPool() 282 for _, rootCA := range rootCAs { 283 if !certPool.AppendCertsFromPEM(rootCA) { 284 return nil, errors.New("Failed to load root certificates") 285 } 286 } 287 return certPool, nil 288 } 289 290 // utility function to load crypto material for organizations 291 func loadOrg(parent int) (testOrg, error) { 292 var org = testOrg{} 293 // load the CA 294 caPEM, err := ioutil.ReadFile(fmt.Sprintf(orgCACert, parent)) 295 if err != nil { 296 return org, err 297 } 298 299 // loop through and load servers 300 var serverCerts = []serverCert{} 301 for i := 1; i <= numServerCerts; i++ { 302 keyPEM, err := ioutil.ReadFile(fmt.Sprintf(orgServerKey, parent, i)) 303 if err != nil { 304 return org, err 305 } 306 certPEM, err := ioutil.ReadFile(fmt.Sprintf(orgServerCert, parent, i)) 307 if err != nil { 308 return org, err 309 } 310 serverCerts = append(serverCerts, serverCert{keyPEM, certPEM}) 311 } 312 313 // loop through and load clients 314 var clientCerts = []tls.Certificate{} 315 for j := 1; j <= numServerCerts; j++ { 316 clientCert, err := loadTLSKeyPairFromFile(fmt.Sprintf(orgClientKey, parent, j), 317 fmt.Sprintf(orgClientCert, parent, j)) 318 if err != nil { 319 return org, err 320 } 321 clientCerts = append(clientCerts, clientCert) 322 } 323 324 // loop through and load child orgs 325 var childOrgs = []testOrg{} 326 for k := 1; k <= numChildOrgs; k++ { 327 childOrg, err := loadChildOrg(parent, k) 328 if err != nil { 329 return org, err 330 } 331 childOrgs = append(childOrgs, childOrg) 332 } 333 334 return testOrg{caPEM, serverCerts, clientCerts, childOrgs}, nil 335 } 336 337 // utility function to load crypto material for child organizations 338 func loadChildOrg(parent, child int) (testOrg, error) { 339 // load the CA 340 caPEM, err := ioutil.ReadFile(fmt.Sprintf(childCACert, parent, child)) 341 if err != nil { 342 return testOrg{}, err 343 } 344 345 // loop through and load servers 346 var serverCerts = []serverCert{} 347 for i := 1; i <= numServerCerts; i++ { 348 keyPEM, err := ioutil.ReadFile(fmt.Sprintf(childServerKey, parent, child, i)) 349 if err != nil { 350 return testOrg{}, err 351 } 352 certPEM, err := ioutil.ReadFile(fmt.Sprintf(childServerCert, parent, child, i)) 353 if err != nil { 354 return testOrg{}, err 355 } 356 serverCerts = append(serverCerts, serverCert{keyPEM, certPEM}) 357 } 358 359 // loop through and load clients 360 var clientCerts = []tls.Certificate{} 361 for j := 1; j <= numServerCerts; j++ { 362 clientCert, err := loadTLSKeyPairFromFile( 363 fmt.Sprintf(childClientKey, parent, child, j), 364 fmt.Sprintf(childClientCert, parent, child, j), 365 ) 366 if err != nil { 367 return testOrg{}, err 368 } 369 clientCerts = append(clientCerts, clientCert) 370 } 371 372 return testOrg{caPEM, serverCerts, clientCerts, []testOrg{}}, nil 373 } 374 375 // loadTLSKeyPairFromFile creates a tls.Certificate from PEM-encoded key and cert files 376 func loadTLSKeyPairFromFile(keyFile, certFile string) (tls.Certificate, error) { 377 certPEMBlock, err := ioutil.ReadFile(certFile) 378 if err != nil { 379 return tls.Certificate{}, err 380 } 381 382 keyPEMBlock, err := ioutil.ReadFile(keyFile) 383 if err != nil { 384 return tls.Certificate{}, err 385 } 386 387 cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) 388 if err != nil { 389 return tls.Certificate{}, err 390 } 391 392 return cert, nil 393 } 394 395 func TestNewGRPCServerInvalidParameters(t *testing.T) { 396 t.Parallel() 397 398 // missing address 399 _, err := comm.NewGRPCServer( 400 "", 401 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 402 ) 403 assert.EqualError(t, err, "missing address parameter") 404 405 // missing port 406 _, err = comm.NewGRPCServer( 407 "abcdef", 408 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 409 ) 410 assert.Error(t, err, "Expected error with missing port") 411 assert.Contains(t, err.Error(), "missing port in address") 412 413 // bad port 414 _, err = comm.NewGRPCServer( 415 "127.0.0.1:1BBB", 416 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 417 ) 418 //check for possible errors based on platform and Go release 419 msgs := []string{ 420 "listen tcp: lookup tcp/1BBB: nodename nor servname provided, or not known", 421 "listen tcp: unknown port tcp/1BBB", 422 "listen tcp: address tcp/1BBB: unknown port", 423 "listen tcp: lookup tcp/1BBB: Servname not supported for ai_socktype", 424 } 425 if assert.Error(t, err, fmt.Sprintf("[%s], [%s] [%s] or [%s] expected", msgs[0], msgs[1], msgs[2], msgs[3])) { 426 assert.Contains(t, msgs, err.Error()) 427 } 428 429 // bad hostname 430 _, err = comm.NewGRPCServer( 431 "hostdoesnotexist.localdomain:9050", 432 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 433 ) 434 // We cannot check for a specific error message due to the fact that some 435 // systems will automatically resolve unknown host names to a "search" 436 // address so we just check to make sure that an error was returned 437 assert.Error(t, err, "error expected") 438 439 // address in use 440 lis, err := net.Listen("tcp", "127.0.0.1:0") 441 assert.NoError(t, err, "failed to create listener") 442 defer lis.Close() 443 444 _, err = comm.NewGRPCServerFromListener( 445 lis, 446 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 447 ) 448 assert.NoError(t, err, "failed to create grpc server") 449 450 _, err = comm.NewGRPCServer( 451 lis.Addr().String(), 452 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 453 ) 454 assert.Error(t, err) 455 assert.Contains(t, err.Error(), "address already in use") 456 457 // missing server Certificate 458 _, err = comm.NewGRPCServerFromListener( 459 lis, 460 comm.ServerConfig{ 461 SecOpts: comm.SecureOptions{UseTLS: true, Key: []byte{}}, 462 }, 463 ) 464 assert.EqualError(t, err, "serverConfig.SecOpts must contain both Key and Certificate when UseTLS is true") 465 466 // missing server Key 467 _, err = comm.NewGRPCServerFromListener( 468 lis, 469 comm.ServerConfig{ 470 SecOpts: comm.SecureOptions{ 471 UseTLS: true, 472 Certificate: []byte{}}, 473 }, 474 ) 475 assert.EqualError(t, err, "serverConfig.SecOpts must contain both Key and Certificate when UseTLS is true") 476 477 // bad server Key 478 _, err = comm.NewGRPCServerFromListener( 479 lis, 480 comm.ServerConfig{ 481 SecOpts: comm.SecureOptions{ 482 UseTLS: true, 483 Certificate: []byte(selfSignedCertPEM), 484 Key: []byte{}, 485 }, 486 }, 487 ) 488 assert.EqualError(t, err, "tls: failed to find any PEM data in key input") 489 490 // bad server Certificate 491 _, err = comm.NewGRPCServerFromListener( 492 lis, 493 comm.ServerConfig{ 494 SecOpts: comm.SecureOptions{ 495 UseTLS: true, 496 Certificate: []byte{}, 497 Key: []byte(selfSignedKeyPEM)}, 498 }, 499 ) 500 assert.EqualError(t, err, "tls: failed to find any PEM data in certificate input") 501 502 srv, err := comm.NewGRPCServerFromListener( 503 lis, 504 comm.ServerConfig{ 505 SecOpts: comm.SecureOptions{ 506 UseTLS: true, 507 Certificate: []byte(selfSignedCertPEM), 508 Key: []byte(selfSignedKeyPEM), 509 RequireClientCert: true}, 510 }, 511 ) 512 assert.NoError(t, err) 513 514 badRootCAs := [][]byte{[]byte(badPEM)} 515 err = srv.SetClientRootCAs(badRootCAs) 516 assert.EqualError(t, err, "failed to set client root certificate(s): asn1: syntax error: data truncated") 517 } 518 519 func TestNewGRPCServer(t *testing.T) { 520 t.Parallel() 521 522 testAddress := "127.0.0.1:9053" 523 srv, err := comm.NewGRPCServer( 524 testAddress, 525 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 526 ) 527 assert.NoError(t, err, "failed to create new GRPC server") 528 529 // resolve the address 530 addr, err := net.ResolveTCPAddr("tcp", testAddress) 531 assert.NoError(t, err) 532 533 // make sure our properties are as expected 534 assert.Equal(t, srv.Address(), addr.String()) 535 assert.Equal(t, srv.Listener().Addr().String(), addr.String()) 536 assert.Equal(t, srv.TLSEnabled(), false) 537 assert.Equal(t, srv.MutualTLSRequired(), false) 538 539 // register the GRPC test server 540 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 541 542 // start the server 543 go srv.Start() 544 defer srv.Stop() 545 546 // should not be needed 547 time.Sleep(10 * time.Millisecond) 548 549 // invoke the EmptyCall service 550 _, err = invokeEmptyCall(testAddress, grpc.WithInsecure()) 551 assert.NoError(t, err, "failed to invoke the EmptyCall service") 552 } 553 554 func TestNewGRPCServerFromListener(t *testing.T) { 555 t.Parallel() 556 557 // create our listener 558 lis, err := net.Listen("tcp", "127.0.0.1:0") 559 assert.NoError(t, err, "failed to create listener") 560 testAddress := lis.Addr().String() 561 562 srv, err := comm.NewGRPCServerFromListener( 563 lis, 564 comm.ServerConfig{SecOpts: comm.SecureOptions{UseTLS: false}}, 565 ) 566 assert.NoError(t, err, "failed to create new GRPC server") 567 568 assert.Equal(t, srv.Address(), testAddress) 569 assert.Equal(t, srv.Listener().Addr().String(), testAddress) 570 assert.Equal(t, srv.TLSEnabled(), false) 571 assert.Equal(t, srv.MutualTLSRequired(), false) 572 573 // register the GRPC test server 574 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 575 576 // start the server 577 go srv.Start() 578 defer srv.Stop() 579 580 // should not be needed 581 time.Sleep(10 * time.Millisecond) 582 583 // invoke the EmptyCall service 584 _, err = invokeEmptyCall(testAddress, grpc.WithInsecure()) 585 assert.NoError(t, err, "client failed to invoke the EmptyCall service") 586 } 587 588 func TestNewSecureGRPCServer(t *testing.T) { 589 t.Parallel() 590 591 // create our listener 592 lis, err := net.Listen("tcp", "127.0.0.1:0") 593 assert.NoError(t, err, "failed to create listener") 594 testAddress := lis.Addr().String() 595 596 srv, err := comm.NewGRPCServerFromListener(lis, comm.ServerConfig{ 597 ConnectionTimeout: 250 * time.Millisecond, 598 SecOpts: comm.SecureOptions{ 599 UseTLS: true, 600 Certificate: []byte(selfSignedCertPEM), 601 Key: []byte(selfSignedKeyPEM)}, 602 }, 603 ) 604 assert.NoError(t, err, "failed to create new grpc server") 605 606 // make sure our properties are as expected 607 assert.NoError(t, err) 608 assert.Equal(t, srv.Address(), testAddress) 609 assert.Equal(t, srv.Listener().Addr().String(), testAddress) 610 611 cert, _ := tls.X509KeyPair([]byte(selfSignedCertPEM), []byte(selfSignedKeyPEM)) 612 assert.Equal(t, srv.ServerCertificate(), cert) 613 614 assert.Equal(t, srv.TLSEnabled(), true) 615 assert.Equal(t, srv.MutualTLSRequired(), false) 616 617 // register the GRPC test server 618 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 619 620 //start the server 621 go srv.Start() 622 defer srv.Stop() 623 624 // should not be needed 625 time.Sleep(10 * time.Millisecond) 626 627 // create the client credentials 628 certPool := x509.NewCertPool() 629 if !certPool.AppendCertsFromPEM([]byte(selfSignedCertPEM)) { 630 t.Fatal("Failed to append certificate to client credentials") 631 } 632 creds := credentials.NewClientTLSFromCert(certPool, "") 633 634 // invoke the EmptyCall service 635 _, err = invokeEmptyCall(testAddress, grpc.WithTransportCredentials(creds)) 636 assert.NoError(t, err, "client failed to invoke the EmptyCall service") 637 638 tlsVersions := map[string]uint16{ 639 "SSL30": tls.VersionSSL30, 640 "TLS10": tls.VersionTLS10, 641 "TLS11": tls.VersionTLS11, 642 } 643 for name, version := range tlsVersions { 644 version := version 645 t.Run(name, func(t *testing.T) { 646 t.Parallel() 647 648 creds := credentials.NewTLS(&tls.Config{RootCAs: certPool, MinVersion: version, MaxVersion: version}) 649 _, err := invokeEmptyCall(testAddress, grpc.WithTransportCredentials(creds), grpc.WithBlock()) 650 assert.Error(t, err, "should not have been able to connect with TLS version < 1.2") 651 assert.Contains(t, err.Error(), "context deadline exceeded") 652 }) 653 } 654 } 655 656 func TestVerifyCertificateCallback(t *testing.T) { 657 t.Parallel() 658 659 ca, err := tlsgen.NewCA() 660 assert.NoError(t, err) 661 662 authorizedClientKeyPair, err := ca.NewClientCertKeyPair() 663 assert.NoError(t, err) 664 665 notAuthorizedClientKeyPair, err := ca.NewClientCertKeyPair() 666 assert.NoError(t, err) 667 668 serverKeyPair, err := ca.NewServerCertKeyPair("127.0.0.1") 669 assert.NoError(t, err) 670 671 verifyFunc := func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { 672 if bytes.Equal(rawCerts[0], authorizedClientKeyPair.TLSCert.Raw) { 673 return nil 674 } 675 return errors.New("certificate mismatch") 676 } 677 678 probeTLS := func(endpoint string, clientKeyPair *tlsgen.CertKeyPair) error { 679 cert, err := tls.X509KeyPair(clientKeyPair.Cert, clientKeyPair.Key) 680 if err != nil { 681 return err 682 } 683 tlsCfg := &tls.Config{ 684 Certificates: []tls.Certificate{cert}, 685 RootCAs: x509.NewCertPool(), 686 } 687 tlsCfg.RootCAs.AppendCertsFromPEM(ca.CertBytes()) 688 689 conn, err := tls.Dial("tcp", endpoint, tlsCfg) 690 if err != nil { 691 return err 692 } 693 conn.Close() 694 return nil 695 } 696 697 gRPCServer, err := comm.NewGRPCServer("127.0.0.1:", comm.ServerConfig{ 698 SecOpts: comm.SecureOptions{ 699 ClientRootCAs: [][]byte{ca.CertBytes()}, 700 Key: serverKeyPair.Key, 701 Certificate: serverKeyPair.Cert, 702 UseTLS: true, 703 VerifyCertificate: verifyFunc, 704 }, 705 }) 706 go gRPCServer.Start() 707 defer gRPCServer.Stop() 708 709 t.Run("Success path", func(t *testing.T) { 710 err = probeTLS(gRPCServer.Address(), authorizedClientKeyPair) 711 assert.NoError(t, err) 712 }) 713 714 t.Run("Failure path", func(t *testing.T) { 715 err = probeTLS(gRPCServer.Address(), notAuthorizedClientKeyPair) 716 assert.EqualError(t, err, "remote error: tls: bad certificate") 717 }) 718 } 719 720 // prior tests used self-signed certficates loaded by the GRPCServer and the test client 721 // here we'll use certificates signed by certificate authorities 722 func TestWithSignedRootCertificates(t *testing.T) { 723 t.Parallel() 724 725 // use Org1 testdata 726 fileBase := "Org1" 727 certPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-server1-cert.pem")) 728 assert.NoError(t, err, "failed to load test certificates") 729 730 keyPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-server1-key.pem")) 731 assert.NoError(t, err, "failed to load test certificates: %v") 732 733 caPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-cert.pem")) 734 assert.NoError(t, err, "failed to load test certificates") 735 736 // create our listener 737 lis, err := net.Listen("tcp", "127.0.0.1:0") 738 assert.NoError(t, err, "failed to create listener") 739 testAddress := lis.Addr().String() 740 741 srv, err := comm.NewGRPCServerFromListener(lis, comm.ServerConfig{ 742 SecOpts: comm.SecureOptions{ 743 UseTLS: true, 744 Certificate: certPEMBlock, 745 Key: keyPEMBlock, 746 }, 747 }) 748 assert.NoError(t, err, "failed to create new grpc server") 749 // register the GRPC test server 750 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 751 752 //start the server 753 go srv.Start() 754 defer srv.Stop() 755 756 // should not be needed 757 time.Sleep(10 * time.Millisecond) 758 759 // create a CertPool for use by the client with the server cert only 760 certPoolServer, err := createCertPool([][]byte{certPEMBlock}) 761 assert.NoError(t, err, "failed to load root certificates into pool") 762 creds := credentials.NewClientTLSFromCert(certPoolServer, "") 763 764 // invoke the EmptyCall service 765 _, err = invokeEmptyCall(testAddress, grpc.WithTransportCredentials(creds)) 766 assert.NoError(t, err, "Expected client to connect with server cert only") 767 768 // now use the CA certificate 769 certPoolCA := x509.NewCertPool() 770 if !certPoolCA.AppendCertsFromPEM(caPEMBlock) { 771 t.Fatal("Failed to append certificate to client credentials") 772 } 773 creds = credentials.NewClientTLSFromCert(certPoolCA, "") 774 775 // invoke the EmptyCall service 776 _, err = invokeEmptyCall(testAddress, grpc.WithTransportCredentials(creds)) 777 assert.NoError(t, err, "client failed to invoke the EmptyCall") 778 } 779 780 // here we'll use certificates signed by intermediate certificate authorities 781 func TestWithSignedIntermediateCertificates(t *testing.T) { 782 t.Parallel() 783 784 // use Org1 testdata 785 fileBase := "Org1" 786 certPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-child1-server1-cert.pem")) 787 assert.NoError(t, err) 788 789 keyPEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-child1-server1-key.pem")) 790 assert.NoError(t, err) 791 792 intermediatePEMBlock, err := ioutil.ReadFile(filepath.Join("testdata", "certs", fileBase+"-child1-cert.pem")) 793 if err != nil { 794 t.Fatalf("Failed to load test certificates: %v", err) 795 } 796 797 // create our listener 798 lis, err := net.Listen("tcp", "127.0.0.1:0") 799 if err != nil { 800 t.Fatalf("Failed to create listener: %v", err) 801 } 802 testAddress := lis.Addr().String() 803 804 srv, err := comm.NewGRPCServerFromListener(lis, comm.ServerConfig{ 805 SecOpts: comm.SecureOptions{ 806 UseTLS: true, 807 Certificate: certPEMBlock, 808 Key: keyPEMBlock}}) 809 // check for error 810 if err != nil { 811 t.Fatalf("Failed to return new GRPC server: %v", err) 812 } 813 814 // register the GRPC test server 815 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 816 817 // start the server 818 go srv.Start() 819 defer srv.Stop() 820 821 // should not be needed 822 time.Sleep(10 * time.Millisecond) 823 824 // create a CertPool for use by the client with the server cert only 825 certPoolServer, err := createCertPool([][]byte{certPEMBlock}) 826 if err != nil { 827 t.Fatalf("Failed to load root certificates into pool: %v", err) 828 } 829 // create the client credentials 830 creds := credentials.NewClientTLSFromCert(certPoolServer, "") 831 832 // invoke the EmptyCall service 833 _, err = invokeEmptyCall(testAddress, grpc.WithTransportCredentials(creds)) 834 835 // client should be able to connect with Go 1.9 836 assert.NoError(t, err, "Expected client to connect with server cert only") 837 838 // now use the CA certificate 839 // create a CertPool for use by the client with the intermediate root CA 840 certPoolCA, err := createCertPool([][]byte{intermediatePEMBlock}) 841 assert.NoError(t, err, "failed to load root certificates into pool") 842 843 creds = credentials.NewClientTLSFromCert(certPoolCA, "") 844 845 // invoke the EmptyCall service 846 _, err = invokeEmptyCall(testAddress, grpc.WithTransportCredentials(creds)) 847 assert.NoError(t, err, "client failed to invoke the EmptyCall service") 848 } 849 850 // utility function for testing client / server communication using TLS 851 func runMutualAuth(t *testing.T, servers []testServer, trustedClients, unTrustedClients []*tls.Config) error { 852 // loop through all the test servers 853 for i := 0; i < len(servers); i++ { 854 //create listener 855 lis, err := net.Listen("tcp", "127.0.0.1:0") 856 if err != nil { 857 return err 858 } 859 srvAddr := lis.Addr().String() 860 861 // create GRPCServer 862 srv, err := comm.NewGRPCServerFromListener(lis, servers[i].config) 863 if err != nil { 864 return err 865 } 866 867 // MutualTLSRequired should be true 868 assert.Equal(t, srv.MutualTLSRequired(), true) 869 870 //register the GRPC test server and start the GRPCServer 871 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 872 go srv.Start() 873 defer srv.Stop() 874 875 // should not be needed but just in case 876 time.Sleep(10 * time.Millisecond) 877 878 // loop through all the trusted clients 879 for j := 0; j < len(trustedClients); j++ { 880 // invoke the EmptyCall service 881 _, err = invokeEmptyCall(srvAddr, grpc.WithTransportCredentials(credentials.NewTLS(trustedClients[j]))) 882 // we expect success from trusted clients 883 if err != nil { 884 return err 885 } else { 886 t.Logf("Trusted client%d successfully connected to %s", j, srvAddr) 887 } 888 } 889 890 // loop through all the untrusted clients 891 for k := 0; k < len(unTrustedClients); k++ { 892 // invoke the EmptyCall service 893 _, err = invokeEmptyCall( 894 srvAddr, 895 grpc.WithTransportCredentials(credentials.NewTLS(unTrustedClients[k])), 896 ) 897 // we expect failure from untrusted clients 898 if err != nil { 899 t.Logf("Untrusted client%d was correctly rejected by %s", k, srvAddr) 900 } else { 901 return fmt.Errorf("Untrusted client %d should not have been able to connect to %s", k, srvAddr) 902 } 903 } 904 } 905 906 return nil 907 } 908 909 func TestMutualAuth(t *testing.T) { 910 t.Parallel() 911 912 var tests = []struct { 913 name string 914 servers []testServer 915 trustedClients []*tls.Config 916 unTrustedClients []*tls.Config 917 }{ 918 { 919 name: "ClientAuthRequiredWithSingleOrg", 920 servers: testOrgs[0].testServers([][]byte{}), 921 trustedClients: testOrgs[0].trustedClients([][]byte{}), 922 unTrustedClients: testOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}), 923 }, 924 { 925 name: "ClientAuthRequiredWithChildClientOrg", 926 servers: testOrgs[0].testServers([][]byte{testOrgs[0].childOrgs[0].rootCA}), 927 trustedClients: testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA}), 928 unTrustedClients: testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}), 929 }, 930 { 931 name: "ClientAuthRequiredWithMultipleChildClientOrgs", 932 servers: testOrgs[0].testServers(append([][]byte{}, 933 testOrgs[0].childOrgs[0].rootCA, 934 testOrgs[0].childOrgs[1].rootCA, 935 )), 936 trustedClients: append(append([]*tls.Config{}, 937 testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})...), 938 testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})...), 939 unTrustedClients: testOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}), 940 }, 941 { 942 name: "ClientAuthRequiredWithDifferentServerAndClientOrgs", 943 servers: testOrgs[0].testServers([][]byte{testOrgs[1].rootCA}), 944 trustedClients: testOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}), 945 unTrustedClients: testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA}), 946 }, 947 { 948 name: "ClientAuthRequiredWithDifferentServerAndChildClientOrgs", 949 servers: testOrgs[1].testServers([][]byte{testOrgs[0].childOrgs[0].rootCA}), 950 trustedClients: testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[1].rootCA}), 951 unTrustedClients: testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[1].rootCA}), 952 }, 953 } 954 955 for _, test := range tests { 956 test := test 957 t.Run(test.name, func(t *testing.T) { 958 t.Parallel() 959 t.Logf("Running test %s ...", test.name) 960 testErr := runMutualAuth(t, test.servers, test.trustedClients, test.unTrustedClients) 961 assert.NoError(t, testErr) 962 }) 963 } 964 } 965 966 func TestSetClientRootCAs(t *testing.T) { 967 t.Parallel() 968 969 // get the config for one of our Org1 test servers 970 serverConfig := testOrgs[0].testServers([][]byte{})[0].config 971 lis, err := net.Listen("tcp", "127.0.0.1:0") 972 assert.NoError(t, err, "listen failed") 973 defer lis.Close() 974 address := lis.Addr().String() 975 976 // create a GRPCServer 977 srv, err := comm.NewGRPCServerFromListener(lis, serverConfig) 978 assert.NoError(t, err, "failed to create GRPCServer") 979 980 // register the GRPC test server and start the GRPCServer 981 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 982 go srv.Start() 983 defer srv.Stop() 984 985 // should not be needed but just in case 986 time.Sleep(10 * time.Millisecond) 987 988 // set up our test clients 989 // Org1 990 clientConfigOrg1Child1 := testOrgs[0].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0] 991 clientConfigOrg1Child2 := testOrgs[0].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})[0] 992 clientConfigsOrg1Children := []*tls.Config{clientConfigOrg1Child1, clientConfigOrg1Child2} 993 org1ChildRootCAs := [][]byte{testOrgs[0].childOrgs[0].rootCA, testOrgs[0].childOrgs[1].rootCA} 994 // Org2 995 clientConfigOrg2Child1 := testOrgs[1].childOrgs[0].trustedClients([][]byte{testOrgs[0].rootCA})[0] 996 clientConfigOrg2Child2 := testOrgs[1].childOrgs[1].trustedClients([][]byte{testOrgs[0].rootCA})[0] 997 clientConfigsOrg2Children := []*tls.Config{clientConfigOrg2Child1, clientConfigOrg2Child2} 998 org2ChildRootCAs := [][]byte{testOrgs[1].childOrgs[0].rootCA, testOrgs[1].childOrgs[1].rootCA} 999 1000 // initially set client CAs to Org1 children 1001 err = srv.SetClientRootCAs(org1ChildRootCAs) 1002 assert.NoError(t, err, "SetClientRootCAs failed") 1003 1004 // clientConfigsOrg1Children are currently trusted 1005 for _, clientConfig := range clientConfigsOrg1Children { 1006 // we expect success as these are trusted clients 1007 _, err = invokeEmptyCall(address, grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))) 1008 assert.NoError(t, err, "trusted client should have connected") 1009 } 1010 1011 // clientConfigsOrg2Children are currently not trusted 1012 for _, clientConfig := range clientConfigsOrg2Children { 1013 // we expect failure as these are now untrusted clients 1014 _, err = invokeEmptyCall(address, grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))) 1015 assert.Error(t, err, "untrusted client should not have been able to connect") 1016 } 1017 1018 // now set client CAs to Org2 children 1019 err = srv.SetClientRootCAs(org2ChildRootCAs) 1020 assert.NoError(t, err, "SetClientRootCAs failed") 1021 1022 // now reverse trusted and not trusted 1023 // clientConfigsOrg1Children are currently trusted 1024 for _, clientConfig := range clientConfigsOrg2Children { 1025 // we expect success as these are trusted clients 1026 _, err = invokeEmptyCall(address, grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))) 1027 assert.NoError(t, err, "trusted client should have connected") 1028 } 1029 1030 // clientConfigsOrg2Children are currently not trusted 1031 for _, clientConfig := range clientConfigsOrg1Children { 1032 // we expect failure as these are now untrusted clients 1033 _, err = invokeEmptyCall(address, grpc.WithTransportCredentials(credentials.NewTLS(clientConfig))) 1034 assert.Error(t, err, "untrusted client should not have connected") 1035 } 1036 } 1037 1038 func TestUpdateTLSCert(t *testing.T) { 1039 t.Parallel() 1040 1041 readFile := func(path string) []byte { 1042 fName := filepath.Join("testdata", "dynamic_cert_update", path) 1043 data, err := ioutil.ReadFile(fName) 1044 if err != nil { 1045 panic(fmt.Errorf("Failed reading %s: %v", fName, err)) 1046 } 1047 return data 1048 } 1049 loadBytes := func(prefix string) (key, cert, caCert []byte) { 1050 cert = readFile(filepath.Join(prefix, "server.crt")) 1051 key = readFile(filepath.Join(prefix, "server.key")) 1052 caCert = readFile(filepath.Join("ca.crt")) 1053 return 1054 } 1055 1056 key, cert, caCert := loadBytes("notlocalhost") 1057 1058 cfg := comm.ServerConfig{ 1059 SecOpts: comm.SecureOptions{ 1060 UseTLS: true, 1061 Key: key, 1062 Certificate: cert, 1063 }, 1064 } 1065 1066 // create our listener 1067 lis, err := net.Listen("tcp", "127.0.0.1:0") 1068 assert.NoError(t, err, "listen failed") 1069 testAddress := lis.Addr().String() 1070 1071 srv, err := comm.NewGRPCServerFromListener(lis, cfg) 1072 assert.NoError(t, err) 1073 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 1074 1075 go srv.Start() 1076 defer srv.Stop() 1077 1078 certPool := x509.NewCertPool() 1079 certPool.AppendCertsFromPEM(caCert) 1080 1081 probeServer := func() error { 1082 _, err = invokeEmptyCall( 1083 testAddress, 1084 grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{RootCAs: certPool})), 1085 grpc.WithBlock(), 1086 ) 1087 return err 1088 } 1089 1090 // bootstrap TLS certificate has a SAN of "notlocalhost" so it should fail 1091 err = probeServer() 1092 assert.Error(t, err) 1093 assert.Contains(t, err.Error(), "context deadline exceeded") 1094 1095 // new TLS certificate has a SAN of "127.0.0.1" so it should succeed 1096 certPath := filepath.Join("testdata", "dynamic_cert_update", "localhost", "server.crt") 1097 keyPath := filepath.Join("testdata", "dynamic_cert_update", "localhost", "server.key") 1098 tlsCert, err := tls.LoadX509KeyPair(certPath, keyPath) 1099 assert.NoError(t, err) 1100 srv.SetServerCertificate(tlsCert) 1101 err = probeServer() 1102 assert.NoError(t, err) 1103 1104 // revert back to the old certificate, should fail. 1105 certPath = filepath.Join("testdata", "dynamic_cert_update", "notlocalhost", "server.crt") 1106 keyPath = filepath.Join("testdata", "dynamic_cert_update", "notlocalhost", "server.key") 1107 tlsCert, err = tls.LoadX509KeyPair(certPath, keyPath) 1108 assert.NoError(t, err) 1109 srv.SetServerCertificate(tlsCert) 1110 1111 err = probeServer() 1112 assert.Error(t, err) 1113 assert.Contains(t, err.Error(), "context deadline exceeded") 1114 } 1115 1116 func TestCipherSuites(t *testing.T) { 1117 t.Parallel() 1118 1119 // default cipher suites 1120 defaultCipherSuites := []uint16{ 1121 tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1122 tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 1123 tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 1124 tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 1125 tls.TLS_RSA_WITH_AES_128_GCM_SHA256, 1126 tls.TLS_RSA_WITH_AES_256_GCM_SHA384, 1127 } 1128 // the other cipher suites supported by Go 1129 otherCipherSuites := []uint16{ 1130 tls.TLS_RSA_WITH_RC4_128_SHA, 1131 tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, 1132 tls.TLS_RSA_WITH_AES_128_CBC_SHA, 1133 tls.TLS_RSA_WITH_AES_256_CBC_SHA, 1134 tls.TLS_RSA_WITH_AES_128_CBC_SHA256, 1135 tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 1136 tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 1137 tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 1138 tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, 1139 tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 1140 tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 1141 tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 1142 tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 1143 tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 1144 tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1145 tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1146 } 1147 certPEM, err := ioutil.ReadFile(filepath.Join("testdata", "certs", "Org1-server1-cert.pem")) 1148 assert.NoError(t, err) 1149 keyPEM, err := ioutil.ReadFile(filepath.Join("testdata", "certs", "Org1-server1-key.pem")) 1150 assert.NoError(t, err) 1151 caPEM, err := ioutil.ReadFile(filepath.Join("testdata", "certs", "Org1-cert.pem")) 1152 assert.NoError(t, err) 1153 certPool, err := createCertPool([][]byte{caPEM}) 1154 assert.NoError(t, err) 1155 1156 serverConfig := comm.ServerConfig{ 1157 SecOpts: comm.SecureOptions{ 1158 Certificate: certPEM, 1159 Key: keyPEM, 1160 UseTLS: true, 1161 }} 1162 1163 var tests = []struct { 1164 name string 1165 clientCiphers []uint16 1166 success bool 1167 }{ 1168 { 1169 name: "server default / client all", 1170 success: true, 1171 }, 1172 { 1173 name: "server default / client match", 1174 clientCiphers: defaultCipherSuites, 1175 success: true, 1176 }, 1177 { 1178 name: "server default / client no match", 1179 clientCiphers: otherCipherSuites, 1180 success: false, 1181 }, 1182 } 1183 1184 // create our listener 1185 lis, err := net.Listen("tcp", "127.0.0.1:0") 1186 assert.NoError(t, err, "listen failed") 1187 testAddress := lis.Addr().String() 1188 srv, err := comm.NewGRPCServerFromListener(lis, serverConfig) 1189 assert.NoError(t, err) 1190 go srv.Start() 1191 1192 for _, test := range tests { 1193 test := test 1194 t.Run(test.name, func(t *testing.T) { 1195 t.Parallel() 1196 1197 tlsConfig := &tls.Config{ 1198 RootCAs: certPool, 1199 CipherSuites: test.clientCiphers, 1200 } 1201 _, err := tls.Dial("tcp", testAddress, tlsConfig) 1202 if test.success { 1203 assert.NoError(t, err) 1204 } else { 1205 assert.Error(t, err, "expected handshake failure") 1206 assert.Contains(t, err.Error(), "handshake failure") 1207 } 1208 }) 1209 } 1210 } 1211 1212 func TestServerInterceptors(t *testing.T) { 1213 lis, err := net.Listen("tcp", "127.0.0.1:0") 1214 assert.NoError(t, err, "listen failed") 1215 msg := "error from interceptor" 1216 1217 // set up interceptors 1218 usiCount := uint32(0) 1219 ssiCount := uint32(0) 1220 usi1 := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { 1221 atomic.AddUint32(&usiCount, 1) 1222 return handler(ctx, req) 1223 } 1224 usi2 := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { 1225 atomic.AddUint32(&usiCount, 1) 1226 return nil, status.Error(codes.Aborted, msg) 1227 } 1228 ssi1 := func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { 1229 atomic.AddUint32(&ssiCount, 1) 1230 return handler(srv, ss) 1231 } 1232 ssi2 := func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { 1233 atomic.AddUint32(&ssiCount, 1) 1234 return status.Error(codes.Aborted, msg) 1235 } 1236 1237 srvConfig := comm.ServerConfig{} 1238 srvConfig.UnaryInterceptors = append(srvConfig.UnaryInterceptors, usi1) 1239 srvConfig.UnaryInterceptors = append(srvConfig.UnaryInterceptors, usi2) 1240 srvConfig.StreamInterceptors = append(srvConfig.StreamInterceptors, ssi1) 1241 srvConfig.StreamInterceptors = append(srvConfig.StreamInterceptors, ssi2) 1242 1243 srv, err := comm.NewGRPCServerFromListener(lis, srvConfig) 1244 assert.NoError(t, err, "failed to create gRPC server") 1245 testpb.RegisterEmptyServiceServer(srv.Server(), &emptyServiceServer{}) 1246 defer srv.Stop() 1247 go srv.Start() 1248 1249 _, err = invokeEmptyCall( 1250 lis.Addr().String(), 1251 grpc.WithBlock(), 1252 grpc.WithInsecure(), 1253 ) 1254 assert.Error(t, err) 1255 assert.Equal(t, status.Convert(err).Message(), msg, "Expected error from second usi") 1256 assert.Equal(t, uint32(2), atomic.LoadUint32(&usiCount), "Expected both usi handlers to be invoked") 1257 1258 _, err = invokeEmptyStream( 1259 lis.Addr().String(), 1260 grpc.WithBlock(), 1261 grpc.WithInsecure(), 1262 ) 1263 assert.Error(t, err) 1264 assert.Equal(t, status.Convert(err).Message(), msg, "Expected error from second ssi") 1265 assert.Equal(t, uint32(2), atomic.LoadUint32(&ssiCount), "Expected both ssi handlers to be invoked") 1266 }