io.grpc.testing.protobuf.SimpleServiceGrpc Java Examples

The following examples show how to use io.grpc.testing.protobuf.SimpleServiceGrpc. 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: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 7 votes vote down vote up
@Test
public void plaintextServer_tlsClient_expectException() throws IOException, URISyntaxException {
  buildServerWithTlsContext(/* downstreamTlsContext= */ null);

  // for TLS, client only needs trustCa
  UpstreamTlsContext upstreamTlsContext =
      CommonTlsContextTestsUtil.buildUpstreamTlsContextFromFilenames(
          /* privateKey= */ null, /* certChain= */ null, CA_PEM_FILE);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(upstreamTlsContext, /* overrideAuthority= */ "foo.test.google.fr");
  try {
    unaryRpc("buddy", blockingStub);
    fail("exception expected");
  } catch (StatusRuntimeException sre) {
    assertThat(sre).hasCauseThat().isInstanceOf(NotSslRecordException.class);
    assertThat(sre).hasCauseThat().hasMessageThat().contains("not an SSL/TLS record");
  }
}
 
Example #2
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 #3
Source File: ShadingTest.java    From grpc-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 #4
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private SimpleServiceGrpc.SimpleServiceBlockingStub getBlockingStub(
    final UpstreamTlsContext upstreamTlsContext, String overrideAuthority)
    throws URISyntaxException {
  URI expectedUri = new URI("sdstest://localhost:" + port);
  fakeNameResolverFactory = new FakeNameResolverFactory.Builder(expectedUri).build();
  NameResolverRegistry.getDefaultRegistry().register(fakeNameResolverFactory);
  XdsChannelBuilder channelBuilder =
      XdsChannelBuilder.forTarget("sdstest://localhost:" + port);
  if (overrideAuthority != null) {
    channelBuilder = channelBuilder.overrideAuthority(overrideAuthority);
  }
  InetSocketAddress socketAddress =
      new InetSocketAddress(Inet4Address.getLoopbackAddress(), port);
  Attributes attrs =
      (upstreamTlsContext != null)
          ? Attributes.newBuilder()
              .set(XdsAttributes.ATTR_UPSTREAM_TLS_CONTEXT, upstreamTlsContext)
              .build()
          : Attributes.EMPTY;
  fakeNameResolverFactory.setServers(
      ImmutableList.of(new EquivalentAddressGroup(socketAddress, attrs)));
  return SimpleServiceGrpc.newBlockingStub(cleanupRule.register(channelBuilder.build()));
}
 
Example #5
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private XdsClient.ListenerWatcher performMtlsTestAndGetListenerWatcher(
    UpstreamTlsContext upstreamTlsContext) throws IOException, URISyntaxException {
  DownstreamTlsContext downstreamTlsContext =
      CommonTlsContextTestsUtil.buildDownstreamTlsContextFromFilenamesWithClientCertRequired(
          SERVER_1_KEY_FILE, SERVER_1_PEM_FILE, CA_PEM_FILE);

  final XdsClientWrapperForServerSds xdsClientWrapperForServerSds =
      XdsClientWrapperForServerSdsTest.createXdsClientWrapperForServerSds(
          port, /* downstreamTlsContext= */ downstreamTlsContext);
  buildServerWithFallbackProtocolNegotiator(xdsClientWrapperForServerSds,
      InternalProtocolNegotiators.serverPlaintext());

  XdsClient.ListenerWatcher listenerWatcher = xdsClientWrapperForServerSds.getListenerWatcher();

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(upstreamTlsContext, "foo.test.google.fr");
  assertThat(unaryRpc("buddy", blockingStub)).isEqualTo("Hello buddy");
  return listenerWatcher;
}
 
