1 package com.atlassian.httpclient.apache.httpcomponents;
2
3 import com.atlassian.httpclient.api.BannedHostException;
4 import com.atlassian.httpclient.api.HostResolver;
5 import com.google.common.collect.ImmutableList;
6 import org.junit.Rule;
7 import org.junit.Test;
8 import org.junit.rules.ExpectedException;
9
10 import java.net.UnknownHostException;
11 import java.util.ArrayList;
12
13 import static org.hamcrest.CoreMatchers.isA;
14 import static org.junit.Assert.fail;
15
16 public class BannedHostResolverTest {
17
18 private static final String AWS_META_HOST = "169.254.169.254";
19
20 @Rule
21 public ExpectedException expectedException = ExpectedException.none();
22
23 @Test
24 public void testBlockSingleIP() throws UnknownHostException {
25 HostResolver resolver = new BannedHostResolver(ImmutableList.of(AWS_META_HOST + "/32"));
26
27 expectedException.expect(isA(BannedHostException.class));
28
29 resolver.resolve(AWS_META_HOST);
30 }
31
32 @Test
33 public void testIpv6AddressesCanBeBlocked() {
34 ImmutableList<String> banList = ImmutableList.of("fd12:3456:7890:1423:ffff:ffff:ffff:ffff", "0:0:0:0:0:ffff:808:808");
35 HostResolver resolver = new BannedHostResolver(banList);
36
37 assertAllIpsFail(banList, resolver);
38 }
39
40 @Test
41 public void testListRestricted() {
42 ImmutableList<String> banList = ImmutableList.of("1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4");
43 HostResolver resolver = new BannedHostResolver(banList);
44
45 assertAllIpsFail(banList, resolver);
46 }
47
48 @Test
49 public void testNoAddressesBlocked() throws UnknownHostException {
50 HostResolver resolver = new BannedHostResolver(new ArrayList<>());
51 resolver.resolve(AWS_META_HOST);
52 }
53
54 @Test
55 public void testSmallRange() throws UnknownHostException {
56 HostResolver resolver = new BannedHostResolver(ImmutableList.of("192.168.0.1/30"));
57
58 resolver.resolve("192.168.0.4");
59
60 expectedException.expect(isA(BannedHostException.class));
61 resolver.resolve("192.168.0.2");
62 }
63
64 private void assertAllIpsFail(ImmutableList<String> banList, HostResolver resolver) {
65 for (String ip : banList) {
66 try {
67 resolver.resolve(ip);
68 fail("Resolution should fail for ip " + ip);
69 } catch (UnknownHostException ignored) {
70 }
71 }
72 }
73
74 }