View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.testing.nio;
29  
30  import java.net.InetSocketAddress;
31  import java.nio.charset.StandardCharsets;
32  import java.util.Arrays;
33  import java.util.Collection;
34  import java.util.Random;
35  import java.util.concurrent.Future;
36  
37  import org.apache.hc.core5.function.Supplier;
38  import org.apache.hc.core5.http.ContentType;
39  import org.apache.hc.core5.http.HttpException;
40  import org.apache.hc.core5.http.HttpHeaders;
41  import org.apache.hc.core5.http.HttpHost;
42  import org.apache.hc.core5.http.HttpRequest;
43  import org.apache.hc.core5.http.HttpResponse;
44  import org.apache.hc.core5.http.HttpStatus;
45  import org.apache.hc.core5.http.HttpVersion;
46  import org.apache.hc.core5.http.Message;
47  import org.apache.hc.core5.http.Method;
48  import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
49  import org.apache.hc.core5.http.impl.bootstrap.AsyncServerBootstrap;
50  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
51  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
52  import org.apache.hc.core5.http.impl.bootstrap.StandardFilter;
53  import org.apache.hc.core5.http.message.BasicHttpRequest;
54  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
55  import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
56  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
57  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
58  import org.apache.hc.core5.http.nio.entity.AsyncEntityProducers;
59  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
60  import org.apache.hc.core5.http.nio.support.AbstractAsyncServerAuthFilter;
61  import org.apache.hc.core5.http.protocol.HttpContext;
62  import org.apache.hc.core5.io.CloseMode;
63  import org.apache.hc.core5.net.URIAuthority;
64  import org.apache.hc.core5.reactor.IOReactorConfig;
65  import org.apache.hc.core5.reactor.ListenerEndpoint;
66  import org.apache.hc.core5.testing.classic.LoggingConnPoolListener;
67  import org.apache.hc.core5.util.Timeout;
68  import org.hamcrest.CoreMatchers;
69  import org.junit.Assert;
70  import org.junit.Rule;
71  import org.junit.Test;
72  import org.junit.rules.ExternalResource;
73  import org.junit.runner.RunWith;
74  import org.junit.runners.Parameterized;
75  import org.slf4j.Logger;
76  import org.slf4j.LoggerFactory;
77  
78  @RunWith(Parameterized.class)
79  public class Http1AuthenticationTest {
80  
81      @Parameterized.Parameters(name = "respond immediately on auth failure: {0}")
82      public static Collection<Object[]> data() {
83          return Arrays.asList(new Object[][]{
84                  { Boolean.FALSE },
85                  { Boolean.TRUE }
86          });
87      }
88  
89      private static final Timeout TIMEOUT = Timeout.ofSeconds(30);
90  
91      private final Logger log = LoggerFactory.getLogger(getClass());
92  
93      private final boolean respondImmediately;
94      private HttpAsyncServer server;
95  
96      public Http1AuthenticationTest(final Boolean respondImmediately) {
97          this.respondImmediately = respondImmediately;
98      }
99  
100     @Rule
101     public ExternalResource serverResource = new ExternalResource() {
102 
103         @Override
104         protected void before() throws Throwable {
105             log.debug("Starting up test server");
106             server = AsyncServerBootstrap.bootstrap()
107                     .setLookupRegistry(null) // same as the default
108                     .setIOReactorConfig(
109                             IOReactorConfig.custom()
110                                     .setSoTimeout(TIMEOUT)
111                                     .build())
112                     .register("*", new Supplier<AsyncServerExchangeHandler>() {
113 
114                         @Override
115                         public AsyncServerExchangeHandler get() {
116                             return new EchoHandler(2048);
117                         }
118 
119                     })
120                     .replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractAsyncServerAuthFilter<String>(respondImmediately) {
121 
122                         @Override
123                         protected String parseChallengeResponse(
124                                 final String challenge, final HttpContext context) throws HttpException {
125                             return challenge;
126                         }
127 
128                         @Override
129                         protected boolean authenticate(
130                                 final String challengeResponse,
131                                 final URIAuthority authority,
132                                 final String requestUri,
133                                 final HttpContext context) {
134                             return challengeResponse != null && challengeResponse.equals("let me pass");
135                         }
136 
137                         @Override
138                         protected String generateChallenge(
139                                 final String challengeResponse,
140                                 final URIAuthority authority,
141                                 final String requestUri,
142                                 final HttpContext context) {
143                             return "who goes there?";
144                         }
145 
146                         @Override
147                         protected AsyncEntityProducer generateResponseContent(final HttpResponse unauthorized) {
148                             return AsyncEntityProducers.create("You shall not pass!!!");
149                         }
150                     })
151                     .setIOSessionListener(LoggingIOSessionListener.INSTANCE)
152                     .setStreamListener(LoggingHttp1StreamListener.INSTANCE_SERVER)
153                     .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
154                     .create();
155         }
156 
157         @Override
158         protected void after() {
159             log.debug("Shutting down test server");
160             if (server != null) {
161                 try {
162                     server.close(CloseMode.IMMEDIATE);
163                 } catch (final Exception ignore) {
164                 }
165             }
166         }
167 
168     };
169 
170     private HttpAsyncRequester requester;
171 
172     @Rule
173     public ExternalResource clientResource = new ExternalResource() {
174 
175         @Override
176         protected void before() throws Throwable {
177             log.debug("Starting up test client");
178             requester = AsyncRequesterBootstrap.bootstrap()
179                     .setIOReactorConfig(IOReactorConfig.custom()
180                             .setSoTimeout(TIMEOUT)
181                             .build())
182                     .setMaxTotal(2)
183                     .setDefaultMaxPerRoute(2)
184                     .setIOSessionListener(LoggingIOSessionListener.INSTANCE)
185                     .setStreamListener(LoggingHttp1StreamListener.INSTANCE_CLIENT)
186                     .setConnPoolListener(LoggingConnPoolListener.INSTANCE)
187                     .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
188                     .create();
189         }
190 
191         @Override
192         protected void after() {
193             log.debug("Shutting down test client");
194             if (requester != null) {
195                 try {
196                     requester.close(CloseMode.GRACEFUL);
197                 } catch (final Exception ignore) {
198                 }
199             }
200         }
201 
202     };
203 
204     @Test
205     public void testGetRequestAuthentication() throws Exception {
206         server.start();
207         final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0));
208         final ListenerEndpoint listener = future.get();
209         final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
210         requester.start();
211 
212         final HttpHost target = new HttpHost("localhost", address.getPort());
213 
214         final HttpRequest request1 = new BasicHttpRequest(Method.GET, target, "/stuff");
215         final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(
216                 new BasicRequestProducer(request1, null),
217                 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
218         final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
219         Assert.assertThat(message1, CoreMatchers.notNullValue());
220         final HttpResponse response1 = message1.getHead();
221         Assert.assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_UNAUTHORIZED));
222         final String body1 = message1.getBody();
223         Assert.assertThat(body1, CoreMatchers.equalTo("You shall not pass!!!"));
224 
225         final HttpRequest request2 = new BasicHttpRequest(Method.GET, target, "/stuff");
226         request2.setHeader(HttpHeaders.AUTHORIZATION, "let me pass");
227         final Future<Message<HttpResponse, String>> resultFuture2 = requester.execute(
228                 new BasicRequestProducer(request2, null),
229                 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
230         final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
231         Assert.assertThat(message2, CoreMatchers.notNullValue());
232         final HttpResponse response2 = message2.getHead();
233         Assert.assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
234         final String body2 = message2.getBody();
235         Assert.assertThat(body2, CoreMatchers.equalTo(""));
236     }
237 
238     @Test
239     public void testPostRequestAuthentication() throws Exception {
240         server.start();
241         final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0));
242         final ListenerEndpoint listener = future.get();
243         final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
244         requester.start();
245 
246         final HttpHost target = new HttpHost("localhost", address.getPort());
247         final Random rnd = new Random();
248         final byte[] stuff = new byte[10240];
249         for (int i = 0; i < stuff.length; i++) {
250             stuff[i] = (byte)('a' + rnd.nextInt(10));
251         }
252         final HttpRequest request1 = new BasicHttpRequest(Method.POST, target, "/stuff");
253         final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(
254                 new BasicRequestProducer(request1, AsyncEntityProducers.create(stuff, ContentType.TEXT_PLAIN)),
255                 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
256         final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
257         Assert.assertThat(message1, CoreMatchers.notNullValue());
258         final HttpResponse response1 = message1.getHead();
259         Assert.assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_UNAUTHORIZED));
260         final String body1 = message1.getBody();
261         Assert.assertThat(body1, CoreMatchers.equalTo("You shall not pass!!!"));
262 
263         final HttpRequest request2 = new BasicHttpRequest(Method.POST, target, "/stuff");
264         request2.setHeader(HttpHeaders.AUTHORIZATION, "let me pass");
265         final Future<Message<HttpResponse, String>> resultFuture2 = requester.execute(
266                 new BasicRequestProducer(request2, AsyncEntityProducers.create(stuff, ContentType.TEXT_PLAIN)),
267                 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
268         final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
269         Assert.assertThat(message2, CoreMatchers.notNullValue());
270         final HttpResponse response2 = message2.getHead();
271         Assert.assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
272         final String body2 = message2.getBody();
273         Assert.assertThat(body2, CoreMatchers.equalTo(new String(stuff, StandardCharsets.US_ASCII)));
274     }
275 
276     @Test
277     public void testPostRequestAuthenticationNoExpectContinue() throws Exception {
278         server.start();
279         final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0));
280         final ListenerEndpoint listener = future.get();
281         final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
282         requester.start();
283 
284         final HttpHost target = new HttpHost("localhost", address.getPort());
285         final Random rnd = new Random();
286         final byte[] stuff = new byte[10240];
287         for (int i = 0; i < stuff.length; i++) {
288             stuff[i] = (byte)('a' + rnd.nextInt(10));
289         }
290 
291         final HttpRequest request1 = new BasicHttpRequest(Method.POST, target, "/stuff");
292         request1.setVersion(HttpVersion.HTTP_1_0);
293         final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(
294                 new BasicRequestProducer(request1, AsyncEntityProducers.create(stuff, ContentType.TEXT_PLAIN)),
295                 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
296         final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
297         Assert.assertThat(message1, CoreMatchers.notNullValue());
298         final HttpResponse response1 = message1.getHead();
299         Assert.assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_UNAUTHORIZED));
300         final String body1 = message1.getBody();
301         Assert.assertThat(body1, CoreMatchers.equalTo("You shall not pass!!!"));
302 
303         final HttpRequest request2 = new BasicHttpRequest(Method.POST, target, "/stuff");
304         request2.setVersion(HttpVersion.HTTP_1_0);
305         request2.setHeader(HttpHeaders.AUTHORIZATION, "let me pass");
306         final Future<Message<HttpResponse, String>> resultFuture2 = requester.execute(
307                 new BasicRequestProducer(request2, AsyncEntityProducers.create(stuff, ContentType.TEXT_PLAIN)),
308                 new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
309         final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
310         Assert.assertThat(message2, CoreMatchers.notNullValue());
311         final HttpResponse response2 = message2.getHead();
312         Assert.assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
313         final String body2 = message2.getBody();
314         Assert.assertThat(body2, CoreMatchers.equalTo(new String(stuff, StandardCharsets.US_ASCII)));
315     }
316 
317 }