io.netty.channel.local.LocalAddress Java Examples

The following examples show how to use io.netty.channel.local.LocalAddress. 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: SslServerInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailure_clientCertNotYetValid() throws Exception {
  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress = new LocalAddress("CLIENT_CERT_EXPIRED_" + sslProvider);

  nettyRule.setUpServer(
      localAddress, getServerHandler(true, true, serverSsc.key(), serverSsc.cert()));
  SelfSignedCaCertificate clientSsc =
      SelfSignedCaCertificate.create(
          "CLIENT",
          Date.from(Instant.now().plus(Duration.ofDays(1))),
          Date.from(Instant.now().plus(Duration.ofDays(2))));
  nettyRule.setUpClient(
      localAddress, getClientHandler(serverSsc.cert(), clientSsc.key(), clientSsc.cert()));

  verifySslExcpetion(
      nettyRule.getServerChannel(),
      channel -> channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get(),
      CertificateNotYetValidException.class);
}
 
Example #2
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testChannelFactoryFailureNotifiesPromise() throws Exception {
    final RuntimeException exception = new RuntimeException("newChannel crash");

    final Bootstrap bootstrap = new Bootstrap()
            .handler(dummyHandler)
            .group(groupA)
            .channelFactory(new ChannelFactory<Channel>() {
        @Override
        public Channel newChannel() {
            throw exception;
        }
    });

    ChannelFuture connectFuture = bootstrap.connect(LocalAddress.ANY);

    // Should fail with the RuntimeException.
    assertThat(connectFuture.await(10000), is(true));
    assertThat(connectFuture.cause(), sameInstance((Throwable) exception));
    assertThat(connectFuture.channel(), is(not(nullValue())));
}
 
Example #3
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncResolutionFailure() throws Exception {
    final Bootstrap bootstrapA = new Bootstrap();
    bootstrapA.group(groupA);
    bootstrapA.channel(LocalChannel.class);
    bootstrapA.resolver(new TestAddressResolverGroup(false));
    bootstrapA.handler(dummyHandler);

    final ServerBootstrap bootstrapB = new ServerBootstrap();
    bootstrapB.group(groupB);
    bootstrapB.channel(LocalServerChannel.class);
    bootstrapB.childHandler(dummyHandler);
    SocketAddress localAddress = bootstrapB.bind(LocalAddress.ANY).sync().channel().localAddress();

    // Connect to the server using the asynchronous resolver.
    ChannelFuture connectFuture = bootstrapA.connect(localAddress);

    // Should fail with the UnknownHostException.
    assertThat(connectFuture.await(10000), is(true));
    assertThat(connectFuture.cause(), is(instanceOf(UnknownHostException.class)));
    assertThat(connectFuture.channel().isOpen(), is(false));
}
 
Example #4
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncResolutionSuccess() throws Exception {
    final Bootstrap bootstrapA = new Bootstrap();
    bootstrapA.group(groupA);
    bootstrapA.channel(LocalChannel.class);
    bootstrapA.resolver(new TestAddressResolverGroup(true));
    bootstrapA.handler(dummyHandler);

    final ServerBootstrap bootstrapB = new ServerBootstrap();
    bootstrapB.group(groupB);
    bootstrapB.channel(LocalServerChannel.class);
    bootstrapB.childHandler(dummyHandler);
    SocketAddress localAddress = bootstrapB.bind(LocalAddress.ANY).sync().channel().localAddress();

    // Connect to the server using the asynchronous resolver.
    bootstrapA.connect(localAddress).sync();
}
 
Example #5
Source File: ProtocolVersionSupportTest.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInheritClusterOverride() {
  BoundCluster cluster =
      new BoundCluster(
          ClusterSpec.builder().withPeerInfo("protocol_versions", Lists.newArrayList(5)).build(),
          0L,
          null);
  BoundDataCenter dc = new BoundDataCenter(cluster);
  BoundNode node =
      new BoundNode(
          new LocalAddress(UUID.randomUUID().toString()),
          NodeSpec.builder().withName("node0").withId(0L).build(),
          Collections.emptyMap(),
          cluster,
          dc,
          null,
          timer,
          null, // channel reference only needed for closing, not useful in context of this test.
          false);

  assertThat(node.getFrameCodec().getSupportedProtocolVersions()).containsOnly(5);
  assertThat(dc.getFrameCodec().getSupportedProtocolVersions()).containsOnly(5);
  assertThat(cluster.getFrameCodec().getSupportedProtocolVersions()).containsOnly(5);
}
 
