io.grpc.internal.testing.TestUtils Java Examples

The following examples show how to use io.grpc.internal.testing.TestUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConcurrencyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private ManagedChannel newClientChannel() throws CertificateException, IOException {
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forClient()
                     .keyManager(clientCertChainFile, clientPrivateKeyFile)
                     .trustManager(clientTrustedCaCerts)
                     .build();

  return NettyChannelBuilder.forAddress("localhost", server.getPort())
      .overrideAuthority(TestUtils.TEST_SERVER_HOST)
      .negotiationType(NegotiationType.TLS)
      .sslContext(sslContext)
      .build();
}
 
Example #2
Source File: ConcurrencyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and starts a new {@link TestServiceImpl} server.
 */
private Server newServer() throws CertificateException, IOException {
  File serverCertChainFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
                     .trustManager(serverTrustedCaCerts)
                     .clientAuth(ClientAuth.REQUIRE)
                     .build();

  return NettyServerBuilder.forPort(0)
      .sslContext(sslContext)
      .addService(new TestServiceImpl(serverExecutor))
      .build()
      .start();
}
 
Example #3
Source File: ConcurrencyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private ManagedChannel newClientChannel() throws CertificateException, IOException {
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forClient()
                     .keyManager(clientCertChainFile, clientPrivateKeyFile)
                     .trustManager(clientTrustedCaCerts)
                     .build();

  return NettyChannelBuilder.forAddress("localhost", server.getPort())
      .overrideAuthority(TestUtils.TEST_SERVER_HOST)
      .negotiationType(NegotiationType.TLS)
      .sslContext(sslContext)
      .build();
}
 
Example #4
Source File: Http2NettyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  try {
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(TestUtils.testServerAddress((InetSocketAddress) getListenAddress()))
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forClient()
            .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
            .trustManager(TestUtils.loadX509Cert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
    // Disable the default census stats interceptor, use testing interceptor instead.
    io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
    return builder.intercept(createCensusStatsClientInterceptor()).build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #5
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    SslProvider sslProvider = SslContext.defaultServerProvider();
    if (sslProvider == SslProvider.OPENSSL && !OpenSsl.isAlpnSupported()) {
      // OkHttp only supports Jetty ALPN on OpenJDK. So if OpenSSL doesn't support ALPN, then we
      // are forced to use Jetty ALPN for Netty instead of OpenSSL.
      sslProvider = SslProvider.JDK;
    }
    SslContextBuilder contextBuilder = SslContextBuilder
        .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    GrpcSslContexts.configure(contextBuilder, sslProvider);
    contextBuilder.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE);
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(contextBuilder.build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #6
Source File: SdsX509TrustManagerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void oneSanInPeerCertsNotFoundException()
    throws CertificateException, IOException {
  CertificateValidationContext certContext =
      CertificateValidationContext.newBuilder().addVerifySubjectAltName("x.foo.com").build();
  trustManager = new SdsX509TrustManager(certContext, mockDelegate);
  X509Certificate[] certs =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(SERVER_1_PEM_FILE));
  try {
    trustManager.verifySubjectAltNameInChain(certs);
    fail("no exception thrown");
  } catch (CertificateException expected) {
    assertThat(expected).hasMessageThat().isEqualTo("Peer certificate SAN check failed");
  }
}
 
Example #7
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private OkHttpChannelBuilder createChannelBuilder() {
  OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("localhost", getPort())
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .connectionSpec(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
          .cipherSuites(TestUtils.preferredTestCiphers().toArray(new String[0]))
          .build())
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          TestUtils.TEST_SERVER_HOST, getPort()));
  io.grpc.internal.TestingAccessor.setStatsImplementation(
      builder, createClientCensusStatsModule());
  try {
    builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
        TestUtils.loadCert("ca.pem")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return builder;
}
 
