1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.testing.nio;
29
30 import static org.junit.Assert.assertEquals;
31 import static org.junit.Assert.assertFalse;
32 import static org.junit.Assert.assertTrue;
33
34 import java.net.InetSocketAddress;
35 import java.util.Arrays;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.Future;
38
39 import org.apache.hc.core5.function.Supplier;
40 import org.apache.hc.core5.http.ContentType;
41 import org.apache.hc.core5.http.HttpHost;
42 import org.apache.hc.core5.http.HttpResponse;
43 import org.apache.hc.core5.http.HttpStatus;
44 import org.apache.hc.core5.http.Message;
45 import org.apache.hc.core5.http.Method;
46 import org.apache.hc.core5.http.URIScheme;
47 import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
48 import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
49 import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
50 import org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer;
51 import org.apache.hc.core5.http.nio.ssl.BasicServerTlsStrategy;
52 import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
53 import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
54 import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
55 import org.apache.hc.core5.http2.impl.nio.ProtocolNegotiationException;
56 import org.apache.hc.core5.http2.impl.nio.bootstrap.H2MultiplexingRequester;
57 import org.apache.hc.core5.http2.impl.nio.bootstrap.H2MultiplexingRequesterBootstrap;
58 import org.apache.hc.core5.http2.impl.nio.bootstrap.H2ServerBootstrap;
59 import org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy;
60 import org.apache.hc.core5.http2.ssl.H2ServerTlsStrategy;
61 import org.apache.hc.core5.io.CloseMode;
62 import org.apache.hc.core5.reactor.IOReactorConfig;
63 import org.apache.hc.core5.reactor.ListenerEndpoint;
64 import org.apache.hc.core5.testing.SSLTestContexts;
65 import org.apache.hc.core5.util.ReflectionUtils;
66 import org.apache.hc.core5.util.Timeout;
67 import org.hamcrest.CoreMatchers;
68 import org.hamcrest.MatcherAssert;
69 import org.junit.Assume;
70 import org.junit.BeforeClass;
71 import org.junit.Rule;
72 import org.junit.Test;
73 import org.junit.rules.ExternalResource;
74 import org.junit.runner.RunWith;
75 import org.junit.runners.Parameterized;
76 import org.junit.runners.Parameterized.Parameters;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79
80 @RunWith(Parameterized.class)
81 public class H2AlpnTest {
82 private final Logger log = LoggerFactory.getLogger(getClass());
83
84 private static final Timeout TIMEOUT = Timeout.ofSeconds(30);
85
86 @Parameters(name = "strict h2 ALPN: {0}, h2 allowed: {1}")
87 public static Iterable<Object[]> parameters() {
88 return Arrays.asList(new Object[][] {
89 { true, true },
90 { true, false },
91 { false, true }
92 });
93 }
94
95 private final boolean strictALPN;
96 private final boolean h2Allowed;
97
98 public H2AlpnTest(final boolean strictALPN, final boolean h2Allowed) {
99 this.strictALPN = strictALPN;
100 this.h2Allowed = h2Allowed;
101 }
102
103 private HttpAsyncServer server;
104
105 @Rule
106 public ExternalResource serverResource = new ExternalResource() {
107
108 @Override
109 protected void before() throws Throwable {
110 log.debug("Starting up test server");
111 final TlsStrategy tlsStrategy = h2Allowed ?
112 new H2ServerTlsStrategy(SSLTestContexts.createServerSSLContext()) :
113 new BasicServerTlsStrategy(SSLTestContexts.createServerSSLContext());
114 server = H2ServerBootstrap.bootstrap()
115 .setIOReactorConfig(
116 IOReactorConfig.custom()
117 .setSoTimeout(TIMEOUT)
118 .build())
119 .setTlsStrategy(tlsStrategy)
120 .setStreamListener(LoggingH2StreamListener.INSTANCE)
121 .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
122 .setExceptionCallback(LoggingExceptionCallback.INSTANCE)
123 .setIOSessionListener(LoggingIOSessionListener.INSTANCE)
124 .register("*", new Supplier<AsyncServerExchangeHandler>() {
125
126 @Override
127 public AsyncServerExchangeHandler get() {
128 return new EchoHandler(2048);
129 }
130
131 })
132 .create();
133 }
134
135 @Override
136 protected void after() {
137 log.debug("Shutting down test server");
138 if (server != null) {
139 server.close(CloseMode.GRACEFUL);
140 }
141 }
142
143 };
144
145 private H2MultiplexingRequester requester;
146
147 @Rule
148 public ExternalResource clientResource = new ExternalResource() {
149
150 @Override
151 protected void before() throws Throwable {
152 log.debug("Starting up test client");
153 requester = H2MultiplexingRequesterBootstrap.bootstrap()
154 .setIOReactorConfig(IOReactorConfig.custom()
155 .setSoTimeout(TIMEOUT)
156 .build())
157 .setTlsStrategy(new H2ClientTlsStrategy(SSLTestContexts.createClientSSLContext()))
158 .setStrictALPNHandshake(strictALPN)
159 .setStreamListener(LoggingH2StreamListener.INSTANCE)
160 .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
161 .setExceptionCallback(LoggingExceptionCallback.INSTANCE)
162 .setIOSessionListener(LoggingIOSessionListener.INSTANCE)
163 .create();
164 }
165
166 @Override
167 protected void after() {
168 log.debug("Shutting down test client");
169 if (requester != null) {
170 requester.close(CloseMode.GRACEFUL);
171 }
172 }
173
174 };
175
176 @BeforeClass
177 public static void determineJavaVersion() {
178 Assume.assumeTrue("Java version must be 9 or greater", ReflectionUtils.determineJRELevel() >= 9);
179 }
180
181 @Test
182 public void testALPN() throws Exception {
183 server.start();
184 final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTPS);
185 final ListenerEndpoint listener = future.get();
186 final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
187 requester.start();
188
189 final HttpHost target = new HttpHost(URIScheme.HTTPS.id, "localhost", address.getPort());
190 final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(
191 new BasicRequestProducer(Method.POST, target, "/stuff",
192 new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)),
193 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
194 final Message<HttpResponse, String> message1;
195 try {
196 message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
197 } catch (final ExecutionException e) {
198 final Throwable cause = e.getCause();
199 assertFalse("h2 negotiation was enabled, but h2 was not negotiated", h2Allowed);
200 assertTrue(cause instanceof ProtocolNegotiationException);
201 assertEquals("ALPN: missing application protocol", cause.getMessage());
202 assertTrue("strict ALPN mode was not enabled, but the client negotiator still threw", strictALPN);
203 return;
204 }
205
206 assertTrue("h2 negotiation was disabled, but h2 was negotiated", h2Allowed);
207 MatcherAssert.assertThat(message1, CoreMatchers.notNullValue());
208 final HttpResponse response1 = message1.getHead();
209 MatcherAssert.assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
210 final String body1 = message1.getBody();
211 MatcherAssert.assertThat(body1, CoreMatchers.equalTo("some stuff"));
212 }
213 }