Example #6
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailure_requireClientCertificate() throws Exception {
  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress = new LocalAddress("REQUIRE_CLIENT_CERT_" + sslProvider);

  nettyRule.setUpServer(
      localAddress, getServerHandler(true, false, serverSsc.key(), serverSsc.cert()));
  nettyRule.setUpClient(
      localAddress,
      getClientHandler(
          serverSsc.cert(),
          // No client cert/private key used.
          null,
          null));

  // When the server rejects the client during handshake due to lack of client certificate, both
  // should throw exceptions.
  nettyRule.assertThatServerRootCause().isInstanceOf(SSLHandshakeException.class);
  nettyRule.assertThatClientRootCause().isInstanceOf(SSLException.class);
  assertThat(nettyRule.getClientChannel().isActive()).isFalse();
}
 
Example #7
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailure_wrongHostnameInCertificate() throws Exception {
  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create("wrong.com");
  LocalAddress localAddress = new LocalAddress("WRONG_HOSTNAME_" + sslProvider);

  nettyRule.setUpServer(
      localAddress, getServerHandler(true, false, serverSsc.key(), serverSsc.cert()));
  SelfSignedCaCertificate clientSsc = SelfSignedCaCertificate.create();
  nettyRule.setUpClient(
      localAddress, getClientHandler(serverSsc.cert(), clientSsc.key(), clientSsc.cert()));

  // When the client rejects the server cert due to wrong hostname, both the server and the client
  // throw exceptions.
  nettyRule.assertThatClientRootCause().isInstanceOf(CertificateException.class);
  nettyRule.assertThatClientRootCause().hasMessageThat().contains(SSL_HOST);
  nettyRule.assertThatServerRootCause().isInstanceOf(SSLException.class);
  assertThat(nettyRule.getClientChannel().isActive()).isFalse();
}
 
Example #8
Source File: ProtocolVersionSupportTest.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInheritClusterOverrideFromCassandraVersion() {
  BoundCluster cluster =
      new BoundCluster(ClusterSpec.builder().withCassandraVersion("2.1.17").build(), 0L, null);
  BoundDataCenter dc = new BoundDataCenter(cluster);
  BoundNode node =
      new BoundNode(
          new LocalAddress(UUID.randomUUID().toString()),
          NodeSpec.builder().withName("node0").withId(0L).build(),
          Collections.emptyMap(),
          cluster,
          dc,
          null,
          timer,
          null, // channel reference only needed for closing, not useful in context of this test.
          false);

  assertThat(node.getFrameCodec().getSupportedProtocolVersions()).containsOnly(3);
  assertThat(dc.getFrameCodec().getSupportedProtocolVersions()).containsOnly(3);
  assertThat(cluster.getFrameCodec().getSupportedProtocolVersions()).containsOnly(3);
}
 
Example #9
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_doesNotRequireClientCert() throws Exception {
  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress = new LocalAddress("DOES_NOT_REQUIRE_CLIENT_CERT_" + sslProvider);

  nettyRule.setUpServer(
      localAddress, getServerHandler(false, false, serverSsc.key(), serverSsc.cert()));
  nettyRule.setUpClient(localAddress, getClientHandler(serverSsc.cert(), null, null));

  SSLSession sslSession = setUpSslChannel(nettyRule.getClientChannel(), serverSsc.cert());
  nettyRule.assertThatMessagesWork();

  // Verify that the SSL session does not contain any client cert. Note that this SslSession is
  // for the client channel, therefore its local certificates are the remote certificates of the
  // SslSession for the server channel, and vice versa.
  assertThat(sslSession.getLocalCertificates()).isNull();
  assertThat(sslSession.getPeerCertificates()).asList().containsExactly(serverSsc.cert());
}
 