Example #8
Source File: Http2NettyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
            .clientAuth(ClientAuth.REQUIRE)
            .trustManager(TestUtils.loadCert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #9
Source File: Http2NettyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
            .clientAuth(ClientAuth.REQUIRE)
            .trustManager(TestUtils.loadCert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #10
Source File: Http2NettyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  try {
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(TestUtils.testServerAddress(getPort()))
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forClient()
            .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
            .trustManager(TestUtils.loadX509Cert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
    io.grpc.internal.TestingAccessor.setStatsImplementation(
        builder, createClientCensusStatsModule());
    return builder.build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #11
Source File: ShadingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tcnative() throws Exception {
  server = NettyServerBuilder.forPort(0)
      .useTransportSecurity(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
      .addService(new SimpleServiceImpl())
      .build().start();
  channel = NettyChannelBuilder
      .forAddress("localhost", server.getPort())
      .sslContext(
          GrpcSslContexts.configure(SslContextBuilder.forClient(), SslProvider.OPENSSL)
              .trustManager(TestUtils.loadCert("ca.pem")).build())
      .overrideAuthority("foo.test.google.fr")
      .build();
  SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel);
  assertThat(SimpleResponse.getDefaultInstance())
      .isEqualTo(stub.unaryRpc(SimpleRequest.getDefaultInstance()));
}
 
Example #12
Source File: Http2OkHttpTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    SslProvider sslProvider = SslContext.defaultServerProvider();
    if (sslProvider == SslProvider.OPENSSL && !SslProvider.isAlpnSupported(SslProvider.OPENSSL)) {
      // OkHttp only supports Jetty ALPN on OpenJDK. So if OpenSSL doesn't support ALPN, then we
      // are forced to use Jetty ALPN for Netty instead of OpenSSL.
      sslProvider = SslProvider.JDK;
    }
    SslContextBuilder contextBuilder = SslContextBuilder
        .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    GrpcSslContexts.configure(contextBuilder, sslProvider);
    contextBuilder.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE);
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(contextBuilder.build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #13
Source File: Utils.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static OkHttpChannelBuilder newOkHttpClientChannel(
    SocketAddress address, boolean tls, boolean testca) {
  InetSocketAddress addr = (InetSocketAddress) address;
  OkHttpChannelBuilder builder =
      OkHttpChannelBuilder.forAddress(addr.getHostName(), addr.getPort());
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    try {
      builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
          Platform.get().getProvider(),
          TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return builder;
}
 
Example #14
Source File: ConcurrencyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and starts a new {@link TestServiceImpl} server.
 */
private Server newServer() throws CertificateException, IOException {
  File serverCertChainFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
                     .trustManager(serverTrustedCaCerts)
                     .clientAuth(ClientAuth.REQUIRE)
                     .build();

  return NettyServerBuilder.forPort(0)
      .sslContext(sslContext)
      .addService(new TestServiceImpl(serverExecutor))
      .build()
      .start();
}
 
Example #15
Source File: SdsTrustManagerFactoryTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void checkClientTrusted_badCert_throwsException()
    throws CertificateException, IOException, CertStoreException {
  SdsTrustManagerFactory factory =
      new SdsTrustManagerFactory(getCertContextFromPath(CA_PEM_FILE));
  SdsX509TrustManager sdsX509TrustManager = (SdsX509TrustManager) factory.getTrustManagers()[0];
  X509Certificate[] clientChain =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(BAD_CLIENT_PEM_FILE));
  try {
    sdsX509TrustManager.checkClientTrusted(clientChain, "RSA");
    Assert.fail("no exception thrown");
  } catch (CertificateException expected) {
    assertThat(expected)
        .hasMessageThat()
        .contains("unable to find valid certification path to requested target");
  }
}
 
Example #16
Source File: SdsTrustManagerFactoryTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void checkServerTrusted_badCert_throwsException()
    throws CertificateException, IOException, CertStoreException {
  SdsTrustManagerFactory factory =
      new SdsTrustManagerFactory(getCertContextFromPath(CA_PEM_FILE));
  SdsX509TrustManager sdsX509TrustManager = (SdsX509TrustManager) factory.getTrustManagers()[0];
  X509Certificate[] serverChain =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(BAD_SERVER_PEM_FILE));
  try {
    sdsX509TrustManager.checkServerTrusted(serverChain, "RSA");
    Assert.fail("no exception thrown");
  } catch (CertificateException expected) {
    assertThat(expected)
        .hasMessageThat()
        .contains("unable to find valid certification path to requested target");
  }
}
 
Example #17
Source File: SdsX509TrustManagerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void wildcardSanInPeerCertsSubdomainMismatch()
    throws CertificateException, IOException {
  // 2. Asterisk (*) cannot match across domain name labels.
  //    For example, *.example.com matches test.example.com but does not match
  //    sub.test.example.com.
  CertificateValidationContext certContext =
      CertificateValidationContext.newBuilder()
          .addVerifySubjectAltName("sub.abc.test.youtube.com")
          .build();
  trustManager = new SdsX509TrustManager(certContext, mockDelegate);
  X509Certificate[] certs =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(SERVER_1_PEM_FILE));
  try {
    trustManager.verifySubjectAltNameInChain(certs);
    fail("no exception thrown");
  } catch (CertificateException expected) {
    assertThat(expected).hasMessageThat().isEqualTo("Peer certificate SAN check failed");
  }
}
 
Example #18
Source File: SdsTrustManagerFactoryTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void constructor_fromInlineBytes()
    throws CertificateException, IOException, CertStoreException {
  SdsTrustManagerFactory factory =
      new SdsTrustManagerFactory(getCertContextFromPathAsInlineBytes(CA_PEM_FILE));
  assertThat(factory).isNotNull();
  TrustManager[] tms = factory.getTrustManagers();
  assertThat(tms).isNotNull();
  assertThat(tms).hasLength(1);
  TrustManager myTm = tms[0];
  assertThat(myTm).isInstanceOf(SdsX509TrustManager.class);
  SdsX509TrustManager sdsX509TrustManager = (SdsX509TrustManager) myTm;
  X509Certificate[] acceptedIssuers = sdsX509TrustManager.getAcceptedIssuers();
  assertThat(acceptedIssuers).isNotNull();
  assertThat(acceptedIssuers).hasLength(1);
  X509Certificate caCert = acceptedIssuers[0];
  assertThat(caCert)
      .isEqualTo(CertificateUtils.toX509Certificates(TestUtils.loadCert(CA_PEM_FILE))[0]);
}
 
Example #19
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private void startServer(int maxStreamsPerConnection, int maxHeaderListSize) throws IOException {
  server = new NettyServer(
      TestUtils.testServerAddress(0),
      NioServerSocketChannel.class,
      new HashMap<ChannelOption<?>, Object>(),
      group, group, negotiator,
      Collections.<ServerStreamTracer.Factory>emptyList(),
      TransportTracer.getDefaultFactory(),
      maxStreamsPerConnection,
      DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE, maxHeaderListSize,
      DEFAULT_SERVER_KEEPALIVE_TIME_NANOS, DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS,
      MAX_CONNECTION_IDLE_NANOS_DISABLED,
      MAX_CONNECTION_AGE_NANOS_DISABLED, MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE, true, 0,
      channelz);
  server.start(serverListener);
  address = TestUtils.testServerAddress(server.getPort());
  authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());
}
 
Example #20
Source File: SdsX509TrustManagerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void checkServerTrustedSslSocket_untrustedServer_expectException()
    throws CertificateException, IOException, CertStoreException {
  TestSslSocket sslSocket = buildTrustManagerAndGetSslSocket();
  X509Certificate[] badServerCert =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(BAD_SERVER_PEM_FILE));
  try {
    trustManager.checkServerTrusted(badServerCert, "ECDHE_ECDSA", sslSocket);
    fail("exception expected");
  } catch (ValidatorException expected) {
    assertThat(expected).hasMessageThat()
        .endsWith("unable to find valid certification path to requested target");
  }
  verify(sslSocket, times(1)).isConnected();
  verify(sslSocket, times(1)).getHandshakeSession();
}
 