Example #6
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/** mTLS - client auth enabled then update server certs to untrusted. */
@Test
public void mtlsClientServer_changeServerContext_expectException()
    throws IOException, URISyntaxException {
  UpstreamTlsContext upstreamTlsContext =
      CommonTlsContextTestsUtil.buildUpstreamTlsContextFromFilenames(
          CLIENT_KEY_FILE, CLIENT_PEM_FILE, CA_PEM_FILE);
  XdsClient.ListenerWatcher listenerWatcher =
      performMtlsTestAndGetListenerWatcher(upstreamTlsContext);
  DownstreamTlsContext downstreamTlsContext =
      CommonTlsContextTestsUtil.buildDownstreamTlsContextFromFilenames(
          BAD_SERVER_KEY_FILE, BAD_SERVER_PEM_FILE, CA_PEM_FILE);
  XdsClientWrapperForServerSdsTest.generateListenerUpdateToWatcher(
      port, downstreamTlsContext, listenerWatcher);
  try {
    SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
        getBlockingStub(upstreamTlsContext, "foo.test.google.fr");
    assertThat(unaryRpc("buddy", blockingStub)).isEqualTo("Hello buddy");
    fail("exception expected");
  } catch (StatusRuntimeException sre) {
    assertThat(sre).hasCauseThat().isInstanceOf(SSLHandshakeException.class);
    assertThat(sre).hasCauseThat().hasMessageThat().isEqualTo("General OpenSslEngine problem");
  }
}
 
Example #7
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tlsServer_plaintextClient_expectException() throws IOException, URISyntaxException {
  DownstreamTlsContext downstreamTlsContext =
      CommonTlsContextTestsUtil.buildDownstreamTlsContextFromFilenames(
          SERVER_1_KEY_FILE, SERVER_1_PEM_FILE, null);
  buildServerWithTlsContext(downstreamTlsContext);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(/* upstreamTlsContext= */ null, /* overrideAuthority= */ null);
  try {
    unaryRpc("buddy", blockingStub);
    fail("exception expected");
  } catch (StatusRuntimeException sre) {
    assertThat(sre.getStatus().getCode()).isEqualTo(Status.UNAVAILABLE.getCode());
    assertThat(sre.getStatus().getDescription()).contains("Network closed");
  }
}
 
Example #8
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void requireClientAuth_noClientCert_expectException()
    throws IOException, URISyntaxException {
  DownstreamTlsContext downstreamTlsContext =
      CommonTlsContextTestsUtil.buildDownstreamTlsContextFromFilenamesWithClientCertRequired(
          SERVER_1_KEY_FILE, SERVER_1_PEM_FILE, CA_PEM_FILE);
  buildServerWithTlsContext(downstreamTlsContext);

  // for TLS, client only uses trustCa
  UpstreamTlsContext upstreamTlsContext =
      CommonTlsContextTestsUtil.buildUpstreamTlsContextFromFilenames(
          /* privateKey= */ null, /* certChain= */ null, CA_PEM_FILE);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(upstreamTlsContext, /* overrideAuthority= */ "foo.test.google.fr");
  try {
    unaryRpc(/* requestMessage= */ "buddy", blockingStub);
    fail("exception expected");
  } catch (StatusRuntimeException sre) {
    assertThat(sre).hasCauseThat().isInstanceOf(SSLHandshakeException.class);
    assertThat(sre).hasCauseThat().hasMessageThat().contains("HANDSHAKE_FAILURE");
  }
}
 
Example #9
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/** TLS channel - no mTLS. */
@Test
public void tlsClientServer_noClientAuthentication() throws IOException, URISyntaxException {
  DownstreamTlsContext downstreamTlsContext =
      CommonTlsContextTestsUtil.buildDownstreamTlsContextFromFilenames(
          SERVER_1_KEY_FILE, SERVER_1_PEM_FILE, null);
  buildServerWithTlsContext(downstreamTlsContext);

  // for TLS, client only needs trustCa
  UpstreamTlsContext upstreamTlsContext =
      CommonTlsContextTestsUtil.buildUpstreamTlsContextFromFilenames(
          /* privateKey= */ null, /* certChain= */ null, CA_PEM_FILE);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(upstreamTlsContext, /* overrideAuthority= */ "foo.test.google.fr");
  assertThat(unaryRpc(/* requestMessage= */ "buddy", blockingStub)).isEqualTo("Hello buddy");
}
 
Example #10
Source File: TlsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a server configured to require client authentication actually does require client
 * authentication.
 */