Example #10
Source File: ProtocolVersionSupportTest.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldUseProtocolVersionOverride() {
  BoundCluster cluster = new BoundCluster(ClusterSpec.builder().build(), 0L, null);
  BoundDataCenter dc = new BoundDataCenter(cluster);
  BoundNode node =
      new BoundNode(
          new LocalAddress(UUID.randomUUID().toString()),
          NodeSpec.builder()
              .withName("node0")
              .withId(0L)
              .withCassandraVersion("2.1.17")
              .withPeerInfo("protocol_versions", Lists.newArrayList(4))
              .build(),
          Collections.emptyMap(),
          cluster,
          dc,
          null,
          timer,
          null, // channel reference only needed for closing, not useful in context of this test.
          false);

  assertThat(node.getFrameCodec().getSupportedProtocolVersions()).containsOnly(4);
}
 
Example #11
Source File: ProtocolVersionSupportTest.java    From simulacron with Apache License 2.0 6 votes vote down vote up
public void testProtocolVersionForCassandraVersion(
    String cassandraVersion, Integer... expectedProtocolVersions) {
  BoundCluster cluster = new BoundCluster(ClusterSpec.builder().build(), 0L, null);
  BoundDataCenter dc = new BoundDataCenter(cluster);
  BoundNode node =
      new BoundNode(
          new LocalAddress(UUID.randomUUID().toString()),
          NodeSpec.builder()
              .withName("node0")
              .withId(0L)
              .withCassandraVersion(cassandraVersion)
              .build(),
          Collections.emptyMap(),
          cluster,
          dc,
          null,
          timer,
          null, // channel reference only needed for closing, not useful in context of this test.
          false);

  assertThat(node.getFrameCodec().getSupportedProtocolVersions())
      .containsOnly(expectedProtocolVersions);
}
 
Example #12
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  // Write before connect.  In the event connect fails, the pipeline is torn down and the handler
  // won't be able to fail the writes with the correct exception.
  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(new LocalAddress("bogus"));

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    assertThat(e).isInstanceOf(ConnectException.class);
    assertThat(e).hasMessageThat().contains("connection refused");
  }
}
 
Example #13
Source File: TestServer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
public TestServer(
    EventLoopGroup eventLoopGroup,
    LocalAddress localAddress,
    ImmutableList<? extends ChannelHandler> handlers) {
  // Creates ChannelInitializer with handlers specified
  ChannelInitializer<LocalChannel> serverInitializer =
      new ChannelInitializer<LocalChannel>() {
        @Override
        protected void initChannel(LocalChannel ch) {
          for (ChannelHandler handler : handlers) {
            ch.pipeline().addLast(handler);
          }
        }
      };
  // Sets up serverBootstrap with specified initializer, eventLoopGroup, and using
  // LocalServerChannel class
  ServerBootstrap serverBootstrap =
      new ServerBootstrap()
          .group(eventLoopGroup)
          .channel(LocalServerChannel.class)
          .childHandler(serverInitializer);

  ChannelFuture unusedFuture = serverBootstrap.bind(localAddress).syncUninterruptibly();
}
 
Example #14
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailure_clientCertExpired() throws Exception {
  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress = new LocalAddress("CLIENT_CERT_EXPIRED_" + sslProvider);

  nettyRule.setUpServer(
      localAddress, getServerHandler(true, true, serverSsc.key(), serverSsc.cert()));
  SelfSignedCaCertificate clientSsc =
      SelfSignedCaCertificate.create(
          "CLIENT",
          Date.from(Instant.now().minus(Duration.ofDays(2))),
          Date.from(Instant.now().minus(Duration.ofDays(1))));
  nettyRule.setUpClient(
      localAddress, getClientHandler(serverSsc.cert(), clientSsc.key(), clientSsc.cert()));

  verifySslExcpetion(
      nettyRule.getServerChannel(),
      channel -> channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get(),
      CertificateExpiredException.class);
}
 
