1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.transport.apache;
20
21 import java.io.File;
22 import java.net.URI;
23 import java.nio.charset.StandardCharsets;
24 import java.util.Base64;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Queue;
29 import java.util.concurrent.atomic.AtomicInteger;
30 import java.util.stream.Stream;
31
32 import org.apache.http.Header;
33 import org.apache.http.HttpHost;
34 import org.apache.http.HttpVersion;
35 import org.apache.http.auth.AuthOption;
36 import org.apache.http.auth.AuthSchemeProvider;
37 import org.apache.http.auth.UsernamePasswordCredentials;
38 import org.apache.http.client.config.AuthSchemes;
39 import org.apache.http.client.config.RequestConfig;
40 import org.apache.http.client.protocol.HttpClientContext;
41 import org.apache.http.config.RegistryBuilder;
42 import org.apache.http.conn.routing.HttpRoute;
43 import org.apache.http.impl.auth.BasicScheme;
44 import org.apache.http.impl.auth.BasicSchemeFactory;
45 import org.apache.http.impl.client.BasicCredentialsProvider;
46 import org.apache.http.message.BasicHeader;
47 import org.apache.http.message.BasicHttpResponse;
48 import org.apache.http.pool.ConnPoolControl;
49 import org.apache.http.pool.PoolStats;
50 import org.eclipse.aether.ConfigurationProperties;
51 import org.eclipse.aether.DefaultRepositoryCache;
52 import org.eclipse.aether.internal.test.util.TestFileUtils;
53 import org.eclipse.aether.internal.test.util.http.HttpTransporterTest;
54 import org.eclipse.aether.internal.test.util.http.RecordingTransportListener;
55 import org.eclipse.aether.repository.Proxy;
56 import org.eclipse.aether.spi.connector.transport.GetTask;
57 import org.eclipse.aether.spi.connector.transport.PeekTask;
58 import org.eclipse.aether.spi.connector.transport.PutTask;
59 import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
60 import org.eclipse.aether.spi.io.PathProcessorSupport;
61 import org.eclipse.aether.util.repository.AuthenticationBuilder;
62 import org.eclipse.jetty.server.Handler;
63 import org.eclipse.jetty.server.Request;
64 import org.eclipse.jetty.server.Response;
65 import org.eclipse.jetty.server.Server;
66 import org.eclipse.jetty.server.ServerConnector;
67 import org.eclipse.jetty.server.handler.ConnectHandler;
68 import org.eclipse.jetty.util.Callback;
69 import org.junit.jupiter.api.AfterEach;
70 import org.junit.jupiter.api.Test;
71 import org.junit.jupiter.api.parallel.ResourceLock;
72 import org.junit.jupiter.api.parallel.Resources;
73 import org.junit.jupiter.params.ParameterizedTest;
74 import org.junit.jupiter.params.provider.CsvSource;
75 import org.junit.jupiter.params.provider.ValueSource;
76
77 import static org.junit.jupiter.api.Assertions.assertEquals;
78 import static org.junit.jupiter.api.Assertions.assertNull;
79 import static org.junit.jupiter.api.Assertions.assertSame;
80 import static org.junit.jupiter.api.Assertions.assertThrows;
81 import static org.junit.jupiter.api.Assertions.assertTrue;
82
83
84
85
86
87 @ResourceLock(Resources.SYSTEM_PROPERTIES)
88 class ApacheTransporterTest extends HttpTransporterTest {
89
90 public ApacheTransporterTest() {
91 super(() -> new ApacheTransporterFactory(standardChecksumExtractor(), new PathProcessorSupport()));
92 }
93
94 @Override
95 protected Stream<String> supportedCompressionAlgorithms() {
96 return Stream.of("gzip", "deflate");
97 }
98
99 protected boolean exposeContentCodingInTransportProperties() {
100
101 return false;
102 }
103
104 @Override
105 protected boolean supportsHttp3() {
106 return false;
107 }
108
109 @Override
110 protected boolean supportsHttp2() {
111 return false;
112 }
113
114 @AfterEach
115 @Override
116 protected void tearDown() throws Exception {
117
118
119 GlobalState globalState = GlobalState.get(session);
120 if (globalState != null) {
121 globalState.close();
122 }
123 super.tearDown();
124 }
125
126 @Override
127 protected boolean supportsRetryLogging() {
128 return true;
129 }
130
131 @Test
132 void testRetryLogging_DefaultHandler() throws Exception {
133 session.setConfigProperty(ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_NAME, "default");
134 super.testRetryLogging_IoException();
135 }
136
137 @ParameterizedTest
138 @ValueSource(strings = {"http", "https"})
139 void testTransfers_SystemProxyAuthenticated(String protocol) throws Exception {
140 httpServer.setProxyAuthentication("testuser", "testpass");
141 try (SystemProperties properties = systemProxyProperties(protocol, httpServer.getHttpPort())) {
142 newTransporter("http://bad.localhost:1/");
143 assertTransfers();
144 }
145 }
146
147 @Test
148 void testSystemProxyAuthenticationDisabled() throws Exception {
149 httpServer.setProxyAuthentication("testuser", "testpass");
150 try (SystemProperties properties = systemProxyProperties("http", httpServer.getHttpPort())) {
151 session.setConfigProperty(ApacheTransporterConfigurationKeys.CONFIG_PROP_USE_SYSTEM_PROPERTIES, false);
152 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort());
153 newTransporter("http://bad.localhost:1/");
154 assertGetStatus(407);
155 }
156 }
157
158 @ParameterizedTest
159 @ValueSource(strings = {"testpass", "wrong"})
160 void testExplicitProxyCredentialsTakePrecedence(String password) throws Exception {
161 httpServer.setProxyAuthentication("testuser", "testpass");
162 try (SystemProperties properties = systemProxyProperties("http", httpServer.getHttpPort())) {
163 proxy = new Proxy(
164 Proxy.TYPE_HTTP,
165 httpServer.getHost(),
166 httpServer.getHttpPort(),
167 new AuthenticationBuilder()
168 .addUsername("testuser")
169 .addPassword(password)
170 .build());
171 newTransporter("http://bad.localhost:1/");
172 if ("testpass".equals(password)) {
173 properties.set("http.proxyPassword", "wrong");
174 assertTransfers();
175 } else {
176 assertGetStatus(407);
177 }
178 }
179 }
180
181 @ParameterizedTest
182 @CsvSource({"Host,other.invalid", "Port,1", "Port,invalid", "Port,", "User,", "Password,wrong"})
183 void testSystemProxyCredentialsMustMatch(String property, String value) throws Exception {
184 httpServer.setProxyAuthentication("testuser", "testpass");
185 try (SystemProperties properties = systemProxyProperties("http", httpServer.getHttpPort())) {
186 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort());
187 properties.set("http.proxy" + property, value);
188 newTransporter("http://bad.localhost:1/");
189 assertGetStatus(407);
190 }
191 }
192
193 @Test
194 void testSystemProxyPasswordDefaultsToEmpty() throws Exception {
195 httpServer.setProxyAuthentication("testuser", "");
196 try (SystemProperties properties = systemProxyProperties("http", httpServer.getHttpPort())) {
197 properties.set("http.proxyPassword", null);
198 newTransporter("http://bad.localhost:1/");
199 assertTransfers();
200 }
201 }
202
203 @ParameterizedTest
204 @CsvSource({"http,80", "https,443"})
205 void testSystemProxyPortDefaults(String protocol, int port) throws Exception {
206 try (SystemProperties properties = new SystemProperties()) {
207 properties.set(protocol + ".proxyHost", "proxy.example");
208 properties.set(protocol + ".proxyPort", null);
209 properties.set(protocol + ".proxyUser", protocol + "-user");
210 assertEquals(protocol + "-user", selectSystemProxyUsername(protocol, port));
211 }
212 }
213
214 @ParameterizedTest
215 @CsvSource({"http,http-user", "https,https-user"})
216 void testSystemProxyCredentialsPreferTargetProtocol(String protocol, String expectedUsername) throws Exception {
217 try (SystemProperties properties = distinctSystemProxyCredentials(8080)) {
218 assertEquals(expectedUsername, selectSystemProxyUsername(protocol, 8080));
219 }
220 }
221
222 @Test
223 void testSystemProxyCredentialsFallBackToOppositeProtocol() throws Exception {
224 try (SystemProperties properties = new SystemProperties()) {
225 properties.set("https.proxyHost", "proxy.example");
226 properties.set("https.proxyPort", "8080");
227 properties.set("https.proxyUser", "https-user");
228 assertEquals("https-user", selectSystemProxyUsername("http", 8080));
229 }
230 }
231
232 @ParameterizedTest
233 @ValueSource(ints = {401, 407})
234 void testSystemProxyCredentialsNotUsedOnDirectRoute(int status) throws Exception {
235 if (status == 401) {
236 httpServer.setAuthentication("testuser", "testpass");
237 } else {
238 httpServer.setProxyAuthentication("testuser", "testpass");
239 }
240 try (SystemProperties properties = systemProxyProperties("http", httpServer.getHttpPort())) {
241 properties.set("http.nonProxyHosts", "*");
242 newTransporter(httpServer.getHttpUrl());
243 assertGetStatus(status);
244 assertTrue(httpServer.getLogEntries().stream()
245 .allMatch(entry -> entry.getRequestHeaders().get("Authorization") == null
246 && entry.getRequestHeaders().get("Proxy-Authorization") == null));
247 }
248 }
249
250 @ParameterizedTest
251 @ValueSource(booleans = {false, true})
252 void testSystemProxyCredentialsNotUsedForServer(boolean serverCredentials) throws Exception {
253 httpServer.setProxyAuthentication("testuser", "testpass");
254 httpServer.setAuthentication("testuser", "testpass");
255 try (SystemProperties properties = systemProxyProperties("http", httpServer.getHttpPort())) {
256 if (serverCredentials) {
257 auth = new AuthenticationBuilder()
258 .addUsername("testuser")
259 .addPassword("testpass")
260 .build();
261 }
262 newTransporter("http://bad.localhost:1/");
263 if (serverCredentials) {
264 assertTransfers();
265 } else {
266 assertGetStatus(401);
267 assertTrue(httpServer.getLogEntries().stream()
268 .allMatch(entry -> entry.getRequestHeaders().get("Authorization") == null));
269 }
270 }
271 }
272
273 @ParameterizedTest
274 @ValueSource(booleans = {false, true})
275 void testSystemProxyAuthenticationThroughHttpsConnect(boolean authenticateServer) throws Exception {
276 httpServer.addHttp2ConnectorWithMutualTLS();
277 if (authenticateServer) {
278 httpServer.setAuthentication("testuser", "testpass");
279 }
280 Server proxyServer = new Server();
281 ServerConnector connector = new ServerConnector(proxyServer);
282 connector.setHost(httpServer.getHost());
283 proxyServer.addConnector(connector);
284 AtomicInteger authenticatedConnects = new AtomicInteger();
285 proxyServer.setHandler(new ConnectHandler() {
286 @Override
287 protected boolean handleAuthentication(Request request, Response response, String address) {
288 String expected = "Basic "
289 + Base64.getEncoder().encodeToString("testuser:testpass".getBytes(StandardCharsets.UTF_8));
290 if (expected.equals(request.getHeaders().get("Proxy-Authorization"))) {
291 authenticatedConnects.incrementAndGet();
292 return true;
293 }
294 response.getHeaders().put("Proxy-Authenticate", "Basic realm=\"proxy\"");
295 return false;
296 }
297 });
298 proxyServer.start();
299 try (SystemProperties properties = systemProxyProperties("https", connector.getLocalPort())) {
300 newTransporter(httpServer.getHttpsUrl());
301 if (authenticateServer) {
302 assertGetStatus(401);
303 } else {
304 assertTransfers();
305 }
306 assertTrue(authenticatedConnects.get() > 0);
307 assertTrue(httpServer.getLogEntries().stream()
308 .allMatch(entry -> entry.getRequestHeaders().get("Authorization") == null
309 && entry.getRequestHeaders().get("Proxy-Authorization") == null));
310 } finally {
311 if (transporter != null) {
312 transporter.close();
313 transporter = null;
314 }
315 proxyServer.stop();
316 }
317 }
318
319 @Test
320 void testSystemProxyCredentialsNotForwardedAfterRedirectToDirectRoute() throws Exception {
321 Server proxyServer = new Server();
322 ServerConnector connector = new ServerConnector(proxyServer);
323 connector.setHost(httpServer.getHost());
324 proxyServer.addConnector(connector);
325 AtomicInteger authenticatedRequests = new AtomicInteger();
326 proxyServer.setHandler(new Handler.Abstract() {
327 @Override
328 public boolean handle(Request request, Response response, Callback callback) throws Exception {
329 String expected = "Basic "
330 + Base64.getEncoder().encodeToString("testuser:testpass".getBytes(StandardCharsets.UTF_8));
331 if (expected.equals(request.getHeaders().get("Proxy-Authorization"))) {
332 authenticatedRequests.incrementAndGet();
333 response.setStatus(302);
334 response.getHeaders().put("Location", httpServer.getHttpUrl() + "/repo/file.txt");
335 } else {
336 response.setStatus(407);
337 response.getHeaders().put("Proxy-Authenticate", "Basic realm=\"proxy\"");
338 }
339 callback.succeeded();
340 return true;
341 }
342 });
343 proxyServer.start();
344 try (SystemProperties properties = systemProxyProperties("http", connector.getLocalPort())) {
345 properties.set("http.nonProxyHosts", httpServer.getHost());
346 newTransporter("http://bad.localhost:1/");
347 GetTask task = new GetTask(URI.create("repo/file.txt"));
348 transporter.get(task);
349 assertEquals("test", task.getDataString());
350 assertTrue(authenticatedRequests.get() > 0);
351 assertTrue(httpServer.getLogEntries().stream()
352 .allMatch(entry -> entry.getRequestHeaders().get("Authorization") == null
353 && entry.getRequestHeaders().get("Proxy-Authorization") == null));
354 } finally {
355 if (transporter != null) {
356 transporter.close();
357 transporter = null;
358 }
359 proxyServer.stop();
360 }
361 }
362
363 @ParameterizedTest
364 @CsvSource({"http,80", "https,443"})
365 void testConcurrentAuthCacheMatchesImplicitDefaultPort(String scheme, int defaultPort) {
366 HttpHost implicitPort = new HttpHost("repo.example.com", -1, scheme);
367 HttpHost explicitPort = new HttpHost("repo.example.com", defaultPort, scheme);
368 BasicScheme authScheme = new BasicScheme();
369 ApacheTransporter.ConcurrentAuthCache authCache = new ApacheTransporter.ConcurrentAuthCache();
370
371 authCache.put(implicitPort, authScheme);
372
373 assertSame(authScheme, authCache.get(explicitPort));
374 assertNull(authCache.get(new HttpHost("repo.example.com", defaultPort + 1, scheme)));
375
376 authCache.remove(explicitPort);
377
378 assertNull(authCache.get(implicitPort));
379 }
380
381 private void assertGetStatus(int status) {
382 HttpTransporterException failure = assertThrows(
383 HttpTransporterException.class, () -> transporter.get(new GetTask(URI.create("repo/file.txt"))));
384 assertEquals(status, failure.getStatusCode());
385 }
386
387 private void assertTransfers() throws Exception {
388 GetTask task = new GetTask(URI.create("repo/file.txt"));
389 transporter.get(task);
390 assertEquals("test", task.getDataString());
391 transporter.peek(new PeekTask(URI.create("repo/file.txt")));
392 transporter.put(new PutTask(URI.create("repo/upload.txt")).setDataString("upload"));
393 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "upload.txt")));
394 }
395
396 private SystemProperties systemProxyProperties(String protocol, int port) {
397 session.setConfigProperty(ApacheTransporterConfigurationKeys.CONFIG_PROP_USE_SYSTEM_PROPERTIES, true);
398 SystemProperties properties = new SystemProperties();
399 for (String scheme : new String[] {"http", "https"}) {
400 properties.set(scheme + ".proxyHost", httpServer.getHost());
401 properties.set(scheme + ".proxyPort", Integer.toString(port));
402 properties.set(scheme + ".proxyUser", null);
403 properties.set(scheme + ".proxyPassword", null);
404 }
405 properties.set(protocol + ".proxyUser", "testuser");
406 properties.set(protocol + ".proxyPassword", "testpass");
407 properties.set("http.nonProxyHosts", "");
408 return properties;
409 }
410
411 private SystemProperties distinctSystemProxyCredentials(int port) {
412 SystemProperties properties = new SystemProperties();
413 for (String protocol : new String[] {"http", "https"}) {
414 properties.set(protocol + ".proxyHost", "proxy.example");
415 properties.set(protocol + ".proxyPort", Integer.toString(port));
416 properties.set(protocol + ".proxyUser", protocol + "-user");
417 }
418 return properties;
419 }
420
421 private String selectSystemProxyUsername(String targetProtocol, int proxyPort) throws Exception {
422 HttpHost proxyHost = new HttpHost("proxy.example", proxyPort);
423 HttpClientContext context = HttpClientContext.create();
424 context.setAttribute(
425 HttpClientContext.HTTP_ROUTE,
426 new HttpRoute(new HttpHost("repository.example", -1, targetProtocol), proxyHost));
427 context.setCredentialsProvider(new BasicCredentialsProvider());
428 context.setRequestConfig(RequestConfig.DEFAULT);
429 context.setAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
430 .register(AuthSchemes.BASIC, new BasicSchemeFactory())
431 .build());
432 Map<String, Header> challenges = Collections.singletonMap(
433 AuthSchemes.BASIC.toLowerCase(), new BasicHeader("Proxy-Authenticate", "Basic realm=\"proxy\""));
434 Queue<AuthOption> options = new SystemProxyAuthenticationStrategy()
435 .select(
436 challenges,
437 proxyHost,
438 new BasicHttpResponse(HttpVersion.HTTP_1_1, 407, "Proxy Authentication Required"),
439 context);
440 UsernamePasswordCredentials credentials =
441 (UsernamePasswordCredentials) options.remove().getCredentials();
442 return credentials.getUserName();
443 }
444
445 private static final class SystemProperties implements AutoCloseable {
446 private final Map<String, String> previous = new HashMap<>();
447
448 void set(String key, String value) {
449 if (!previous.containsKey(key)) {
450 previous.put(key, System.getProperty(key));
451 }
452 if (value == null) {
453 System.clearProperty(key);
454 } else {
455 System.setProperty(key, value);
456 }
457 }
458
459 @Override
460 public void close() {
461 previous.forEach((key, value) -> {
462 if (value == null) {
463 System.clearProperty(key);
464 } else {
465 System.setProperty(key, value);
466 }
467 });
468 }
469 }
470
471 @Test
472 void testGet_WebDav() throws Exception {
473 httpServer.setWebDav(true);
474 RecordingTransportListener listener = new RecordingTransportListener();
475 GetTask task = new GetTask(URI.create("repo/dir/file.txt")).setListener(listener);
476 ((ApacheTransporter) transporter).getState().setWebDav(true);
477 transporter.get(task);
478 assertEquals("test", task.getDataString());
479 assertEquals(0L, listener.getDataOffset());
480 assertEquals(4L, listener.getDataLength());
481 assertEquals(1, listener.getStartedCount());
482 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount());
483 assertEquals(task.getDataString(), new String(listener.getBaos().toByteArray(), StandardCharsets.UTF_8));
484 assertEquals(
485 1, httpServer.getLogEntries().size(), httpServer.getLogEntries().toString());
486 }
487
488 @Test
489 void testPut_WebDav() throws Exception {
490 httpServer.setWebDav(true);
491 session.setConfigProperty(ConfigurationProperties.HTTP_SUPPORT_WEBDAV, true);
492 newTransporter(httpServer.getHttpUrl());
493
494 RecordingTransportListener listener = new RecordingTransportListener();
495 PutTask task = new PutTask(URI.create("repo/dir1/dir2/file.txt"))
496 .setListener(listener)
497 .setDataString("upload");
498 transporter.put(task);
499 assertEquals(0L, listener.getDataOffset());
500 assertEquals(6L, listener.getDataLength());
501 assertEquals(1, listener.getStartedCount());
502 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount());
503 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "dir1/dir2/file.txt")));
504
505 assertEquals(
506 5, httpServer.getLogEntries().size(), "Expected 5 requests but got: " + httpServer.getLogEntries());
507 assertEquals("OPTIONS", httpServer.getLogEntries().get(0).getMethod());
508 assertEquals("MKCOL", httpServer.getLogEntries().get(1).getMethod());
509 assertEquals("/repo/dir1/dir2/", httpServer.getLogEntries().get(1).getPath());
510 assertEquals("MKCOL", httpServer.getLogEntries().get(2).getMethod());
511 assertEquals("/repo/dir1/", httpServer.getLogEntries().get(2).getPath());
512 assertEquals("MKCOL", httpServer.getLogEntries().get(3).getMethod());
513 assertEquals("/repo/dir1/dir2/", httpServer.getLogEntries().get(3).getPath());
514 assertEquals("PUT", httpServer.getLogEntries().get(4).getMethod());
515 }
516
517 @Test
518 void testConnectionReuse() throws Exception {
519 httpServer.addHttp2ConnectorWithMutualTLS();
520 session.setCache(new DefaultRepositoryCache());
521 for (int i = 0; i < 3; i++) {
522 newTransporter(httpServer.getHttpsUrl());
523 GetTask task = new GetTask(URI.create("repo/file.txt"));
524 transporter.get(task);
525 assertEquals("test", task.getDataString());
526 }
527 PoolStats stats = ((ConnPoolControl<?>)
528 ((ApacheTransporter) transporter).getState().getConnectionManager())
529 .getTotalStats();
530 assertEquals(1, stats.getAvailable(), stats.toString());
531 }
532
533 @Test
534 void testConnectionNoReuse() throws Exception {
535 httpServer.addHttp2ConnectorWithMutualTLS();
536 session.setCache(new DefaultRepositoryCache());
537 session.setConfigProperty(ConfigurationProperties.HTTP_REUSE_CONNECTIONS, false);
538 for (int i = 0; i < 3; i++) {
539 newTransporter(httpServer.getHttpsUrl());
540 GetTask task = new GetTask(URI.create("repo/file.txt"));
541 transporter.get(task);
542 assertEquals("test", task.getDataString());
543 }
544 PoolStats stats = ((ConnPoolControl<?>)
545 ((ApacheTransporter) transporter).getState().getConnectionManager())
546 .getTotalStats();
547 assertEquals(0, stats.getAvailable(), stats.toString());
548 }
549
550 @Test
551 void testRetryHandler_badGateway_defaultCount_positive() throws Exception {
552 newTransporter(httpServer.getHttpUrl());
553 httpServer.setServerErrorsBeforeWorks(1, 502);
554 transporter.peek(new PeekTask(URI.create("repo/file.txt")));
555 }
556
557 @Test
558 void testRetryHandler_gatewayTimeout_defaultCount_positive() throws Exception {
559 newTransporter(httpServer.getHttpUrl());
560 httpServer.setServerErrorsBeforeWorks(1, 504);
561 transporter.peek(new PeekTask(URI.create("repo/file.txt")));
562 }
563 }