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.Before;
71 import org.junit.BeforeClass;
72 import org.junit.Rule;
73 import org.junit.Test;
74 import org.junit.rules.ExternalResource;
75 import org.junit.runner.RunWith;
76 import org.junit.runners.Parameterized;
77 import org.junit.runners.Parameterized.Parameters;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 @RunWith(Parameterized.class)
82 public class H2AlpnTest {
83 private final Logger log = LoggerFactory.getLogger(getClass());
84
85 private static final Timeout TIMEOUT = Timeout.ofSeconds(30);
86
87 @Parameters(name = "strict h2 ALPN: {0}, h2 allowed: {1}")
88 public static Iterable<Object[]> parameters() {
89 return Arrays.asList(new Object[][] {
90 { true, true },
91 { true, false },
92 { false, true }
93 });
94 }
95
96 private final boolean strictALPN;
97 private final boolean h2Allowed;
98
99 public H2AlpnTest(final boolean strictALPN, final boolean h2Allowed) {
100 this.strictALPN = strictALPN;
101 this.h2Allowed = h2Allowed;
102 }
103
104 private HttpAsyncServer server;
105
106 @Rule
107 public ExternalResource serverResource = new ExternalResource() {
108
109 @Override
110 protected void before() throws Throwable {
111 log.debug("Starting up test server");
112 final TlsStrategy tlsStrategy = h2Allowed ?
113 new H2ServerTlsStrategy(SSLTestContexts.createServerSSLContext()) :
114 new BasicServerTlsStrategy(SSLTestContexts.createServerSSLContext());
115 server = H2ServerBootstrap.bootstrap()
116 .setIOReactorConfig(
117 IOReactorConfig.custom()
118 .setSoTimeout(TIMEOUT)
119 .build())
120 .setTlsStrategy(tlsStrategy)
121 .setStreamListener(LoggingH2StreamListener.INSTANCE)
122 .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
123 .setExceptionCallback(LoggingExceptionCallback.INSTANCE)
124 .setIOSessionListener(LoggingIOSessionListener.INSTANCE)
125 .register("*", new Supplier<AsyncServerExchangeHandler>() {
126
127 @Override
128 public AsyncServerExchangeHandler get() {
129 return new EchoHandler(2048);
130 }
131
132 })
133 .create();
134 }
135
136 @Override
137 protected void after() {
138 log.debug("Shutting down test server");
139 if (server != null) {
140 server.close(CloseMode.GRACEFUL);
141 }
142 }
143
144 };
145
146 private H2MultiplexingRequester requester;
147
148 @Rule
149 public ExternalResource clientResource = new ExternalResource() {
150
151 @Override
152 protected void before() throws Throwable {
153 log.debug("Starting up test client");
154 requester = H2MultiplexingRequesterBootstrap.bootstrap()
155 .setIOReactorConfig(IOReactorConfig.custom()
156 .setSoTimeout(TIMEOUT)
157 .build())
158 .setTlsStrategy(new H2ClientTlsStrategy(SSLTestContexts.createClientSSLContext()))
159 .setStrictALPNHandshake(strictALPN)
160 .setStreamListener(LoggingH2StreamListener.INSTANCE)
161 .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
162 .setExceptionCallback(LoggingExceptionCallback.INSTANCE)
163 .setIOSessionListener(LoggingIOSessionListener.INSTANCE)
164 .create();
165 }
166
167 @Override
168 protected void after() {
169 log.debug("Shutting down test client");
170 if (requester != null) {
171 requester.close(CloseMode.GRACEFUL);
172 }
173 }
174
175 };
176
177 private static int JAVA_VER;
178
179 @BeforeClass
180 public static void determineJavaVersion() {
181 JAVA_VER = ReflectionUtils.determineJRELevel();
182 }
183
184 @Before
185 public void checkVersion() {
186 Assume.assumeTrue("Java version must be 9 or greater and less than 16", JAVA_VER >= 9 && JAVA_VER < 16);
187 }
188
189 @Test
190 public void testALPN() throws Exception {
191 server.start();
192 final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTPS);
193 final ListenerEndpoint listener = future.get();
194 final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
195 requester.start();
196
197 final HttpHost target = new HttpHost(URIScheme.HTTPS.id, "localhost", address.getPort());
198 final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(
199 new BasicRequestProducer(Method.POST, target, "/stuff",
200 new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)),
201 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
202 final Message<HttpResponse, String> message1;
203 try {
204 message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
205 } catch (final ExecutionException e) {
206 final Throwable cause = e.getCause();
207 assertFalse("h2 negotiation was enabled, but h2 was not negotiated", h2Allowed);
208 assertTrue(cause instanceof ProtocolNegotiationException);
209 assertEquals("ALPN: missing application protocol", cause.getMessage());
210 assertTrue("strict ALPN mode was not enabled, but the client negotiator still threw", strictALPN);
211 return;
212 }
213
214 assertTrue("h2 negotiation was disabled, but h2 was negotiated", h2Allowed);
215 MatcherAssert.assertThat(message1, CoreMatchers.notNullValue());
216 final HttpResponse response1 = message1.getHead();
217 MatcherAssert.assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
218 final String body1 = message1.getBody();
219 MatcherAssert.assertThat(body1, CoreMatchers.equalTo("some stuff"));
220 }
221 }