Example #21
Source File: SdsTrustManagerFactoryTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void constructor_fromFile() throws CertificateException, IOException, CertStoreException {
  SdsTrustManagerFactory factory =
      new SdsTrustManagerFactory(getCertContextFromPath(CA_PEM_FILE));
  assertThat(factory).isNotNull();
  TrustManager[] tms = factory.getTrustManagers();
  assertThat(tms).isNotNull();
  assertThat(tms).hasLength(1);
  TrustManager myTm = tms[0];
  assertThat(myTm).isInstanceOf(SdsX509TrustManager.class);
  SdsX509TrustManager sdsX509TrustManager = (SdsX509TrustManager) myTm;
  X509Certificate[] acceptedIssuers = sdsX509TrustManager.getAcceptedIssuers();
  assertThat(acceptedIssuers).isNotNull();
  assertThat(acceptedIssuers).hasLength(1);
  X509Certificate caCert = acceptedIssuers[0];
  assertThat(caCert)
      .isEqualTo(CertificateUtils.toX509Certificates(TestUtils.loadCert(CA_PEM_FILE))[0]);
}
 
Example #22
Source File: SdsX509TrustManagerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void oneIpAddressInPeerCertsMismatch() throws CertificateException, IOException {
  CertificateValidationContext certContext =
      CertificateValidationContext.newBuilder()
          .addVerifySubjectAltName("x.foo.com")
          .addVerifySubjectAltName("192.168.2.3")
          .build();
  trustManager = new SdsX509TrustManager(certContext, mockDelegate);
  X509Certificate[] certs =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(SERVER_1_PEM_FILE));
  try {
    trustManager.verifySubjectAltNameInChain(certs);
    fail("no exception thrown");
  } catch (CertificateException expected) {
    assertThat(expected).hasMessageThat().isEqualTo("Peer certificate SAN check failed");
  }
}
 