@Test
public void noClientAuthFailure() throws Exception {
  // Create & start a server.
  File serverCertFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client. It has no credentials.
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Check that the TLS handshake fails.
  try {
    client.unaryRpc(SimpleRequest.getDefaultInstance());
    fail("TLS handshake should have failed, but didn't; received RPC response");
  } catch (StatusRuntimeException e) {
    // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
    // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
    // Thus, reliably detecting the underlying cause is not feasible.
    assertEquals(
        Throwables.getStackTraceAsString(e),
        Status.Code.UNAVAILABLE, e.getStatus().getCode());
  }
}
 
Example #11
Source File: ShadingTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void basic() throws Exception {
  server = ServerBuilder.forPort(0)
      .addService(new SimpleServiceImpl())
      .build().start();
  channel = ManagedChannelBuilder
      .forAddress("localhost", server.getPort())
      .usePlaintext()
      .build();
  SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel);
  assertThat(SimpleResponse.getDefaultInstance())
      .isEqualTo(stub.unaryRpc(SimpleRequest.getDefaultInstance()));
}
 
Example #12
Source File: ShadingTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void basic() throws Exception {
  server = ServerBuilder.forPort(0)
      .addService(new SimpleServiceImpl())
      .build().start();
  channel = ManagedChannelBuilder
      .forAddress("localhost", server.getPort())
      .usePlaintext()
      .build();
  SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel);
  assertThat(SimpleResponse.getDefaultInstance())
      .isEqualTo(stub.unaryRpc(SimpleRequest.getDefaultInstance()));
}
 
Example #13
Source File: TlsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a client and a server configured using GrpcSslContexts can successfully
 * communicate with each other.
 */
@Test
public void basicClientServerIntegrationTest() throws Exception {
  // Create & start a server.
  File serverCertFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client.
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .keyManager(clientCertChainFile, clientPrivateKeyFile)
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Send an actual request, via the full GRPC & network stack, and check that a proper
  // response comes back.
  client.unaryRpc(SimpleRequest.getDefaultInstance());
}
 
Example #14
Source File: OrcaMetricReportingServerInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  SimpleServiceGrpc.SimpleServiceImplBase simpleServiceImpl =
      new SimpleServiceGrpc.SimpleServiceImplBase() {
        @Override
        public void unaryRpc(
            SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
          for (Map.Entry<String, Double> entry : applicationMetrics.entrySet()) {
            CallMetricRecorder.getCurrent().recordCallMetric(entry.getKey(), entry.getValue());
          }
          SimpleResponse response =
              SimpleResponse.newBuilder().setResponseMessage("Simple response").build();
          responseObserver.onNext(response);
          responseObserver.onCompleted();
        }
      };

  ServerInterceptor metricReportingServerInterceptor = new OrcaMetricReportingServerInterceptor();
  String serverName = InProcessServerBuilder.generateName();
  grpcCleanupRule.register(
      InProcessServerBuilder
          .forName(serverName)
          .directExecutor()
          .addService(
              ServerInterceptors.intercept(simpleServiceImpl, metricReportingServerInterceptor))
          .build().start());

  ManagedChannel baseChannel =
      grpcCleanupRule.register(InProcessChannelBuilder.forName(serverName).build());
  channelToUse =
      ClientInterceptors.intercept(
          baseChannel, new TrailersCapturingClientInterceptor(trailersCapture));
}
 
Example #15
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** Say hello to server. */
private static String unaryRpc(
    String requestMessage, SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub) {
  SimpleRequest request = SimpleRequest.newBuilder().setRequestMessage(requestMessage).build();
  SimpleResponse response = blockingStub.unaryRpc(request);
  return response.getResponseMessage();
}
 
Example #16
Source File: TlsTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a client and a server configured using GrpcSslContexts can successfully
 * communicate with each other.
 */
@Test
public void basicClientServerIntegrationTest() throws Exception {
  // Create & start a server.
  File serverCertFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client.
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .keyManager(clientCertChainFile, clientPrivateKeyFile)
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Send an actual request, via the full GRPC & network stack, and check that a proper
  // response comes back.
  client.unaryRpc(SimpleRequest.getDefaultInstance());
}
 
Example #17
Source File: TlsTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a server configured to require client authentication actually does require client
 * authentication.
 */