Example #15
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_trustAnyClientCert() throws Exception {
  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress = new LocalAddress("TRUST_ANY_CLIENT_CERT_" + sslProvider);

  nettyRule.setUpServer(
      localAddress, getServerHandler(true, false, serverSsc.key(), serverSsc.cert()));
  SelfSignedCaCertificate clientSsc = SelfSignedCaCertificate.create();
  nettyRule.setUpClient(
      localAddress, getClientHandler(serverSsc.cert(), clientSsc.key(), clientSsc.cert()));

  SSLSession sslSession = setUpSslChannel(nettyRule.getClientChannel(), serverSsc.cert());
  nettyRule.assertThatMessagesWork();

  // Verify that the SSL session gets the client cert. Note that this SslSession is for the client
  // channel, therefore its local certificates are the remote certificates of the SslSession for
  // the server channel, and vice versa.
  assertThat(sslSession.getLocalCertificates()).asList().containsExactly(clientSsc.cert());
  assertThat(sslSession.getPeerCertificates()).asList().containsExactly(serverSsc.cert());
}
 
Example #16
Source File: NettyRule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Sets up a client channel connecting to the give local address. */
void setUpClient(LocalAddress localAddress, ChannelHandler handler) {
  checkState(echoHandler != null, "Must call setUpServer before setUpClient");
  checkState(dumpHandler == null, "Can't call setUpClient twice");
  dumpHandler = new DumpHandler();
  ChannelInitializer<LocalChannel> clientInitializer =
      new ChannelInitializer<LocalChannel>() {
        @Override
        protected void initChannel(LocalChannel ch) throws Exception {
          // Add the given handler
          ch.pipeline().addLast(handler);
          // Add the "dumpHandler" last to log the incoming message
          ch.pipeline().addLast(dumpHandler);
        }
      };
  Bootstrap b =
      new Bootstrap()
          .group(eventLoopGroup)
          .channel(LocalChannel.class)
          .handler(clientInitializer);
  clientChannel = b.connect(localAddress).syncUninterruptibly().channel();
}
 
Example #17
Source File: NettyRule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Sets up a server channel bound to the given local address. */
public void setUpServer(LocalAddress localAddress, ChannelHandler... handlers) {
  checkState(echoHandler == null, "Can't call setUpServer twice");
  echoHandler = new EchoHandler();
  ChannelInitializer<LocalChannel> serverInitializer =
      new ChannelInitializer<LocalChannel>() {
        @Override
        protected void initChannel(LocalChannel ch) {
          // Add the given handler
          ch.pipeline().addLast(handlers);
          // Add the "echoHandler" last to log the incoming message and send it back
          ch.pipeline().addLast(echoHandler);
          serverChannel = ch;
        }
      };
  ServerBootstrap sb =
      new ServerBootstrap()
          .group(eventLoopGroup)
          .channel(LocalServerChannel.class)
          .childHandler(serverInitializer);
  ChannelFuture unusedFuture = sb.bind(localAddress).syncUninterruptibly();
}
 
Example #18
Source File: SslClientInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailure_defaultTrustManager_rejectSelfSignedCert() throws Exception {
  SelfSignedCaCertificate ssc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress =
      new LocalAddress("DEFAULT_TRUST_MANAGER_REJECT_SELF_SIGNED_CERT_" + sslProvider);
  nettyRule.setUpServer(localAddress, getServerHandler(false, ssc.key(), ssc.cert()));
  SslClientInitializer<LocalChannel> sslClientInitializer =
      new SslClientInitializer<>(
          sslProvider, hostProvider, portProvider, ImmutableList.of(), null, null);
  nettyRule.setUpClient(localAddress, sslClientInitializer);
  // The connection is now terminated, both the client side and the server side should get
  // exceptions.
  nettyRule.assertThatClientRootCause().isInstanceOf(CertPathBuilderException.class);
  nettyRule.assertThatServerRootCause().isInstanceOf(SSLException.class);
  assertThat(nettyRule.getClientChannel().isActive()).isFalse();
}
 
Example #19
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void handlerRemovedFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) {
          ctx.pipeline().remove(
              ctx.pipeline().context(WriteBufferingAndExceptionHandler.class).name());
        }
      });
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  chan.connect(addr);
  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.pipeline().removeFirst();

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
    assertThat(status.getDescription()).contains("Buffer removed");
  }
}
 
Example #20
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtException_closeAtMostOnce() throws Exception {
  final AtomicInteger closes = new AtomicInteger();
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelDuplexHandler() {
        @Override
        public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
          closes.getAndIncrement();
          // Simulates a loop between this handler and the WriteBufferingAndExceptionHandler.
          ctx.fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());
          super.close(ctx, promise);
        }
      });
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  chan.connect(addr).sync();
  chan.close().sync();
  assertEquals(1, closes.get());
}
 