Example #23
Source File: Utils.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static OkHttpChannelBuilder newOkHttpClientChannel(
    SocketAddress address, boolean tls, boolean testca) {
  InetSocketAddress addr = (InetSocketAddress) address;
  OkHttpChannelBuilder builder =
      OkHttpChannelBuilder.forAddress(addr.getHostName(), addr.getPort());
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    try {
      builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
          Platform.get().getProvider(),
          TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return builder;
}
 
Example #24
Source File: ArmeriaGrpcServerInteropTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.https(new InetSocketAddress("127.0.0.1", 0));
    sb.tls(ssc.certificateFile(), ssc.privateKeyFile());
    sb.tlsCustomizer(ssl -> {
        try {
            ssl.trustManager(TestUtils.loadCert("ca.pem"));
        } catch (IOException e) {
            Exceptions.throwUnsafely(e);
        }
    });
    sb.maxRequestLength(16 * 1024 * 1024);
    sb.serviceUnder("/", grpcService.decorate((delegate, ctx, req) -> {
        ctxCapture.set(ctx);
        return delegate.serve(ctx, req);
    }));
}
 
Example #25
Source File: GrpcUtilsTest.java    From gcp-token-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testManagedChannelTLSSuccess() {
    String certificate;
    try {
        X509Certificate[] trustedCaCerts = {
            TestUtils.loadX509Cert("ca.pem")
        };
        certificate =
            "-----BEGIN CERTIFICATE-----\n" +
            Base64.getEncoder().encodeToString(trustedCaCerts[0].getEncoded()) + "\n" +
            "-----END CERTIFICATE-----";
    } catch (CertificateException | IOException e) {
        throw new RuntimeException(e);
    }
    ManagedChannel channel = GrpcUtils.newManagedChannel("testhost", 8888, true, certificate);
    // TODO: Verify that the certificate is correctly assigned to the channel
}
 
Example #26
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void serverTlsHandler_userEventTriggeredSslEvent_supportedProtocolCustom()
    throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "managed_mtls";
    }
  };

  File serverCert = TestUtils.loadCert("server1.pem");
  File key = TestUtils.loadCert("server1.key");
  List<String> alpnList = Arrays.asList("managed_mtls", "h2");
  ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
      ApplicationProtocolConfig.Protocol.ALPN,
      ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
      ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
      alpnList);

  sslContext = GrpcSslContexts.forServer(serverCert, key)
      .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apn).build();

  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  pipeline.addLast(handler);

  pipeline.replace(SslHandler.class, null, goodSslHandler);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  assertTrue(channel.isOpen());
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
Example #27
Source File: SdsX509TrustManagerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void wildcardSanInPeerCertsVerifiesMultipleVerifySans()
    throws CertificateException, IOException {
  CertificateValidationContext certContext =
      CertificateValidationContext.newBuilder()
          .addVerifySubjectAltName("x.foo.com")
          .addVerifySubjectAltName("abc.test.youtube.com") // should match *.test.youtube.com
          .build();
  trustManager = new SdsX509TrustManager(certContext, mockDelegate);
  X509Certificate[] certs =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(SERVER_1_PEM_FILE));
  trustManager.verifySubjectAltNameInChain(certs);
}
 
Example #28
Source File: SdsX509TrustManagerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void oneSanInPeerCertsVerifiesMultipleVerifySans()
    throws CertificateException, IOException {
  CertificateValidationContext certContext =
      CertificateValidationContext.newBuilder()
          .addVerifySubjectAltName("x.foo.com")
          .addVerifySubjectAltName("waterzooi.test.google.be")
          .build();
  trustManager = new SdsX509TrustManager(certContext, mockDelegate);
  X509Certificate[] certs =
      CertificateUtils.toX509Certificates(TestUtils.loadCert(SERVER_1_PEM_FILE));
  trustManager.verifySubjectAltNameInChain(certs);
}
 
Example #29
Source File: TestServiceServer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** The main application allowing this server to be launched from the command line. */
public static void main(String[] args) throws Exception {
  // Let Netty use Conscrypt if it is available.
  TestUtils.installConscryptIfAvailable();
  final TestServiceServer server = new TestServiceServer();
  server.parseArgs(args);
  if (server.useTls) {
    System.out.println(
        "\nUsing fake CA for TLS certificate. Test clients should expect host\n"
            + "*.test.google.fr and our test CA. For the Java test client binary, use:\n"
            + "--server_host_override=foo.test.google.fr --use_test_ca=true\n");
  }

  Runtime.getRuntime()
      .addShutdownHook(
          new Thread() {
            @Override
            @SuppressWarnings("CatchAndPrintStackTrace")
            public void run() {
              try {
                System.out.println("Shutting down");
                server.stop();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          });
  server.start();
  System.out.println("Server started on port " + server.port);
  server.blockUntilShutdown();
}
 
Example #30
Source File: NettyClientTransportTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static SslContext createSslContext() {
  try {
    File serverCert = TestUtils.loadCert("server1.pem");
    File key = TestUtils.loadCert("server1.key");
    return GrpcSslContexts.forServer(serverCert, key)
        .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE).build();
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}