/
ForwardProxyTLSServerTest.java
843 lines (760 loc) · 33 KB
/
ForwardProxyTLSServerTest.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.proxy;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.URI;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.security.Principal;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpProxy;
import org.eclipse.jetty.client.Origin;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.util.BasicAuthentication;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
public class ForwardProxyTLSServerTest
{
public static Stream<SslContextFactory.Server> proxyTLS()
{
return Stream.of(null, newProxySslContextFactory());
}
private Server server;
private ServerConnector serverConnector;
private Server proxy;
private ServerConnector proxyConnector;
private SslContextFactory.Server proxySslContextFactory;
protected void startTLSServer(Handler handler) throws Exception
{
SslContextFactory.Server sslContextFactory = newServerSslContextFactory();
startTLSServer(sslContextFactory, handler);
}
protected void startTLSServer(SslContextFactory.Server sslContextFactory, Handler handler) throws Exception
{
QueuedThreadPool serverThreads = new QueuedThreadPool();
serverThreads.setName("server");
server = new Server(serverThreads);
serverConnector = new ServerConnector(server, sslContextFactory);
server.addConnector(serverConnector);
server.setHandler(handler);
server.start();
}
protected void startProxy(SslContextFactory.Server proxyTLS) throws Exception
{
startProxy(proxyTLS, new ConnectHandler());
}
protected void startProxy(SslContextFactory.Server proxyTLS, ConnectHandler connectHandler) throws Exception
{
proxySslContextFactory = proxyTLS;
QueuedThreadPool proxyThreads = new QueuedThreadPool();
proxyThreads.setName("proxy");
proxy = new Server(proxyThreads);
proxyConnector = new ServerConnector(proxy, proxyTLS);
proxy.addConnector(proxyConnector);
// Under Windows, it takes a while to detect that a connection
// attempt fails, so use an explicit timeout
connectHandler.setConnectTimeout(1000);
proxy.setHandler(connectHandler);
proxy.start();
}
protected HttpProxy newHttpProxy()
{
return new HttpProxy(new Origin.Address("localhost", proxyConnector.getLocalPort()), proxySslContextFactory != null);
}
private static SslContextFactory.Server newServerSslContextFactory()
{
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
String keyStorePath = MavenTestingUtils.getTestResourceFile("server_keystore.p12").getAbsolutePath();
sslContextFactory.setKeyStorePath(keyStorePath);
sslContextFactory.setKeyStorePassword("storepwd");
return sslContextFactory;
}
private static SslContextFactory.Server newProxySslContextFactory()
{
SslContextFactory.Server proxyTLS = new SslContextFactory.Server();
String keyStorePath = MavenTestingUtils.getTestResourceFile("proxy_keystore.p12").getAbsolutePath();
proxyTLS.setKeyStorePath(keyStorePath);
proxyTLS.setKeyStorePassword("storepwd");
return proxyTLS;
}
private static SslContextFactory.Client newClientSslContextFactory()
{
return new SslContextFactory.Client(true);
}
@AfterEach
public void stop() throws Exception
{
stopProxy();
stopServer();
}
protected void stopServer() throws Exception
{
if (server != null)
{
server.stop();
server.join();
}
}
protected void stopProxy() throws Exception
{
if (proxy != null)
{
proxy.stop();
proxy.join();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testOneExchange(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS);
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
try
{
// Use a numeric host to test the URI of the CONNECT request.
// URIs such as host:80 may interpret "host" as the scheme,
// but when the host is numeric it is not a valid URI.
String host = "127.0.0.1";
String body = "BODY";
ContentResponse response = httpClient.newRequest(host, serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertEquals(body, content);
}
finally
{
httpClient.stop();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testTwoExchanges(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS);
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
try
{
String body = "BODY";
ContentResponse response1 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response1.getStatus());
String content = response1.getContentAsString();
assertEquals(body, content);
content = "body=" + body;
ContentResponse response2 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.POST)
.path("/echo")
.header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())
.header(HttpHeader.CONTENT_LENGTH, String.valueOf(content.length()))
.content(new StringContentProvider(content))
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response2.getStatus());
content = response2.getContentAsString();
assertEquals(body, content);
}
finally
{
httpClient.stop();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testTwoConcurrentExchanges(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS);
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
try
{
AtomicReference<Connection> connection = new AtomicReference<>();
CountDownLatch connectionLatch = new CountDownLatch(1);
String content1 = "BODY";
ContentResponse response1 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(content1, "UTF-8"))
.onRequestCommit(request ->
{
Destination destination = httpClient.getDestination(HttpScheme.HTTPS.asString(), "localhost", serverConnector.getLocalPort());
destination.newConnection(new Promise.Adapter<Connection>()
{
@Override
public void succeeded(Connection result)
{
connection.set(result);
connectionLatch.countDown();
}
});
})
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response1.getStatus());
String content = response1.getContentAsString();
assertEquals(content1, content);
assertTrue(connectionLatch.await(5, TimeUnit.SECONDS));
String body2 = "body=" + content1;
org.eclipse.jetty.client.api.Request request2 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.POST)
.path("/echo")
.header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())
.header(HttpHeader.CONTENT_LENGTH, String.valueOf(body2.length()))
.content(new StringContentProvider(body2));
// Make sure the second connection can send the exchange via the tunnel
FutureResponseListener listener2 = new FutureResponseListener(request2);
connection.get().send(request2, listener2);
ContentResponse response2 = listener2.get(5, TimeUnit.SECONDS);
assertEquals(HttpStatus.OK_200, response2.getStatus());
String content2 = response2.getContentAsString();
assertEquals(content1, content2);
}
finally
{
httpClient.stop();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testShortIdleTimeoutOverriddenByRequest(SslContextFactory.Server proxyTLS) throws Exception
{
// Short idle timeout for HttpClient.
long idleTimeout = 500;
startTLSServer(new ServerHandler());
startProxy(proxyTLS, new ConnectHandler()
{
@Override
protected void handleConnect(Request baseRequest, HttpServletRequest request, HttpServletResponse response, String serverAddress)
{
try
{
// Make sure the proxy remains idle enough.
Thread.sleep(2 * idleTimeout);
super.handleConnect(baseRequest, request, response, serverAddress);
}
catch (InterruptedException x)
{
onConnectFailure(request, response, null, x);
}
}
});
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
// Short idle timeout for HttpClient.
httpClient.setIdleTimeout(idleTimeout);
httpClient.start();
try
{
String host = "localhost";
String body = "BODY";
ContentResponse response = httpClient.newRequest(host, serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
// Long idle timeout for the request.
.idleTimeout(10 * idleTimeout, TimeUnit.MILLISECONDS)
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertEquals(body, content);
}
finally
{
httpClient.stop();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyDown(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS);
int proxyPort = proxyConnector.getLocalPort();
stopProxy();
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(new HttpProxy(new Origin.Address("localhost", proxyPort), proxySslContextFactory != null));
httpClient.start();
ExecutionException x = assertThrows(ExecutionException.class, () ->
{
String body = "BODY";
httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
});
assertThat(x.getCause(), Matchers.instanceOf(ConnectException.class));
httpClient.stop();
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testServerDown(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
int serverPort = serverConnector.getLocalPort();
stopServer();
startProxy(proxyTLS);
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
assertThrows(ExecutionException.class, () ->
{
String body = "BODY";
httpClient.newRequest("localhost", serverPort)
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
});
httpClient.stop();
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyClosesConnection(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS, new ConnectHandler()
{
@Override
protected void handleConnect(Request baseRequest, HttpServletRequest request, HttpServletResponse response, String serverAddress)
{
((HttpConnection)baseRequest.getHttpChannel().getHttpTransport()).close();
}
});
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
assertThrows(ExecutionException.class, () ->
httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.timeout(5, TimeUnit.SECONDS)
.send());
httpClient.stop();
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testIPv6(SslContextFactory.Server proxyTLS) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS);
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
HttpProxy httpProxy = new HttpProxy(new Origin.Address("[::1]", proxyConnector.getLocalPort()), proxyTLS != null);
httpClient.getProxyConfiguration().getProxies().add(httpProxy);
httpClient.start();
try
{
ContentResponse response = httpClient.newRequest("[::1]", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.path("/echo?body=")
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
}
finally
{
httpClient.stop();
}
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyAuthentication(SslContextFactory.Server proxyTLS) throws Exception
{
String realm = "test-realm";
testProxyAuthentication(proxyTLS, new ConnectHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String proxyAuth = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
if (proxyAuth == null)
{
baseRequest.setHandled(true);
response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + realm + "\"");
return;
}
super.handle(target, baseRequest, request, response);
}
}, realm);
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyAuthenticationWithResponseContent(SslContextFactory.Server proxyTLS) throws Exception
{
String realm = "test-realm";
testProxyAuthentication(proxyTLS, new ConnectHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String proxyAuth = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
if (proxyAuth == null)
{
baseRequest.setHandled(true);
response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + realm + "\"");
response.getOutputStream().write(new byte[4096]);
return;
}
super.handle(target, baseRequest, request, response);
}
}, realm);
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyAuthenticationWithIncludedAddressWithResponseContent(SslContextFactory.Server proxyTLS) throws Exception
{
String realm = "test-realm";
testProxyAuthentication(proxyTLS, new ConnectHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String proxyAuth = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
if (proxyAuth == null)
{
baseRequest.setHandled(true);
response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + realm + "\"");
response.getOutputStream().write(new byte[1024]);
return;
}
super.handle(target, baseRequest, request, response);
}
}, realm, true);
}
@ParameterizedTest
@MethodSource("proxyTLS")
public void testProxyAuthenticationClosesConnection(SslContextFactory.Server proxyTLS) throws Exception
{
String realm = "test-realm";
testProxyAuthentication(proxyTLS, new ConnectHandler()
{
@Override
protected boolean handleAuthentication(HttpServletRequest request, HttpServletResponse response, String address)
{
String header = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.toString());
if (header == null || !header.startsWith("Basic "))
{
response.setHeader(HttpHeader.PROXY_AUTHENTICATE.toString(), "Basic realm=\"" + realm + "\"");
// Returning false adds Connection: close to the 407 response.
return false;
}
else
{
return true;
}
}
}, realm);
}
private void testProxyAuthentication(SslContextFactory.Server proxyTLS, ConnectHandler connectHandler, String realm) throws Exception
{
testProxyAuthentication(proxyTLS, connectHandler, realm, false);
}
private void testProxyAuthentication(SslContextFactory.Server proxyTLS, ConnectHandler connectHandler, String realm, boolean includeAddress) throws Exception
{
startTLSServer(new ServerHandler());
startProxy(proxyTLS, connectHandler);
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
HttpProxy httpProxy = newHttpProxy();
if (includeAddress)
httpProxy.getIncludedAddresses().add("localhost:" + serverConnector.getLocalPort());
httpClient.getProxyConfiguration().getProxies().add(httpProxy);
URI uri = URI.create((proxySslContextFactory == null ? "http" : "https") + "://localhost:" + proxyConnector.getLocalPort());
httpClient.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, "proxyUser", "proxyPassword"));
httpClient.start();
try
{
String host = "localhost";
String body = "BODY";
ContentResponse response = httpClient.newRequest(host, serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertEquals(body, content);
}
finally
{
httpClient.stop();
}
}
@Test
public void testBothProxyAndServerNeedClientAuth() throws Exception
{
// Keystore server_keystore.p12 contains:
// - alias "mykey": self-signed certificate with private key.
// - alias "client_root": certificate from client_keystore.p12 under the "server" alias.
// Keystore proxy_keystore.p12 contains:
// - alias "mykey": self-signed certificate with private key.
// - alias "client_root": certificate from client_keystore.p12 under the "proxy" alias.
// Keystore client_keystore.p12 contains:
// - alias "proxy": self-signed certificate with private key to send to the proxy.
// - alias "server": self-signed certificate with private key to send to the server.
// - alias "proxy_root": certificate from proxy_keystore under the "mykey" alias.
// - alias "server_root": certificate from server_keystore under the "mykey" alias.
// We want setEndpointIdentificationAlgorithm(null) for all 3 SslContextFactory
// because the certificate common names do not match the host names.
SslContextFactory.Server serverTLS = newServerSslContextFactory();
serverTLS.setEndpointIdentificationAlgorithm(null);
serverTLS.setNeedClientAuth(true);
startTLSServer(serverTLS, new ServerHandler());
int serverPort = serverConnector.getLocalPort();
String serverAlias = "server";
SslContextFactory.Server proxyTLS = newProxySslContextFactory();
proxyTLS.setEndpointIdentificationAlgorithm(null);
proxyTLS.setNeedClientAuth(true);
startProxy(proxyTLS);
int proxyPort = proxyConnector.getLocalPort();
String proxyAlias = "proxy";
SslContextFactory.Client clientSslContextFactory = new SslContextFactory.Client()
{
@Override
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception
{
KeyManager[] keyManagers = super.getKeyManagers(keyStore);
for (int i = 0; i < keyManagers.length; i++)
{
KeyManager keyManager = keyManagers[i];
if (keyManager instanceof X509ExtendedKeyManager)
{
X509ExtendedKeyManager extKeyManager = (X509ExtendedKeyManager)keyManager;
keyManagers[i] = new X509ExtendedKeyManagerWrapper(extKeyManager)
{
@Override
public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine)
{
int port = engine.getPeerPort();
if (port == serverPort)
return serverAlias;
else if (port == proxyPort)
return proxyAlias;
else
return super.chooseEngineClientAlias(keyType, issuers, engine);
}
};
}
}
return keyManagers;
}
};
clientSslContextFactory.setKeyStorePath(MavenTestingUtils.getTestResourceFile("client_keystore.p12").getAbsolutePath());
clientSslContextFactory.setKeyStorePassword("storepwd");
clientSslContextFactory.setEndpointIdentificationAlgorithm(null);
HttpClient httpClient = new HttpClient(clientSslContextFactory);
httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
httpClient.start();
try
{
String body = "BODY";
ContentResponse response = httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertEquals(body, content);
}
finally
{
httpClient.stop();
}
}
@Test
public void testBothProxyAndServerNeedClientAuthWithDifferentKeyStores() throws Exception
{
SslContextFactory.Server serverTLS = newServerSslContextFactory();
serverTLS.setEndpointIdentificationAlgorithm(null);
serverTLS.setNeedClientAuth(true);
startTLSServer(serverTLS, new ServerHandler());
int serverPort = serverConnector.getLocalPort();
SslContextFactory.Server proxyServerTLS = newProxySslContextFactory();
proxyServerTLS.setEndpointIdentificationAlgorithm(null);
proxyServerTLS.setNeedClientAuth(true);
startProxy(proxyServerTLS);
int proxyPort = proxyConnector.getLocalPort();
SslContextFactory.Client clientTLS = new SslContextFactory.Client()
{
@Override
public SSLEngine newSSLEngine(String host, int port)
{
if (port != serverPort)
throw new IllegalStateException();
return super.newSSLEngine(host, port);
}
};
clientTLS.setKeyStorePath(MavenTestingUtils.getTestResourceFile("client_server_keystore.p12").getAbsolutePath());
clientTLS.setKeyStorePassword("storepwd");
clientTLS.setEndpointIdentificationAlgorithm(null);
HttpClient httpClient = new HttpClient(clientTLS);
SslContextFactory.Client proxyClientTLS = new SslContextFactory.Client()
{
@Override
public SSLEngine newSSLEngine(String host, int port)
{
if (port != proxyPort)
throw new IllegalStateException();
return super.newSSLEngine(host, port);
}
};
proxyClientTLS.setKeyStorePath(MavenTestingUtils.getTestResourceFile("client_proxy_keystore.p12").getAbsolutePath());
proxyClientTLS.setKeyStorePassword("storepwd");
proxyClientTLS.setEndpointIdentificationAlgorithm(null);
proxyClientTLS.start();
HttpProxy httpProxy = new HttpProxy(new Origin.Address("localhost", proxyConnector.getLocalPort()), proxyClientTLS);
httpClient.getProxyConfiguration().getProxies().add(httpProxy);
httpClient.start();
try
{
String body = "BODY";
ContentResponse response = httpClient.newRequest("localhost", serverConnector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.method(HttpMethod.GET)
.path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
.timeout(5, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertEquals(body, content);
}
finally
{
httpClient.stop();
}
}
@Test
@Tag("external")
@Disabled
public void testExternalProxy() throws Exception
{
// Free proxy server obtained from http://hidemyass.com/proxy-list/
String proxyHost = "81.208.25.53";
int proxyPort = 3128;
try
{
new Socket(proxyHost, proxyPort).close();
}
catch (Throwable x)
{
assumeTrue(false, "Environment not able to connect to proxy service");
}
HttpClient httpClient = new HttpClient(newClientSslContextFactory());
httpClient.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
httpClient.start();
try
{
ContentResponse response = httpClient.newRequest("https://www.google.com")
// Use a longer timeout, sometimes the proxy takes a while to answer
.timeout(20, TimeUnit.SECONDS)
.send();
assertEquals(HttpStatus.OK_200, response.getStatus());
}
finally
{
httpClient.stop();
}
}
private static class ServerHandler extends AbstractHandler
{
@Override
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
{
request.setHandled(true);
String uri = httpRequest.getRequestURI();
if ("/echo".equals(uri))
{
String body = httpRequest.getParameter("body");
ServletOutputStream output = httpResponse.getOutputStream();
output.print(body);
}
else
{
throw new ServletException();
}
}
}
}