Example #21
Source File: ReentrantChannelTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseInFlush() throws Exception {

    LocalAddress addr = new LocalAddress("testCloseInFlush");

    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();

    Bootstrap cb = getLocalClientBootstrap();

    setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);

    Channel clientChannel = cb.connect(addr).sync().channel();

    clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            promise.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    ctx.channel().close();
                }
            });
            super.write(ctx, msg, promise);
            ctx.channel().flush();
        }
    });

    clientChannel.write(createTestBuf(2000)).sync();
    clientChannel.closeFuture().sync();

    assertLog("WRITE\nFLUSH\nCLOSE\n");
}
 
Example #22
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtExceptionFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.pipeline().fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.ABORTED);
    assertThat(status.getDescription()).contains("zap");
  }
}
 
Example #23
Source File: DefaultChannelPipelineTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelConnect() throws Exception {
    ChannelPipeline pipeline = new LocalChannel().pipeline();

    ChannelPromise promise = pipeline.channel().newPromise();
    assertTrue(promise.cancel(false));
    ChannelFuture future = pipeline.connect(new LocalAddress("test"), promise);
    assertTrue(future.isCancelled());
}
 
Example #24
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_CertSignedByOtherCA() throws Exception {
  // The self-signed cert of the CA.
  SelfSignedCaCertificate caSsc = SelfSignedCaCertificate.create();
  KeyPair keyPair = getKeyPair();
  X509Certificate serverCert = signKeyPair(caSsc, keyPair, SSL_HOST);
  LocalAddress localAddress = new LocalAddress("CERT_SIGNED_BY_OTHER_CA_" + sslProvider);

  nettyRule.setUpServer(
      localAddress,
      getServerHandler(
          true,
          false,
          keyPair.getPrivate(),
          // Serving both the server cert, and the CA cert
          serverCert,
          caSsc.cert()));
  SelfSignedCaCertificate clientSsc = SelfSignedCaCertificate.create();
  nettyRule.setUpClient(
      localAddress,
      getClientHandler(
          // Client trusts the CA cert
          caSsc.cert(), clientSsc.key(), clientSsc.cert()));

  SSLSession sslSession = setUpSslChannel(nettyRule.getClientChannel(), serverCert, caSsc.cert());
  nettyRule.assertThatMessagesWork();

  assertThat(sslSession.getLocalCertificates()).asList().containsExactly(clientSsc.cert());
  assertThat(sslSession.getPeerCertificates())
      .asList()
      .containsExactly(serverCert, caSsc.cert())
      .inOrder();
}
 
Example #25
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtReadFails() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.pipeline().fireChannelRead(Unpooled.copiedBuffer(new byte[] {'a'}));

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
    assertThat(status.getDescription()).contains("channelRead() missed");
  }
}
 
Example #26
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void waitUntilActiveHandler_channelActive() throws Exception {
  final CountDownLatch latch = new CountDownLatch(1);
  WaitUntilActiveHandler handler =
      new WaitUntilActiveHandler(new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
          assertTrue(ctx.channel().isActive());
          latch.countDown();
          super.handlerAdded(ctx);
        }
      });

  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  assertEquals(1, latch.getCount());

  chan.connect(addr).sync();
  chan.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
  assertNull(chan.pipeline().context(WaitUntilActiveHandler.class));
}
 
Example #27
Source File: HttpRequestMessageImplTest.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Test
public void testOriginalRequestInfo() {
    HttpQueryParams queryParams = new HttpQueryParams();
    queryParams.add("flag", "5");
    Headers headers = new Headers();
    headers.add("Host", "blah.netflix.com");
    request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams,
            headers,
            "192.168.0.2", "https", 7002, "localhost", new LocalAddress("777"), false);

    request.storeInboundRequest();
    HttpRequestInfo originalRequest = request.getInboundRequest();

    Assert.assertEquals(request.getPort(), originalRequest.getPort());
    Assert.assertEquals(request.getPath(), originalRequest.getPath());
    Assert.assertEquals(request.getQueryParams().getFirst("flag"),
            originalRequest.getQueryParams().getFirst("flag"));
    Assert.assertEquals(request.getHeaders().getFirst("Host"), originalRequest.getHeaders().getFirst("Host"));

    request.setPort(8080);
    request.setPath("/another/place");
    request.getQueryParams().set("flag", "20");
    request.getHeaders().set("Host", "wah.netflix.com");

    Assert.assertEquals(7002, originalRequest.getPort());
    Assert.assertEquals("/some/where", originalRequest.getPath());
    Assert.assertEquals("5", originalRequest.getQueryParams().getFirst("flag"));
    Assert.assertEquals("blah.netflix.com", originalRequest.getHeaders().getFirst("Host"));
}
 
