InternalNetworkHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); if(!isInternalNetwork(channel)) { logger.error("[not internal network] {}, close channel", channel.remoteAddress()); channel.close(); } super.channelActive(ctx); } InternalNetworkHandler(String... internalIpPrefix); @Override void channelActive(ChannelHandlerContext ctx);  }
@Test public void testChannelActiveWithInternalNetwork() throws Exception { when(config.getInternalNetworkPrefix()).thenReturn(new String[]{"10"}); InternalNetworkHandler handler = new InternalNetworkHandler(config.getInternalNetworkPrefix()); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(channel.remoteAddress()).thenReturn(new InetSocketAddress("10.2.1.1", 1234)); when(ctx.channel()).thenReturn(channel); handler.channelActive(ctx); verify(channel, never()).close(); }
@Test public void testChannelActiveWithOutterNetwork() throws Exception { when(config.getInternalNetworkPrefix()).thenReturn(new String[]{"10", "26"}); InternalNetworkHandler handler = new InternalNetworkHandler(config.getInternalNetworkPrefix()); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(channel.remoteAddress()).thenReturn(new InetSocketAddress("101.2.1.1", 1234)); when(ctx.channel()).thenReturn(channel); handler.channelActive(ctx); verify(channel).close(); }
@Test public void testChannelActiveWithNoPrefixSupported() throws Exception { when(config.getInternalNetworkPrefix()).thenReturn(null); InternalNetworkHandler handler = new InternalNetworkHandler(config.getInternalNetworkPrefix()); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(channel.remoteAddress()).thenReturn(new InetSocketAddress("101.2.1.1", 1234)); when(ctx.channel()).thenReturn(channel); handler.channelActive(ctx); verify(channel, never()).close(); }