@Test
public void noClientAuthFailure() throws Exception {
  // Create & start a server.
  File serverCertFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client. It has no credentials.
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Check that the TLS handshake fails.
  try {
    client.unaryRpc(SimpleRequest.getDefaultInstance());
    fail("TLS handshake should have failed, but didn't; received RPC response");
  } catch (StatusRuntimeException e) {
    // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
    // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
    // Thus, reliably detecting the underlying cause is not feasible.
    assertEquals(
        Throwables.getStackTraceAsString(e),
        Status.Code.UNAVAILABLE, e.getStatus().getCode());
  }
}
 
Example #18
Source File: TlsTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a client configured using GrpcSslContexts refuses to talk to a server that has an
 * an untrusted certificate.
 */
@Test
public void clientRejectsUntrustedServerCert() throws Exception {
  // Create & start a server.
  File serverCertFile = TestUtils.loadCert("badserver.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("badserver.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client.
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .keyManager(clientCertChainFile, clientPrivateKeyFile)
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Check that the TLS handshake fails.
  try {
    client.unaryRpc(SimpleRequest.getDefaultInstance());
    fail("TLS handshake should have failed, but didn't; received RPC response");
  } catch (StatusRuntimeException e) {
    // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
    // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
    // Thus, reliably detecting the underlying cause is not feasible.
    // TODO(carl-mastrangelo): eventually replace this with a hamcrest matcher.
    assertEquals(
        Throwables.getStackTraceAsString(e),
        Status.Code.UNAVAILABLE, e.getStatus().getCode());
  }
}
 
Example #19
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void noClientAuth_sendBadClientCert_passes() throws IOException, URISyntaxException {
  DownstreamTlsContext downstreamTlsContext =
      CommonTlsContextTestsUtil.buildDownstreamTlsContextFromFilenames(
          SERVER_1_KEY_FILE, SERVER_1_PEM_FILE, /* trustCa= */ null);
  buildServerWithTlsContext(downstreamTlsContext);

  UpstreamTlsContext upstreamTlsContext =
      CommonTlsContextTestsUtil.buildUpstreamTlsContextFromFilenames(
          BAD_CLIENT_KEY_FILE, BAD_CLIENT_PEM_FILE, CA_PEM_FILE);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(upstreamTlsContext, /* overrideAuthority= */ "foo.test.google.fr");
  assertThat(unaryRpc("buddy", blockingStub)).isEqualTo("Hello buddy");
}
 
Example #20
Source File: TlsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a client configured using GrpcSslContexts refuses to talk to a server that has an
 * an untrusted certificate.
 */
@Test
public void clientRejectsUntrustedServerCert() throws Exception {
  // Create & start a server.
  File serverCertFile = TestUtils.loadCert("badserver.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("badserver.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client.
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .keyManager(clientCertChainFile, clientPrivateKeyFile)
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Check that the TLS handshake fails.
  try {
    client.unaryRpc(SimpleRequest.getDefaultInstance());
    fail("TLS handshake should have failed, but didn't; received RPC response");
  } catch (StatusRuntimeException e) {
    // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
    // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
    // Thus, reliably detecting the underlying cause is not feasible.
    // TODO(carl-mastrangelo): eventually replace this with a hamcrest matcher.
    assertEquals(
        Throwables.getStackTraceAsString(e),
        Status.Code.UNAVAILABLE, e.getStatus().getCode());
  }
}
 
Example #21
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nullFallbackProtocolNegotiator_expectException()
    throws IOException, URISyntaxException {
  buildServerWithTlsContext(/* downstreamTlsContext= */ null,
      /* fallbackProtocolNegotiator= */ null);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(/* upstreamTlsContext= */ null, /* overrideAuthority= */ null);
  try {
    unaryRpc("buddy", blockingStub);
    fail("exception expected");
  } catch (StatusRuntimeException sre) {
    assertThat(sre.getStatus().getCode()).isEqualTo(Status.UNAVAILABLE.getCode());
  }
}
 
Example #22
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void plaintextClientServer_withDefaultTlsContext() throws IOException, URISyntaxException {
  DownstreamTlsContext defaultTlsContext =
      EnvoyServerProtoData.DownstreamTlsContext.fromEnvoyProtoDownstreamTlsContext(
          io.envoyproxy.envoy.api.v2.auth.DownstreamTlsContext.getDefaultInstance());
  buildServerWithTlsContext(/* downstreamTlsContext= */ defaultTlsContext);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
          getBlockingStub(/* upstreamTlsContext= */ null, /* overrideAuthority= */ null);
  assertThat(unaryRpc("buddy", blockingStub)).isEqualTo("Hello buddy");
}
 
Example #23
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void plaintextClientServer() throws IOException, URISyntaxException {
  buildServerWithTlsContext(/* downstreamTlsContext= */ null);

  SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub =
      getBlockingStub(/* upstreamTlsContext= */ null, /* overrideAuthority= */ null);
  assertThat(unaryRpc("buddy", blockingStub)).isEqualTo("Hello buddy");
}
 
Example #24
Source File: NettyGrpcServerRuleTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void serverAllowsServicesToBeAddedViaServiceRegistry_withoutDirectExecutor() {
    TestServiceImpl testService = new TestServiceImpl();

    grpcServerRule.getServiceRegistry().addService(testService);

    SimpleServiceGrpc.SimpleServiceBlockingStub stub =
            SimpleServiceGrpc.newBlockingStub(grpcServerRule.getChannel());

    SimpleRequest request1 = SimpleRequest.getDefaultInstance();

    SimpleRequest request2 = SimpleRequest.newBuilder().build();

    stub.unaryRpc(request1);
    stub.unaryRpc(request2);

    assertThat(testService.unaryCallRequests).containsExactly(request1, request2);
}
 
Example #25
Source File: TlsTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that a server configured to require client authentication refuses to accept connections
 * from a client that has an untrusted certificate.
 */
@Test
public void serverRejectsUntrustedClientCert() throws Exception {
  // Create & start a server. It requires client authentication and trusts only the test CA.
  File serverCertFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client. Its credentials come from a CA that the server does not trust. The client
  // trusts both test CAs, so we can be sure that the handshake failure is due to the server
  // rejecting the client's cert, not the client rejecting the server's cert.
  File clientCertChainFile = TestUtils.loadCert("badclient.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("badclient.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .keyManager(clientCertChainFile, clientPrivateKeyFile)
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Check that the TLS handshake fails.
  try {
    client.unaryRpc(SimpleRequest.getDefaultInstance());
    fail("TLS handshake should have failed, but didn't; received RPC response");
  } catch (StatusRuntimeException e) {
    // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
    // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
    // Thus, reliably detecting the underlying cause is not feasible.
    assertEquals(
        Throwables.getStackTraceAsString(e),
        Status.Code.UNAVAILABLE, e.getStatus().getCode());
  }
}
 
Example #26
Source File: HandshakerServiceChannelTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void doRpc(Channel channel) {
  SimpleServiceGrpc.newBlockingStub(channel).unaryRpc(SimpleRequest.getDefaultInstance());
}
 
Example #27
Source File: GrpcServerRuleTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void serverAllowsServicesToBeAddedViaServiceRegistry_withoutDirectExecutor() {
  TestServiceImpl testService = new TestServiceImpl();

  grpcServerRule1.getServiceRegistry().addService(testService);

  SimpleServiceGrpc.SimpleServiceBlockingStub stub =
      SimpleServiceGrpc.newBlockingStub(grpcServerRule1.getChannel());

  SimpleRequest request1 = SimpleRequest.getDefaultInstance();

  SimpleRequest request2 = SimpleRequest.newBuilder().build();

  stub.unaryRpc(request1);
  stub.unaryRpc(request2);

  assertThat(testService.unaryCallRequests).containsExactly(request1, request2);
}
 
Example #28
Source File: GrpcServerRuleTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void serverAllowsServicesToBeAddedViaServiceRegistry_withDirectExecutor() {
  TestServiceImpl testService = new TestServiceImpl();

  grpcServerRule2.getServiceRegistry().addService(testService);

  SimpleServiceGrpc.SimpleServiceBlockingStub stub =
      SimpleServiceGrpc.newBlockingStub(grpcServerRule2.getChannel());

  SimpleRequest request1 = SimpleRequest.getDefaultInstance();

  SimpleRequest request2 = SimpleRequest.newBuilder().build();

  stub.unaryRpc(request1);
  stub.unaryRpc(request2);

  assertThat(testService.unaryCallRequests).containsExactly(request1, request2);
}
 
Example #29
Source File: OrcaMetricReportingServerInterceptorTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shareCallMetricRecorderInContext() throws IOException {
  final CallMetricRecorder callMetricRecorder =
      InternalCallMetricRecorder.newCallMetricRecorder();
  ServerStreamTracer.Factory callMetricRecorderSharingStreamTracerFactory =
      new ServerStreamTracer.Factory() {
    @Override
    public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata headers) {
      return new ServerStreamTracer() {
        @Override
        public Context filterContext(Context context) {
          return context.withValue(InternalCallMetricRecorder.CONTEXT_KEY, callMetricRecorder);
        }
      };
    }
  };

  final AtomicReference<CallMetricRecorder> callMetricRecorderCapture = new AtomicReference<>();
  SimpleServiceGrpc.SimpleServiceImplBase simpleServiceImpl =
      new SimpleServiceGrpc.SimpleServiceImplBase() {
        @Override
        public void unaryRpc(
            SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
          callMetricRecorderCapture.set(CallMetricRecorder.getCurrent());
          SimpleResponse response =
              SimpleResponse.newBuilder().setResponseMessage("Simple response").build();
          responseObserver.onNext(response);
          responseObserver.onCompleted();
        }
      };

  ServerInterceptor metricReportingServerInterceptor = new OrcaMetricReportingServerInterceptor();
  String serverName = InProcessServerBuilder.generateName();
  grpcCleanupRule.register(
      InProcessServerBuilder
          .forName(serverName)
          .directExecutor()
          .addStreamTracerFactory(callMetricRecorderSharingStreamTracerFactory)
          .addService(
              ServerInterceptors.intercept(simpleServiceImpl, metricReportingServerInterceptor))
          .build().start());

  ManagedChannel channel =
      grpcCleanupRule.register(InProcessChannelBuilder.forName(serverName).build());
  ClientCalls.blockingUnaryCall(channel, SIMPLE_METHOD, CallOptions.DEFAULT, REQUEST);

  assertThat(callMetricRecorderCapture.get()).isSameInstanceAs(callMetricRecorder);
}
 
Example #30
Source File: TlsTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that a server configured to require client authentication refuses to accept connections
 * from a client that has an untrusted certificate.
 */
@Test
public void serverRejectsUntrustedClientCert() throws Exception {
  // Create & start a server. It requires client authentication and trusts only the test CA.
  File serverCertFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  server = serverBuilder(0, serverCertFile, serverPrivateKeyFile, serverTrustedCaCerts)
      .addService(new SimpleServiceImpl())
      .build()
      .start();

  // Create a client. Its credentials come from a CA that the server does not trust. The client
  // trusts both test CAs, so we can be sure that the handshake failure is due to the server
  // rejecting the client's cert, not the client rejecting the server's cert.
  File clientCertChainFile = TestUtils.loadCert("badclient.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("badclient.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };
  channel = clientChannel(server.getPort(), clientContextBuilder
      .keyManager(clientCertChainFile, clientPrivateKeyFile)
      .trustManager(clientTrustedCaCerts)
      .build());
  SimpleServiceGrpc.SimpleServiceBlockingStub client = SimpleServiceGrpc.newBlockingStub(channel);

  // Check that the TLS handshake fails.
  try {
    client.unaryRpc(SimpleRequest.getDefaultInstance());
    fail("TLS handshake should have failed, but didn't; received RPC response");
  } catch (StatusRuntimeException e) {
    // GRPC reports this situation by throwing a StatusRuntimeException that wraps either a
    // javax.net.ssl.SSLHandshakeException or a java.nio.channels.ClosedChannelException.
    // Thus, reliably detecting the underlying cause is not feasible.
    assertEquals(
        Throwables.getStackTraceAsString(e),
        Status.Code.UNAVAILABLE, e.getStatus().getCode());
  }
}