Example #28
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void channelCloseFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.close();

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.UNAVAILABLE);
    assertThat(status.getDescription())
        .contains("Connection closing while performing protocol negotiation");
  }
}
 
Example #29
Source File: SslClientInitializerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_customTrustManager_wrongHostnameInCertificate() throws Exception {
  LocalAddress localAddress =
      new LocalAddress("CUSTOM_TRUST_MANAGER_WRONG_HOSTNAME_" + sslProvider);

  // Generate a new key pair.
  KeyPair keyPair = getKeyPair();

  // Generate a self signed certificate, and use it to sign the key pair.
  SelfSignedCaCertificate ssc = SelfSignedCaCertificate.create();
  X509Certificate cert = signKeyPair(ssc, keyPair, "wrong.com");

  // Set up the server to use the signed cert and private key to perform handshake;
  PrivateKey privateKey = keyPair.getPrivate();
  nettyRule.setUpServer(localAddress, getServerHandler(false, privateKey, cert));

  // Set up the client to trust the self signed cert used to sign the cert that server provides.
  SslClientInitializer<LocalChannel> sslClientInitializer =
      new SslClientInitializer<>(
          sslProvider, hostProvider, portProvider, ImmutableList.of(ssc.cert()), null, null);
  nettyRule.setUpClient(localAddress, sslClientInitializer);

  // When the client rejects the server cert due to wrong hostname, both the client and server
  // should throw exceptions.
  nettyRule.assertThatClientRootCause().isInstanceOf(CertificateException.class);
  nettyRule.assertThatClientRootCause().hasMessageThat().contains(SSL_HOST);
  nettyRule.assertThatServerRootCause().isInstanceOf(SSLException.class);
  assertThat(nettyRule.getClientChannel().isActive()).isFalse();
}
 
Example #30
Source File: SslClientInitializerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_customTrustManager_acceptSelfSignedCert_clientCertRequired()
    throws Exception {
  LocalAddress localAddress =
      new LocalAddress(
          "CUSTOM_TRUST_MANAGER_ACCEPT_SELF_SIGNED_CERT_CLIENT_CERT_REQUIRED_" + sslProvider);

  SelfSignedCaCertificate serverSsc = SelfSignedCaCertificate.create(SSL_HOST);
  SelfSignedCaCertificate clientSsc = SelfSignedCaCertificate.create();

  // Set up the server to require client certificate.
  nettyRule.setUpServer(localAddress, getServerHandler(true, serverSsc.key(), serverSsc.cert()));

  // Set up the client to trust the server certificate and use the client certificate.
  SslClientInitializer<LocalChannel> sslClientInitializer =
      new SslClientInitializer<>(
          sslProvider,
          hostProvider,
          portProvider,
          ImmutableList.of(serverSsc.cert()),
          () -> clientSsc.key(),
          () -> ImmutableList.of(clientSsc.cert()));
  nettyRule.setUpClient(localAddress, sslClientInitializer);

  SSLSession sslSession = setUpSslChannel(nettyRule.getClientChannel(), serverSsc.cert());
  nettyRule.assertThatMessagesWork();

  // Verify that the SNI extension is sent during handshake.
  assertThat(sniHostReceived).isEqualTo(SSL_HOST);

  // Verify that the SSL session gets the client cert. Note that this SslSession is for the client
  // channel, therefore its local certificates are the remote certificates of the SslSession for
  // the server channel, and vice versa.
  assertThat(sslSession.getLocalCertificates()).asList().containsExactly(clientSsc.cert());
  assertThat(sslSession.getPeerCertificates()).asList().containsExactly(serverSsc.cert());
}