001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.eclipse.aether.internal.test.util.http; 020 021import javax.net.ssl.SSLContext; 022 023import java.io.File; 024import java.io.FileNotFoundException; 025import java.io.IOException; 026import java.io.InputStream; 027import java.net.ServerSocket; 028import java.net.URI; 029import java.nio.charset.StandardCharsets; 030import java.nio.file.Files; 031import java.nio.file.Path; 032import java.nio.file.attribute.FileTime; 033import java.security.NoSuchAlgorithmException; 034import java.time.Duration; 035import java.util.HashMap; 036import java.util.List; 037import java.util.Map; 038import java.util.concurrent.TimeUnit; 039import java.util.concurrent.atomic.AtomicReference; 040import java.util.function.Supplier; 041import java.util.regex.Pattern; 042import java.util.stream.Stream; 043 044import org.awaitility.Awaitility; 045import org.eclipse.aether.ConfigurationProperties; 046import org.eclipse.aether.DefaultRepositoryCache; 047import org.eclipse.aether.DefaultRepositorySystemSession; 048import org.eclipse.aether.DefaultSessionData; 049import org.eclipse.aether.internal.impl.transport.http.DefaultChecksumExtractor; 050import org.eclipse.aether.internal.impl.transport.http.Nx2ChecksumExtractor; 051import org.eclipse.aether.internal.impl.transport.http.XChecksumExtractor; 052import org.eclipse.aether.internal.test.util.TestFileUtils; 053import org.eclipse.aether.internal.test.util.TestLocalRepositoryManager; 054import org.eclipse.aether.repository.Authentication; 055import org.eclipse.aether.repository.Proxy; 056import org.eclipse.aether.repository.RemoteRepository; 057import org.eclipse.aether.spi.connector.transport.GetTask; 058import org.eclipse.aether.spi.connector.transport.PeekTask; 059import org.eclipse.aether.spi.connector.transport.PutTask; 060import org.eclipse.aether.spi.connector.transport.Transporter; 061import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor; 062import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractorStrategy; 063import org.eclipse.aether.spi.connector.transport.http.HttpTransporter; 064import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException; 065import org.eclipse.aether.spi.connector.transport.http.HttpTransporterFactory; 066import org.eclipse.aether.spi.connector.transport.http.RFC9457.HttpRFC9457Exception; 067import org.eclipse.aether.transfer.HttpTransportProperty; 068import org.eclipse.aether.transfer.NoTransporterException; 069import org.eclipse.aether.transfer.TransferCancelledException; 070import org.eclipse.aether.util.repository.AuthenticationBuilder; 071import org.eclipse.jetty.http.HttpVersion; 072import org.junit.jupiter.api.AfterAll; 073import org.junit.jupiter.api.AfterEach; 074import org.junit.jupiter.api.BeforeAll; 075import org.junit.jupiter.api.BeforeEach; 076import org.junit.jupiter.api.MethodOrderer; 077import org.junit.jupiter.api.Test; 078import org.junit.jupiter.api.TestInfo; 079import org.junit.jupiter.api.TestMethodOrder; 080import org.junit.jupiter.api.Timeout; 081import org.junit.jupiter.api.io.TempDir; 082import org.junit.jupiter.params.ParameterizedTest; 083import org.junit.jupiter.params.provider.ValueSource; 084 085import static java.util.Objects.requireNonNull; 086import static org.junit.jupiter.api.Assertions.assertEquals; 087import static org.junit.jupiter.api.Assertions.assertLinesMatch; 088import static org.junit.jupiter.api.Assertions.assertNotNull; 089import static org.junit.jupiter.api.Assertions.assertNull; 090import static org.junit.jupiter.api.Assertions.assertThrows; 091import static org.junit.jupiter.api.Assertions.assertTrue; 092import static org.junit.jupiter.api.Assertions.fail; 093import static org.junit.jupiter.api.Assumptions.assumeTrue; 094 095/** 096 * Common set of tests against Http transporter. 097 */ 098@SuppressWarnings({"checkstyle:methodname", "checkstyle:sizes"}) 099@TestMethodOrder(MethodOrderer.MethodName.class) 100public abstract class HttpTransporterTest { 101 102 protected static SSLContext defaultSslContext; 103 104 static { 105 // uncomment to enable SSL debugging for easier troubleshooting of SSL related test failures 106 // System.setProperty("javax.net.debug", "all"); 107 } 108 109 @BeforeAll 110 protected static void beforeAll() throws NoSuchAlgorithmException { 111 SslTestSupport.installKeyStores(); 112 // override default SSLContext to include our custom keystore and truststore (which are "cross connected" with 113 // HttpServer) 114 defaultSslContext = SSLContext.getDefault(); 115 SSLContext.setDefault(SslTestSupport.createClientSSLContext()); 116 } 117 118 @AfterAll 119 protected static void afterAll() { 120 if (defaultSslContext != null) { 121 SSLContext.setDefault(defaultSslContext); 122 } 123 } 124 125 private final Supplier<HttpTransporterFactory> transporterFactorySupplier; 126 127 protected DefaultRepositorySystemSession session; 128 129 protected HttpTransporterFactory factory; 130 131 protected HttpTransporter transporter; 132 133 protected Runnable closer; 134 135 @TempDir 136 protected Path tempDir; 137 138 protected File repoDir; 139 140 protected HttpServer httpServer; 141 142 protected Authentication auth; 143 144 protected Proxy proxy; 145 146 protected HttpTransporterTest(Supplier<HttpTransporterFactory> transporterFactorySupplier) { 147 this.transporterFactorySupplier = requireNonNull(transporterFactorySupplier); 148 } 149 150 protected static ChecksumExtractor standardChecksumExtractor() { 151 HashMap<String, ChecksumExtractorStrategy> strategies = new HashMap<>(); 152 strategies.put("1", new Nx2ChecksumExtractor()); 153 strategies.put("2", new XChecksumExtractor()); 154 return new DefaultChecksumExtractor(strategies); 155 } 156 157 protected RemoteRepository newRepo(String url) { 158 return new RemoteRepository.Builder("test", "default", url) 159 .setAuthentication(auth) 160 .setProxy(proxy) 161 .build(); 162 } 163 164 protected void newTransporter(String url) throws Exception { 165 if (transporter != null) { 166 transporter.close(); 167 transporter = null; 168 } 169 if (closer != null) { 170 closer.run(); 171 closer = null; 172 } 173 session = new DefaultRepositorySystemSession(session); 174 session.setData(new DefaultSessionData()); 175 transporter = factory.newInstance(session, newRepo(url)); 176 } 177 178 protected static final long OLD_FILE_TIMESTAMP = 160660800000L; 179 180 /** HTTP status code for "Too Many Requests". */ 181 private static final int SC_TOO_MANY_REQUESTS = 429; 182 183 @BeforeEach 184 protected void setUp(TestInfo testInfo) throws Exception { 185 System.out.println("=== " + testInfo.getDisplayName() + " ==="); 186 session = new DefaultRepositorySystemSession(h -> { 187 this.closer = h; 188 return true; 189 }); 190 session.setLocalRepositoryManager(new TestLocalRepositoryManager()); 191 factory = transporterFactorySupplier.get(); 192 repoDir = Files.createDirectories(tempDir.resolve("repo")).toFile(); 193 repoFile("file.txt", "test"); 194 repoFile("artifact.pom", "<xml>pom</xml>"); 195 repoFile("dir/file.txt", "test"); 196 Files.setLastModifiedTime(repoFile("dir/oldFile.txt", "oldTest"), FileTime.fromMillis(OLD_FILE_TIMESTAMP)); 197 repoFile("empty.txt", ""); 198 repoFile("some space.txt", "space"); 199 try (InputStream is = getCompressibleFileStream()) { 200 Files.copy(is, repoDir.toPath().resolve("compressible-file.xml")); 201 } 202 Files.setLastModifiedTime( 203 repoFile("resume.txt", "resumable"), FileTime.fromMillis(System.currentTimeMillis() - 90 * 1000)); 204 httpServer = new HttpServer().setRepoDir(repoDir).start(); 205 // always create a transporter connecting to the Http URL 206 newTransporter(httpServer.getHttpUrl()); 207 } 208 209 private static InputStream getCompressibleFileStream() { 210 return HttpTransporterTest.class.getClassLoader().getResourceAsStream("compressible-file.xml"); 211 } 212 213 /** 214 * Writes a file with the given relative name and content into the repository directory served by the test server. 215 */ 216 protected Path repoFile(String name, String content) throws IOException { 217 Path file = repoDir.toPath().resolve(name); 218 Files.createDirectories(file.getParent()); 219 return Files.write(file, content.getBytes(StandardCharsets.UTF_8)); 220 } 221 222 /** 223 * Creates a file with the given content in the per-test temporary directory. 224 */ 225 protected File tempFile(String content) throws IOException { 226 Path file = Files.createTempFile(tempDir, "tmpfile-", ".data"); 227 Files.write(file, content.getBytes(StandardCharsets.UTF_8)); 228 return file.toFile(); 229 } 230 231 @AfterEach 232 protected void tearDown() throws Exception { 233 if (transporter != null) { 234 transporter.close(); 235 transporter = null; 236 } 237 if (closer != null) { 238 closer.run(); 239 closer = null; 240 } 241 if (httpServer != null) { 242 if (closesAllConnectionsOnTransporterClose()) { 243 // check for leaked connections (e.g., due to not closing response body streams) 244 Awaitility.await().atMost(3, TimeUnit.SECONDS).until(() -> httpServer.getNumConnectedEndPoints() == 0); 245 } 246 httpServer.stop(); 247 httpServer = null; 248 } 249 factory = null; 250 session = null; 251 } 252 253 /** 254 * Indicates whether the transporter implementation closes all connections when the transporter is closed. 255 * @return {@code true} if all connections are closed on transporter close, {@code false} otherwise. 256 */ 257 protected boolean closesAllConnectionsOnTransporterClose() { 258 return true; 259 } 260 261 /** 262 * Indicates whether the transporter implementation supports preemptive authentication (i.e., sending credentials with the first request). 263 * @return {@code true} if preemptive authentication is supported, {@code false} otherwise. 264 */ 265 protected boolean supportsPreemptiveAuth() { 266 return true; 267 } 268 269 /** 270 * Indicates whether the transporter implementation supports HTTP/3. 271 * @return {@code true} if HTTP/3 is supported, {@code false} otherwise. 272 */ 273 protected boolean supportsHttp3() { 274 return true; 275 } 276 277 /** 278 * Indicates whether the transporter implementation supports HTTP/2. 279 * @return {@code true} if HTTP/2 is supported, {@code false} otherwise. 280 */ 281 protected boolean supportsHttp2() { 282 return true; 283 } 284 285 @Test 286 protected void testClassify() { 287 assertEquals(Transporter.ERROR_OTHER, transporter.classify(new FileNotFoundException())); 288 assertEquals(Transporter.ERROR_OTHER, transporter.classify(new HttpTransporterException(403))); 289 assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(new HttpTransporterException(404))); 290 assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(new HttpTransporterException(410))); 291 } 292 293 @Test 294 protected void testPeek() throws Exception { 295 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 296 } 297 298 @Test 299 protected void testPeek_DoesNotAcceptRfc9457() throws Exception { 300 // peek is HEAD request, therefore cannot support RFC 9457 301 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 302 String accept = httpServer.getLogEntries().get(0).getRequestHeaders().get("Accept"); 303 assertNull(accept, "No accept header expected for HEAD request, but was: " + accept); 304 } 305 306 @Test 307 protected void testRetryHandler_defaultCount_positive() throws Exception { 308 httpServer.setConnectionsToClose(3); 309 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 310 } 311 312 protected boolean supportsRetryLogging() { 313 return true; 314 } 315 316 @ParameterizedTest 317 @ValueSource(ints = {429, 503}) 318 protected void testRetryLogging_HttpStatus(int status) throws Exception { 319 assumeTrue(supportsRetryLogging()); 320 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 2); 321 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL, 1); 322 newTransporter(httpServer.getHttpUrl()); 323 httpServer.setServerErrorsBeforeWorks(2, status); 324 325 try (RetryLogCapture capture = new RetryLogCapture(transporter.getClass())) { 326 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 327 String request = "HEAD request to " + httpServer.getHttpUrl() + "/repo/file.txt"; 328 assertLinesMatch( 329 List.of( 330 Pattern.quote(request + " failed (attempt 1 of 3) due to status " + status 331 + ". Retrying in 1 ms") 332 + ".*\\.\\.\\.", 333 Pattern.quote(request + " failed (attempt 2 of 3) due to status " + status 334 + ". Retrying in 2 ms") 335 + ".*\\.\\.\\."), 336 capture.messages()); 337 } 338 } 339 340 @ParameterizedTest 341 @ValueSource(ints = {429, 503}) 342 protected void testRetryLogging_HttpStatusWithRetryAfter(int status) throws Exception { 343 assumeTrue(supportsRetryLogging()); 344 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 1); 345 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL, 1); 346 newTransporter(httpServer.getHttpUrl()); 347 httpServer.setServerErrorsBeforeWorks(1, status, Map.of("Retry-After", "1")); 348 349 try (RetryLogCapture capture = new RetryLogCapture(transporter.getClass())) { 350 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 351 String request = "HEAD request to " + httpServer.getHttpUrl() + "/repo/file.txt"; 352 assertLinesMatch( 353 List.of(Pattern.quote(request + " failed (attempt 1 of 2) due to status " + status 354 + ". Retrying in 1000 ms") 355 + ".*\\.\\.\\."), 356 capture.messages()); 357 } 358 } 359 360 @Test 361 protected void testRetryLogging_IoException() throws Exception { 362 assumeTrue(supportsRetryLogging()); 363 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 1); 364 newTransporter(httpServer.getHttpUrl()); 365 // Exhaust the JDK client's internal retries as well as the transporter's retries. 366 httpServer.setConnectionsToClose(100); 367 368 try (RetryLogCapture capture = new RetryLogCapture(transporter.getClass())) { 369 assertThrows(IOException.class, () -> transporter.peek(new PeekTask(URI.create("repo/file.txt")))); 370 String request = "HEAD request to " + httpServer.getHttpUrl() + "/repo/file.txt"; 371 assertLinesMatch( 372 List.of(Pattern.quote(request + " failed (attempt 1 of 2) due to ") + ".*" 373 + Pattern.quote("Retrying immediately...")), 374 capture.messages()); 375 } 376 } 377 378 @ParameterizedTest 379 @ValueSource(ints = {0, 1}) 380 protected void testRetryLogging_NoRetry(int retryCount) throws Exception { 381 assumeTrue(supportsRetryLogging()); 382 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, retryCount); 383 newTransporter(httpServer.getHttpUrl()); 384 httpServer.setServerErrorsBeforeWorks(1, retryCount == 0 ? 503 : 404); 385 386 try (RetryLogCapture capture = new RetryLogCapture(transporter.getClass())) { 387 assertThrows( 388 HttpTransporterException.class, () -> transporter.peek(new PeekTask(URI.create("repo/file.txt")))); 389 assertEquals(List.of(), capture.messages()); 390 } 391 } 392 393 @Test 394 protected void testRetryLogging_IntervalTooLong() throws Exception { 395 assumeTrue(supportsRetryLogging()); 396 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 1); 397 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL_MAX, 1); 398 newTransporter(httpServer.getHttpUrl()); 399 httpServer.setServerErrorsBeforeWorks(1, 503, Map.of("Retry-After", "1")); 400 401 try (RetryLogCapture capture = new RetryLogCapture(transporter.getClass())) { 402 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 403 String request = "HEAD request to " + httpServer.getHttpUrl() + "/repo/file.txt"; 404 assertEquals( 405 List.of( 406 request + " failed (attempt 1 of 2) due to status " + 503 407 + ". Retrying in 1 ms (due to Retry-After header with seconds value 1, capped at max value)..."), 408 capture.messages()); 409 } 410 } 411 412 @Test 413 protected void testRetryHandler_defaultCount_negative() throws Exception { 414 httpServer.setConnectionsToClose(4); 415 try { 416 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 417 fail("Expected error"); 418 } catch (Exception expected) { 419 } 420 } 421 422 @Test 423 protected void testRetryHandler_tooManyRequests_explicitCount_positive() throws Exception { 424 // set low retry count as this involves back off delays 425 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 1); 426 int retryIntervalMs = 500; 427 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL, retryIntervalMs); 428 newTransporter(httpServer.getHttpUrl()); 429 httpServer.setServerErrorsBeforeWorks(1, SC_TOO_MANY_REQUESTS); 430 long startTime = System.currentTimeMillis(); 431 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 432 assertTrue( 433 System.currentTimeMillis() - startTime >= retryIntervalMs, 434 "Expected back off delay of at least " + retryIntervalMs); 435 } 436 437 @Test 438 protected void testRetryHandler_tooManyRequests_withRetryAfterHeader_explicitCount_positive() throws Exception { 439 // set low retry count as this involves back off delays 440 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 1); 441 int retryIntervalMs = 5000; 442 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL, retryIntervalMs); 443 newTransporter(httpServer.getHttpUrl()); 444 Duration retryAfterDuration = Duration.ofSeconds(1); 445 httpServer.setServerErrorsBeforeWorks( 446 1, SC_TOO_MANY_REQUESTS, Map.of("Retry-After", String.valueOf(retryAfterDuration.getSeconds()))); 447 long startTime = System.currentTimeMillis(); 448 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 449 long elapsedTimeMs = System.currentTimeMillis() - startTime; 450 assertTrue( 451 elapsedTimeMs >= retryAfterDuration.toMillis(), 452 "Expected back off delay of at least " + retryAfterDuration.toMillis() + " ms"); 453 assertTrue(elapsedTimeMs < retryIntervalMs, "Expected back off delay of less than " + retryIntervalMs + " ms"); 454 } 455 456 @Test 457 protected void testRetryHandler_tooManyRequests_explicitCount_negative() throws Exception { 458 // set low retry count as this involves back off delays 459 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 3); 460 int retryIntervalMs = 100; 461 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL, retryIntervalMs); 462 newTransporter(httpServer.getHttpUrl()); 463 httpServer.setServerErrorsBeforeWorks(4, SC_TOO_MANY_REQUESTS); 464 long startTime = System.currentTimeMillis(); 465 try { 466 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 467 fail("Expected error"); 468 } catch (Exception expected) { 469 } 470 // linear backoff: 1x + 2x + 3x 471 long expectedMinimumDuration = retryIntervalMs * (1 + 2 + 3); 472 assertTrue( 473 System.currentTimeMillis() - startTime >= expectedMinimumDuration, 474 "Expected back off delay of at least " + expectedMinimumDuration); 475 } 476 477 @Test 478 protected void testRetryHandler_explicitCount_positive() throws Exception { 479 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 10); 480 newTransporter(httpServer.getHttpUrl()); 481 httpServer.setConnectionsToClose(10); 482 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 483 } 484 485 @Test 486 protected void testRetryHandler_disabled() throws Exception { 487 session.setConfigProperty(ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT, 0); 488 newTransporter(httpServer.getHttpUrl()); 489 httpServer.setConnectionsToClose(1); 490 try { 491 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 492 } catch (Exception expected) { 493 } 494 } 495 496 @Test 497 protected void testPeek_NotFound() throws Exception { 498 try { 499 transporter.peek(new PeekTask(URI.create("repo/missing.txt"))); 500 fail("Expected error"); 501 } catch (HttpTransporterException e) { 502 assertEquals(404, e.getStatusCode()); 503 assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); 504 } 505 } 506 507 @Test 508 protected void testPeek_Closed() throws Exception { 509 transporter.close(); 510 try { 511 transporter.peek(new PeekTask(URI.create("repo/missing.txt"))); 512 fail("Expected error"); 513 } catch (IllegalStateException e) { 514 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 515 } 516 } 517 518 @Test 519 protected void testPeek_Authenticated() throws Exception { 520 httpServer.setAuthentication("testuser", "testpass"); 521 auth = new AuthenticationBuilder() 522 .addUsername("testuser") 523 .addPassword("testpass") 524 .build(); 525 newTransporter(httpServer.getHttpUrl()); 526 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 527 } 528 529 @Test 530 protected void testPeek_Unauthenticated() throws Exception { 531 httpServer.setAuthentication("testuser", "testpass"); 532 try { 533 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 534 fail("Expected error"); 535 } catch (HttpTransporterException e) { 536 assertEquals(401, e.getStatusCode()); 537 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 538 } 539 } 540 541 @Test 542 protected void testPeek_ProxyAuthenticated() throws Exception { 543 httpServer.setProxyAuthentication("testuser", "testpass"); 544 auth = new AuthenticationBuilder() 545 .addUsername("testuser") 546 .addPassword("testpass") 547 .build(); 548 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); 549 newTransporter("http://bad.localhost:1/"); 550 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 551 } 552 553 @Test 554 protected void testPeek_ProxyUnauthenticated() throws Exception { 555 httpServer.setProxyAuthentication("testuser", "testpass"); 556 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); 557 newTransporter("http://bad.localhost:1/"); 558 try { 559 transporter.peek(new PeekTask(URI.create("repo/file.txt"))); 560 fail("Expected error"); 561 } catch (HttpTransporterException e) { 562 assertEquals(407, e.getStatusCode()); 563 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 564 } 565 } 566 567 @Test 568 protected void testPeek_SSL() throws Exception { 569 httpServer.addHttp2ConnectorWithMutualTLS(); 570 newTransporter(httpServer.getHttpsUrl()); 571 RecordingTransportListener listener = new RecordingTransportListener(); 572 PeekTask task = new PeekTask(URI.create("repo/file.txt")).setListener(listener); 573 transporter.peek(task); 574 if (exposeContentCodingInTransportProperties()) { 575 assertEquals( 576 HttpTransportProperty.SslProtocol.TLS_1_3, 577 listener.getTransportProperties().get(HttpTransportProperty.Key.SSL_PROTOCOL)); 578 } 579 } 580 581 @Test 582 protected void testPeek_Redirect() throws Exception { 583 httpServer.addHttp2ConnectorWithMutualTLS(); 584 transporter.peek(new PeekTask(URI.create("redirect/file.txt"))); 585 transporter.peek(new PeekTask(URI.create("redirect/file.txt?scheme=https"))); 586 } 587 588 @Test 589 protected void testGet_ToMemory() throws Exception { 590 RecordingTransportListener listener = new RecordingTransportListener(); 591 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 592 transporter.get(task); 593 assertEquals("test", task.getDataString()); 594 assertEquals(0L, listener.getDataOffset()); 595 assertEquals(4L, listener.getDataLength()); 596 assertEquals(1, listener.getStartedCount()); 597 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 598 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 599 } 600 601 @Test 602 protected void testGet_ToFile() throws Exception { 603 File file = tempFile("failure"); 604 RecordingTransportListener listener = new RecordingTransportListener(); 605 GetTask task = new GetTask(URI.create("repo/file.txt")) 606 .setDataPath(file.toPath()) 607 .setListener(listener); 608 transporter.get(task); 609 assertEquals("test", TestFileUtils.readString(file)); 610 assertEquals(0L, listener.getDataOffset()); 611 assertEquals(4L, listener.getDataLength()); 612 assertEquals(1, listener.getStartedCount()); 613 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 614 assertEquals("test", listener.getBaos().toString(StandardCharsets.UTF_8)); 615 } 616 617 @Test 618 protected void testGet_ToFileTimestamp() throws Exception { 619 File file = tempFile("failure"); 620 RecordingTransportListener listener = new RecordingTransportListener(); 621 GetTask task = new GetTask(URI.create("repo/dir/oldFile.txt")) 622 .setDataPath(file.toPath()) 623 .setListener(listener); 624 transporter.get(task); 625 assertEquals("oldTest", TestFileUtils.readString(file)); 626 assertEquals(0L, listener.getDataOffset()); 627 assertEquals(7L, listener.getDataLength()); 628 assertEquals(1, listener.getStartedCount()); 629 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 630 assertEquals("oldTest", listener.getBaos().toString(StandardCharsets.UTF_8)); 631 assertEquals(OLD_FILE_TIMESTAMP, file.lastModified()); 632 } 633 634 @Test 635 protected void testGet_AcceptsRfc9457() throws Exception { 636 GetTask task = new GetTask(URI.create("repo/file.txt")); 637 transporter.get(task); 638 String accept = httpServer.getLogEntries().get(0).getRequestHeaders().get("Accept"); 639 assertNotNull(accept, "Missing Accept header when retrieving artifact"); 640 assertTrue( 641 accept.contains("application/problem+json"), 642 "Expected Accept header to contain application/problem+json, but was: " + accept); 643 } 644 645 @Test 646 protected void testGet_ParseRfc9457() throws Exception { 647 // use Maven Central (Cloudflare CDN) as endpoints that return RFC 9457 responses 648 newTransporter("https://repo.maven.apache.org"); 649 try { 650 // https://blog.cloudflare.com/rfc-9457-agent-error-pages/#how-to-use-it 651 GetTask task = new GetTask(URI.create("cdn-cgi/error/1020")); 652 transporter.get(task); 653 fail("Should have throw HttpRFC9457Exception"); 654 } catch (HttpRFC9457Exception e) { 655 // Expected exception, verify the content of the RFC 9457 message. 656 assertEquals(403, e.getStatusCode()); 657 assertEquals("Error 1020: Access denied", e.getPayload().getTitle()); 658 assertEquals( 659 "The request was blocked by a Cloudflare firewall rule configured by the site owner.", 660 e.getPayload().getDetail()); 661 } 662 } 663 664 /** 665 * Provides compression algorithms supported by the transporter implementation. 666 * This should be the string value passed in the {@code Accept-Encoding} header. 667 * 668 * @return stream of supported compression algorithm names 669 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept-Encoding#directives">Accept-Encoding directives</a> 670 */ 671 protected abstract Stream<String> supportedCompressionAlgorithms(); 672 673 protected boolean exposeContentCodingInTransportProperties() { 674 return true; 675 } 676 677 @ParameterizedTest 678 // DEFLATE isn't supported by Jetty server (https://github.com/jetty/jetty.project/issues/280) 679 @ValueSource(strings = {"br", "gzip", "zstd"}) 680 protected void testGet_WithCompression(String encoding) throws Exception { 681 assumeTrue( 682 supportedCompressionAlgorithms().anyMatch(supported -> supported.equals(encoding)), 683 () -> "Transporter does not support compression algorithm: " + encoding); 684 RecordingTransportListener listener = new RecordingTransportListener(); 685 // requires a file with at least 48/50 bytes (otherwise compression is disabled, 686 // https://github.com/jetty/jetty.project/blob/2264d3d9f9586f3e5e9040fba779ed72e931cb46/jetty-core/jetty-compression/jetty-compression-brotli/src/main/java/org/eclipse/jetty/compression/brotli/BrotliCompression.java#L61) 687 GetTask task = new GetTask(URI.create(encoding + "/repo/compressible-file.xml")).setListener(listener); 688 transporter.get(task); 689 String acceptEncoding = 690 httpServer.getLogEntries().get(0).getRequestHeaders().get("Accept-Encoding"); 691 assertNotNull(acceptEncoding, "Missing Accept-Encoding header when retrieving pom"); 692 assertTrue(acceptEncoding.contains(encoding)); 693 // check original response header sent by server (client transparently handles compression and removes it) 694 // see https://issues.apache.org/jira/browse/HTTPCORE-792 695 // and https://github.com/mizosoft/methanol/issues/182 696 for (HttpServer.LogEntry log : httpServer.getLogEntries()) { 697 assertEquals(encoding, log.getResponseHeaders().get("Content-Encoding")); 698 } 699 String expectedResourceData; 700 try (InputStream is = getCompressibleFileStream()) { 701 expectedResourceData = new String(is.readAllBytes(), StandardCharsets.UTF_8); 702 } 703 assertEquals(expectedResourceData, task.getDataString()); 704 assertEquals(0L, listener.getDataOffset()); 705 // data length is unknown as chunked transfer encoding is used with compression 706 assertEquals(-1, listener.getDataLength()); 707 assertEquals(1, listener.getStartedCount()); 708 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 709 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 710 if (exposeContentCodingInTransportProperties()) { 711 assertEquals(encoding, listener.getTransportProperties().get(HttpTransportProperty.Key.CONTENT_CODING)); 712 } 713 } 714 715 @Test 716 protected void testGet_EmptyResource() throws Exception { 717 File file = tempFile("failure"); 718 RecordingTransportListener listener = new RecordingTransportListener(); 719 GetTask task = new GetTask(URI.create("repo/empty.txt")) 720 .setDataPath(file.toPath()) 721 .setListener(listener); 722 transporter.get(task); 723 assertEquals("", TestFileUtils.readString(file)); 724 assertEquals(0L, listener.getDataOffset()); 725 assertEquals(0L, listener.getDataLength()); 726 assertEquals(1, listener.getStartedCount()); 727 assertEquals(0, listener.getProgressedCount()); 728 assertEquals("", listener.getBaos().toString(StandardCharsets.UTF_8)); 729 } 730 731 @Test 732 protected void testGet_EncodedResourcePath() throws Exception { 733 GetTask task = new GetTask(URI.create("repo/some%20space.txt")); 734 transporter.get(task); 735 assertEquals("space", task.getDataString()); 736 } 737 738 @Test 739 protected void testGet_Authenticated() throws Exception { 740 httpServer.setAuthentication("testuser", "testpass"); 741 auth = new AuthenticationBuilder() 742 .addUsername("testuser") 743 .addPassword("testpass") 744 .build(); 745 newTransporter(httpServer.getHttpUrl()); 746 RecordingTransportListener listener = new RecordingTransportListener(); 747 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 748 transporter.get(task); 749 assertEquals("test", task.getDataString()); 750 assertEquals(0L, listener.getDataOffset()); 751 assertEquals(4L, listener.getDataLength()); 752 assertEquals(1, listener.getStartedCount()); 753 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 754 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 755 } 756 757 @Test 758 protected void testGet_Unauthenticated() throws Exception { 759 httpServer.setAuthentication("testuser", "testpass"); 760 try { 761 transporter.get(new GetTask(URI.create("repo/file.txt"))); 762 fail("Expected error"); 763 } catch (HttpTransporterException e) { 764 assertEquals(401, e.getStatusCode()); 765 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 766 } 767 } 768 769 @Test 770 protected void testGet_ProxyAuthenticated() throws Exception { 771 httpServer.setProxyAuthentication("testuser", "testpass"); 772 Authentication auth = new AuthenticationBuilder() 773 .addUsername("testuser") 774 .addPassword("testpass") 775 .build(); 776 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); 777 newTransporter("http://bad.localhost:1/"); 778 RecordingTransportListener listener = new RecordingTransportListener(); 779 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 780 transporter.get(task); 781 assertEquals("test", task.getDataString()); 782 assertEquals(0L, listener.getDataOffset()); 783 assertEquals(4L, listener.getDataLength()); 784 assertEquals(1, listener.getStartedCount()); 785 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 786 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 787 } 788 789 @Test 790 protected void testGet_ProxyUnauthenticated() throws Exception { 791 httpServer.setProxyAuthentication("testuser", "testpass"); 792 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); 793 newTransporter("http://bad.localhost:1/"); 794 try { 795 transporter.get(new GetTask(URI.create("repo/file.txt"))); 796 fail("Expected error"); 797 } catch (HttpTransporterException e) { 798 assertEquals(407, e.getStatusCode()); 799 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 800 } 801 } 802 803 @Test 804 protected void testGet_RFC9457Response() throws Exception { 805 try { 806 transporter.get(new GetTask(URI.create("rfc9457/file.txt"))); 807 fail("Expected error"); 808 } catch (HttpRFC9457Exception e) { 809 assertEquals(403, e.getStatusCode()); 810 assertEquals(e.getPayload().getType(), URI.create("https://example.com/probs/out-of-credit")); 811 assertEquals(403, e.getPayload().getStatus()); 812 assertEquals("You do not have enough credit.", e.getPayload().getTitle()); 813 assertEquals( 814 "Your current balance is 30, but that costs 50.", 815 e.getPayload().getDetail()); 816 assertEquals(URI.create("/account/12345/msgs/abc"), e.getPayload().getInstance()); 817 } 818 } 819 820 @Test 821 protected void testGet_RFC9457Response_with_missing_fields() throws Exception { 822 try { 823 transporter.get(new GetTask(URI.create("rfc9457/missing_fields.txt"))); 824 fail("Expected error"); 825 } catch (HttpRFC9457Exception e) { 826 assertEquals(403, e.getStatusCode()); 827 assertEquals(e.getPayload().getType(), URI.create("about:blank")); 828 assertNull(e.getPayload().getStatus()); 829 assertNull(e.getPayload().getTitle()); 830 assertNull(e.getPayload().getDetail()); 831 assertNull(e.getPayload().getInstance()); 832 } 833 } 834 835 @Test 836 protected void testGet_SSL() throws Exception { 837 httpServer.addHttp2ConnectorWithMutualTLS(); 838 newTransporter(httpServer.getHttpsUrl()); 839 RecordingTransportListener listener = new RecordingTransportListener(); 840 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 841 transporter.get(task); 842 assertEquals("test", task.getDataString()); 843 assertEquals(0L, listener.getDataOffset()); 844 assertEquals(4L, listener.getDataLength()); 845 assertEquals(1, listener.getStartedCount()); 846 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 847 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 848 if (exposeContentCodingInTransportProperties()) { 849 assertEquals( 850 HttpTransportProperty.SslProtocol.TLS_1_3, 851 listener.getTransportProperties().get(HttpTransportProperty.Key.SSL_PROTOCOL)); 852 assertEquals( 853 "TLS_AES_256_GCM_SHA384", 854 listener.getTransportProperties().get(HttpTransportProperty.Key.SSL_CIPHER_SUITE)); 855 } 856 } 857 858 @Test 859 protected void testGet_SSL_WithServerErrors() throws Exception { 860 httpServer.setServerErrorsBeforeWorks(1); 861 httpServer.addHttp2ConnectorWithMutualTLS(); 862 newTransporter(httpServer.getHttpsUrl()); 863 for (int i = 1; i < 3; i++) { 864 try { 865 RecordingTransportListener listener = new RecordingTransportListener(); 866 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 867 transporter.get(task); 868 assertEquals("test", task.getDataString()); 869 assertEquals(0L, listener.getDataOffset()); 870 assertEquals(4L, listener.getDataLength()); 871 assertEquals(1, listener.getStartedCount()); 872 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 873 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 874 } catch (HttpTransporterException e) { 875 assertEquals(500, e.getStatusCode()); 876 } 877 } 878 } 879 880 @Test 881 protected void testGet_HTTPS_Unknown_SecurityMode() throws Exception { 882 session.setConfigProperty(ConfigurationProperties.HTTPS_SECURITY_MODE, "unknown"); 883 httpServer.addHttp2Connector(); 884 try { 885 newTransporter(httpServer.getHttpsUrl()); 886 fail("Unsupported security mode"); 887 } catch (IllegalArgumentException a) { 888 // good 889 } 890 } 891 892 @Test 893 protected void testGet_HTTPS_Insecure_SecurityMode() throws Exception { 894 // we have to reset the default ssl context to avoid the default truststore being used, which would make the 895 // test pass even if the security mode is not set to insecure 896 SSLContext.setDefault(defaultSslContext); 897 try { 898 session.setConfigProperty( 899 ConfigurationProperties.HTTPS_SECURITY_MODE, ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE); 900 httpServer.addHttp2Connector(); 901 newTransporter(httpServer.getHttpsUrl()); 902 RecordingTransportListener listener = new RecordingTransportListener(); 903 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 904 transporter.get(task); 905 assertEquals("test", task.getDataString()); 906 assertEquals(0L, listener.getDataOffset()); 907 assertEquals(4L, listener.getDataLength()); 908 assertEquals(1, listener.getStartedCount()); 909 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 910 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 911 } finally { 912 // restore the default SSL context used for all other tests 913 SSLContext.setDefault(SslTestSupport.createClientSSLContext()); 914 } 915 } 916 917 @Test 918 protected void testGet_HTTPS_HTTP2Only_Insecure_SecurityMode() throws Exception { 919 assumeTrue(supportsHttp2(), "Transporter does not support HTTP/2"); 920 // we have to reset the default ssl context to avoid the default truststore being used, which would make the 921 // test pass even if the security mode is not set to insecure 922 SSLContext.setDefault(defaultSslContext); 923 try { 924 session.setConfigProperty(ConfigurationProperties.HTTP_VERSION, ConfigurationProperties.HttpVersion.HTTP_2); 925 session.setConfigProperty( 926 ConfigurationProperties.HTTPS_SECURITY_MODE, ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE); 927 httpServer.addHttp2OnlyConnector(); 928 newTransporter(httpServer.getHttpsUrl()); 929 RecordingTransportListener listener = new RecordingTransportListener(); 930 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 931 transporter.get(task); 932 assertEquals("test", task.getDataString()); 933 assertEquals(0L, listener.getDataOffset()); 934 assertEquals(4L, listener.getDataLength()); 935 assertEquals(1, listener.getStartedCount()); 936 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 937 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 938 httpServer.getLogEntries().forEach(log -> { 939 assertEquals(HttpVersion.HTTP_2, log.getVersion()); 940 }); 941 } finally { 942 // restore the default SSL context used for all other tests 943 SSLContext.setDefault(SslTestSupport.createClientSSLContext()); 944 } 945 } 946 947 @Test 948 protected void testGet_HTTP3Only() throws Exception { 949 assumeTrue(supportsHttp3(), "Transporter does not support HTTP/3"); 950 session.setConfigProperty(ConfigurationProperties.HTTP_VERSION, ConfigurationProperties.HttpVersion.HTTP_3); 951 httpServer.addHttp3Connector(false); 952 httpServer.start(); 953 newTransporter(httpServer.getHttp3Url()); 954 RecordingTransportListener listener = new RecordingTransportListener(); 955 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 956 transporter.get(task); 957 assertEquals("test", task.getDataString()); 958 assertEquals(0L, listener.getDataOffset()); 959 assertEquals(4L, listener.getDataLength()); 960 assertEquals(1, listener.getStartedCount()); 961 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 962 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 963 httpServer.getLogEntries().forEach(log -> { 964 assertEquals(HttpVersion.HTTP_3, log.getVersion()); 965 }); 966 } 967 968 @Test 969 protected void testGet_HTTP3() throws Exception { 970 assumeTrue(supportsHttp3(), "Transporter does not support HTTP/3"); 971 session.setConfigProperty(ConfigurationProperties.HTTP_VERSION, ConfigurationProperties.HttpVersion.HTTP_3); 972 // both HTTP2 and HTTP3 endpoints are available at the same port 973 // reserve a port free for both TCP and UDP, as the same-numbered UDP port of an OS-assigned TCP port may be 974 // taken (https://github.com/apache/maven-resolver/issues/2036) 975 int port = httpServer.findFreeTcpAndUdpPort(); 976 httpServer.addHttp2OnlyConnectorWithMutualTLS(port); 977 httpServer.addHttp3Connector(false, port); 978 // alt-svc header should point to http/3 979 httpServer.start(); 980 newTransporter(httpServer.getHttp3Url()); 981 RecordingTransportListener listener = new RecordingTransportListener(); 982 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 983 // issue 2 requests to ensure that the second request is HTTP/3 (the first one may be HTTP/2 if the TCP 984 // connection is faster) 985 transporter.get(task); 986 transporter.get(task); 987 assertEquals("test", task.getDataString()); 988 assertEquals(0L, listener.getDataOffset()); 989 assertEquals(4L, listener.getDataLength()); 990 assertEquals(2, listener.getStartedCount()); 991 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 992 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 993 // the last request should be HTTP/3 finally 994 assertEquals( 995 HttpVersion.HTTP_3, 996 httpServer 997 .getLogEntries() 998 .get(httpServer.getLogEntries().size() - 1) 999 .getVersion()); 1000 } 1001 1002 @Test 1003 protected void testGet_HTTP3FallbackToHTTP2() throws Exception { 1004 assumeTrue(supportsHttp3(), "Transporter does not support HTTP/3"); 1005 session.setConfigProperty(ConfigurationProperties.HTTP_VERSION, ConfigurationProperties.HttpVersion.HTTP_3); 1006 httpServer.addHttp2OnlyConnectorWithMutualTLS(); 1007 httpServer.start(); 1008 newTransporter(httpServer.getHttpsUrl()); 1009 RecordingTransportListener listener = new RecordingTransportListener(); 1010 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 1011 transporter.get(task); 1012 assertEquals("test", task.getDataString()); 1013 assertEquals(0L, listener.getDataOffset()); 1014 assertEquals(4L, listener.getDataLength()); 1015 assertEquals(1, listener.getStartedCount()); 1016 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1017 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 1018 assertEquals( 1019 HttpTransportProperty.HttpVersion.HTTP_2, 1020 listener.getTransportProperties().get(HttpTransportProperty.Key.HTTP_VERSION)); 1021 httpServer.getLogEntries().forEach(log -> { 1022 assertEquals(HttpVersion.HTTP_2, log.getVersion()); 1023 }); 1024 } 1025 1026 @Test 1027 protected void testGet_Redirect() throws Exception { 1028 httpServer.addHttp2ConnectorWithMutualTLS(); 1029 RecordingTransportListener listener = new RecordingTransportListener(); 1030 GetTask task = new GetTask(URI.create("redirect/file.txt?scheme=https")).setListener(listener); 1031 transporter.get(task); 1032 assertEquals("test", task.getDataString()); 1033 assertEquals(0L, listener.getDataOffset()); 1034 assertEquals(4L, listener.getDataLength()); 1035 assertEquals(1, listener.getStartedCount()); 1036 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1037 assertEquals(task.getDataString(), listener.getBaos().toString(StandardCharsets.UTF_8)); 1038 } 1039 1040 @Test 1041 protected void testGet_Redirect_ModeNone() throws Exception { 1042 session.setConfigProperty( 1043 ConfigurationProperties.HTTP_REDIRECT_MODE + ".test", ConfigurationProperties.RedirectMode.NONE); 1044 newTransporter(httpServer.getHttpUrl()); 1045 1046 assertThrows(Exception.class, () -> transporter.get(new GetTask(URI.create("redirect/file.txt")))); 1047 assertEquals(1, httpServer.getLogEntries().size()); 1048 } 1049 1050 @Test 1051 protected void testGet_Redirect_ModeSameAuthority() throws Exception { 1052 session.setConfigProperty( 1053 ConfigurationProperties.HTTP_REDIRECT_MODE + ".test", 1054 ConfigurationProperties.RedirectMode.SAME_AUTHORITY); 1055 newTransporter(httpServer.getHttpUrl()); 1056 1057 GetTask task = new GetTask(URI.create("redirect/file.txt")); 1058 transporter.get(task); 1059 1060 assertEquals("test", task.getDataString()); 1061 assertEquals(2, httpServer.getLogEntries().size()); 1062 } 1063 1064 @Test 1065 protected void testGet_Redirect_ModeSameAuthorityRefusesDifferentAuthority() throws Exception { 1066 session.setConfigProperty( 1067 ConfigurationProperties.HTTP_REDIRECT_MODE + ".test", 1068 ConfigurationProperties.RedirectMode.SAME_AUTHORITY); 1069 newTransporter(httpServer.getHttpUrl()); 1070 1071 assertThrows( 1072 Exception.class, () -> transporter.get(new GetTask(URI.create("redirect/file.txt?host=127.0.0.1")))); 1073 assertEquals(1, httpServer.getLogEntries().size()); 1074 } 1075 1076 @Test 1077 protected void testGet_Redirect_ModeAnyAllowsDifferentAuthority() throws Exception { 1078 session.setConfigProperty(ConfigurationProperties.HTTP_REDIRECT_MODE, ConfigurationProperties.RedirectMode.ANY); 1079 newTransporter(httpServer.getHttpUrl()); 1080 1081 GetTask task = new GetTask(URI.create("redirect/file.txt?host=127.0.0.1")); 1082 transporter.get(task); 1083 1084 assertEquals("test", task.getDataString()); 1085 assertEquals(2, httpServer.getLogEntries().size()); 1086 } 1087 1088 @Test 1089 protected void testGet_Redirect_OriginScopedHeadersByDefault() throws Exception { 1090 Map<String, String> headers = Map.of("X-Secret", "secret"); 1091 session.setConfigProperty(ConfigurationProperties.HTTP_HEADERS + ".test", headers); 1092 newTransporter(httpServer.getHttpUrl()); 1093 1094 transporter.get(new GetTask(URI.create("redirect/file.txt?host=127.0.0.1"))); 1095 1096 assertEquals(2, httpServer.getLogEntries().size()); 1097 assertEquals( 1098 "secret", httpServer.getLogEntries().get(0).getRequestHeaders().get("X-Secret")); 1099 assertNull(httpServer.getLogEntries().get(1).getRequestHeaders().get("X-Secret")); 1100 } 1101 1102 @Test 1103 protected void testGet_Redirect_OriginScopedHeadersDisabled() throws Exception { 1104 Map<String, String> headers = Map.of("X-Secret", "secret"); 1105 session.setConfigProperty(ConfigurationProperties.HTTP_HEADERS + ".test", headers); 1106 session.setConfigProperty(ConfigurationProperties.HTTP_ORIGIN_SCOPED_HEADERS, false); 1107 newTransporter(httpServer.getHttpUrl()); 1108 1109 transporter.get(new GetTask(URI.create("redirect/file.txt?host=127.0.0.1"))); 1110 1111 assertEquals(2, httpServer.getLogEntries().size()); 1112 assertEquals( 1113 "secret", httpServer.getLogEntries().get(0).getRequestHeaders().get("X-Secret")); 1114 assertEquals( 1115 "secret", httpServer.getLogEntries().get(1).getRequestHeaders().get("X-Secret")); 1116 } 1117 1118 @Test 1119 protected void testGet_Redirect_OriginScopedAuthenticationNotReplayed() throws Exception { 1120 httpServer.setAuthentication("testuser", "testpass"); 1121 auth = new AuthenticationBuilder() 1122 .addUsername("testuser") 1123 .addPassword("testpass") 1124 .build(); 1125 newTransporter(httpServer.getHttpUrl()); 1126 1127 assertThrows( 1128 Exception.class, () -> transporter.get(new GetTask(URI.create("redirect/file.txt?host=127.0.0.1")))); 1129 1130 HttpServer.LogEntry redirectTarget = 1131 httpServer.getLogEntries().get(httpServer.getLogEntries().size() - 1); 1132 assertTrue(redirectTarget.getPath().startsWith("/repo/file.txt")); 1133 assertNull(redirectTarget.getRequestHeaders().get("Authorization")); 1134 } 1135 1136 @Test 1137 protected void testGet_Redirect_InsecureRedirectRefusedByDefault() throws Exception { 1138 httpServer.addHttp2ConnectorWithMutualTLS(); 1139 session.setConfigProperty(ConfigurationProperties.HTTP_VERSION, ConfigurationProperties.HttpVersion.HTTP_1_1); 1140 newTransporter(httpServer.getHttpsUrl()); 1141 1142 assertThrows(Exception.class, () -> transporter.get(new GetTask(URI.create("redirect/file.txt?scheme=http")))); 1143 1144 assertEquals(1, httpServer.getLogEntries().size()); 1145 } 1146 1147 @Test 1148 protected void testGet_Redirect_InsecureRedirectAllowedWhenConfigured() throws Exception { 1149 httpServer.addHttp2ConnectorWithMutualTLS(); 1150 session.setConfigProperty(ConfigurationProperties.HTTP_VERSION, ConfigurationProperties.HttpVersion.HTTP_1_1); 1151 session.setConfigProperty(ConfigurationProperties.HTTP_FOLLOW_INSECURE_REDIRECT, true); 1152 newTransporter(httpServer.getHttpsUrl()); 1153 1154 GetTask task = new GetTask(URI.create("redirect/file.txt?scheme=http")); 1155 transporter.get(task); 1156 1157 assertEquals("test", task.getDataString()); 1158 assertEquals(2, httpServer.getLogEntries().size()); 1159 } 1160 1161 @Test 1162 protected void testGet_Resume() throws Exception { 1163 File file = tempFile("re"); 1164 RecordingTransportListener listener = new RecordingTransportListener(); 1165 GetTask task = new GetTask(URI.create("repo/resume.txt")) 1166 .setDataPath(file.toPath(), true) 1167 .setListener(listener); 1168 transporter.get(task); 1169 assertEquals("resumable", TestFileUtils.readString(file)); 1170 assertEquals(1L, listener.getStartedCount()); 1171 assertEquals(2L, listener.getDataOffset()); 1172 assertEquals(9, listener.getDataLength()); 1173 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1174 assertEquals("sumable", listener.getBaos().toString(StandardCharsets.UTF_8)); 1175 } 1176 1177 @Test 1178 protected void testGet_ResumeLocalContentsOutdated() throws Exception { 1179 File file = tempFile("re"); 1180 file.setLastModified(System.currentTimeMillis() - 5 * 60 * 1000); 1181 RecordingTransportListener listener = new RecordingTransportListener(); 1182 GetTask task = new GetTask(URI.create("repo/resume.txt")) 1183 .setDataPath(file.toPath(), true) 1184 .setListener(listener); 1185 transporter.get(task); 1186 assertEquals("resumable", TestFileUtils.readString(file)); 1187 assertEquals(1L, listener.getStartedCount()); 1188 assertEquals(0L, listener.getDataOffset()); 1189 assertEquals(9, listener.getDataLength()); 1190 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1191 assertEquals("resumable", listener.getBaos().toString(StandardCharsets.UTF_8)); 1192 // the 412 answer to the resume request was discarded; only the served response may report properties (url 1193 // transport reports none) 1194 assertTrue(listener.getTransportPropertiesCount() <= 1, "Count: " + listener.getTransportPropertiesCount()); 1195 } 1196 1197 @Test 1198 protected void testGet_ResumeRangesNotSupportedByServer() throws Exception { 1199 httpServer.setRangeSupport(false); 1200 File file = tempFile("re"); 1201 RecordingTransportListener listener = new RecordingTransportListener(); 1202 GetTask task = new GetTask(URI.create("repo/resume.txt")) 1203 .setDataPath(file.toPath(), true) 1204 .setListener(listener); 1205 transporter.get(task); 1206 assertEquals("resumable", TestFileUtils.readString(file)); 1207 assertEquals(1L, listener.getStartedCount()); 1208 assertEquals(0L, listener.getDataOffset()); 1209 assertEquals(9, listener.getDataLength()); 1210 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1211 assertEquals("resumable", listener.getBaos().toString(StandardCharsets.UTF_8)); 1212 } 1213 1214 @Test 1215 protected void testGet_Checksums_Nexus() throws Exception { 1216 httpServer.setChecksumHeader(HttpServer.ChecksumHeader.NEXUS); 1217 GetTask task = new GetTask(URI.create("repo/file.txt")); 1218 transporter.get(task); 1219 assertEquals("test", task.getDataString()); 1220 assertEquals( 1221 "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get("SHA-1")); 1222 } 1223 1224 @Test 1225 protected void testGet_Checksums_XChecksum() throws Exception { 1226 httpServer.setChecksumHeader(HttpServer.ChecksumHeader.XCHECKSUM); 1227 GetTask task = new GetTask(URI.create("repo/file.txt")); 1228 transporter.get(task); 1229 assertEquals("test", task.getDataString()); 1230 assertEquals( 1231 "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get("SHA-1")); 1232 } 1233 1234 @Test 1235 protected void testGet_Checksums_XChecksum_Google() throws Exception { 1236 httpServer.setChecksumHeader(HttpServer.ChecksumHeader.XCHECKSUM_GOOGLE); 1237 GetTask task = new GetTask(URI.create("repo/file.txt")); 1238 transporter.get(task); 1239 assertEquals("test", task.getDataString()); 1240 assertEquals( 1241 "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get("SHA-1")); 1242 } 1243 1244 @Test 1245 protected void testGet_Checksums_XChecksum_Amazon() throws Exception { 1246 httpServer.setChecksumHeader(HttpServer.ChecksumHeader.XCHECKSUM_AMAZON); 1247 GetTask task = new GetTask(URI.create("repo/file.txt")); 1248 transporter.get(task); 1249 assertEquals("test", task.getDataString()); 1250 assertEquals( 1251 "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get("SHA-1")); 1252 } 1253 1254 @Test 1255 protected void testGet_FileHandleLeak() throws Exception { 1256 for (int i = 0; i < 100; i++) { 1257 File file = tempFile("failure"); 1258 transporter.get(new GetTask(URI.create("repo/file.txt")).setDataPath(file.toPath())); 1259 assertTrue(file.delete(), i + ", " + file.getAbsolutePath()); 1260 } 1261 } 1262 1263 @Test 1264 protected void testGet_NotFound() throws Exception { 1265 try { 1266 transporter.get(new GetTask(URI.create("repo/missing.txt"))); 1267 fail("Expected error"); 1268 } catch (HttpTransporterException e) { 1269 assertEquals(404, e.getStatusCode()); 1270 assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); 1271 } 1272 } 1273 1274 @Test 1275 protected void testGet_Closed() throws Exception { 1276 transporter.close(); 1277 try { 1278 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1279 fail("Expected error"); 1280 } catch (IllegalStateException e) { 1281 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1282 } 1283 } 1284 1285 @Test 1286 protected void testGet_StartCancelled() throws Exception { 1287 RecordingTransportListener listener = new RecordingTransportListener(); 1288 listener.cancelStart(); 1289 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 1290 try { 1291 transporter.get(task); 1292 fail("Expected error"); 1293 } catch (TransferCancelledException e) { 1294 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1295 } 1296 assertEquals(0L, listener.getDataOffset()); 1297 assertEquals(4L, listener.getDataLength()); 1298 assertEquals(1, listener.getStartedCount()); 1299 assertEquals(0, listener.getProgressedCount()); 1300 } 1301 1302 @Test 1303 protected void testGet_ProgressCancelled() throws Exception { 1304 RecordingTransportListener listener = new RecordingTransportListener(); 1305 listener.cancelProgress(); 1306 GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); 1307 try { 1308 transporter.get(task); 1309 fail("Expected error"); 1310 } catch (TransferCancelledException e) { 1311 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1312 } 1313 assertEquals(0L, listener.getDataOffset()); 1314 assertEquals(4L, listener.getDataLength()); 1315 assertEquals(1, listener.getStartedCount()); 1316 assertEquals(1, listener.getProgressedCount()); 1317 } 1318 1319 @Test 1320 protected void testPut_FromMemory() throws Exception { 1321 RecordingTransportListener listener = new RecordingTransportListener(); 1322 String payload = "upload"; 1323 PutTask task = 1324 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString(payload); 1325 transporter.put(task); 1326 assertEquals(0L, listener.getDataOffset()); 1327 assertEquals(6L, listener.getDataLength()); 1328 assertEquals(1, listener.getStartedCount()); 1329 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1330 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1331 assertEquals( 1332 String.valueOf(payload.getBytes(StandardCharsets.UTF_8).length), 1333 httpServer.getLogEntries().get(0).getRequestHeaders().get("Content-Length")); 1334 } 1335 1336 @Test 1337 protected void testPut_AcceptsRfc9457() throws Exception { 1338 String payload = "upload"; 1339 PutTask task = new PutTask(URI.create("repo/file.txt")).setDataString(payload); 1340 transporter.put(task); 1341 String accept = httpServer.getLogEntries().get(0).getRequestHeaders().get("Accept"); 1342 assertNotNull(accept, "Missing Accept header when retrieving artifact"); 1343 assertTrue( 1344 accept.contains("application/problem+json"), 1345 "Expected Accept header to contain application/problem+json, but was: " + accept); 1346 } 1347 1348 @Test 1349 protected void testPut_FromFile() throws Exception { 1350 File file = tempFile("upload"); 1351 RecordingTransportListener listener = new RecordingTransportListener(); 1352 PutTask task = 1353 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataPath(file.toPath()); 1354 transporter.put(task); 1355 assertEquals(0L, listener.getDataOffset()); 1356 assertEquals(6L, listener.getDataLength()); 1357 assertEquals(1, listener.getStartedCount()); 1358 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1359 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1360 assertEquals( 1361 String.valueOf(file.length()), 1362 httpServer.getLogEntries().get(0).getRequestHeaders().get("Content-Length")); 1363 } 1364 1365 @Test 1366 protected void testPut_EmptyResource() throws Exception { 1367 RecordingTransportListener listener = new RecordingTransportListener(); 1368 PutTask task = new PutTask(URI.create("repo/file.txt")).setListener(listener); 1369 transporter.put(task); 1370 assertEquals(0L, listener.getDataOffset()); 1371 assertEquals(0L, listener.getDataLength()); 1372 // some transports may skip the upload for empty resources 1373 assertTrue( 1374 listener.getStartedCount() <= 1, 1375 "The transport should be started at most once but was started " + listener.getStartedCount() 1376 + " times"); 1377 assertEquals(0, listener.getProgressedCount()); 1378 assertEquals("", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1379 } 1380 1381 @Test 1382 protected void testPut_EncodedResourcePath() throws Exception { 1383 RecordingTransportListener listener = new RecordingTransportListener(); 1384 PutTask task = new PutTask(URI.create("repo/some%20space.txt")) 1385 .setListener(listener) 1386 .setDataString("OK"); 1387 transporter.put(task); 1388 assertEquals(0L, listener.getDataOffset()); 1389 assertEquals(2L, listener.getDataLength()); 1390 assertEquals(1, listener.getStartedCount()); 1391 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1392 assertEquals("OK", TestFileUtils.readString(new File(repoDir, "some space.txt"))); 1393 } 1394 1395 @Test 1396 protected void testPut_Authenticated_ExpectContinue() throws Exception { 1397 httpServer.setAuthentication("testuser", "testpass"); 1398 auth = new AuthenticationBuilder() 1399 .addUsername("testuser") 1400 .addPassword("testpass") 1401 .build(); 1402 newTransporter(httpServer.getHttpUrl()); 1403 RecordingTransportListener listener = new RecordingTransportListener(); 1404 PutTask task = 1405 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1406 transporter.put(task); 1407 assertEquals(0L, listener.getDataOffset()); 1408 assertEquals(6L, listener.getDataLength()); 1409 assertEquals(supportsPreemptiveAuth() ? 1 : 2, listener.getStartedCount()); 1410 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1411 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1412 } 1413 1414 @Test 1415 protected void testPut_Authenticated_ExpectContinueBroken() throws Exception { 1416 // this makes OPTIONS recover, and have only 1 PUT (startedCount=1 as OPTIONS is not counted) 1417 session.setConfigProperty(ConfigurationProperties.HTTP_SUPPORT_WEBDAV, true); 1418 httpServer.setAuthentication("testuser", "testpass"); 1419 httpServer.setExpectSupport(HttpServer.ExpectContinue.BROKEN); 1420 auth = new AuthenticationBuilder() 1421 .addUsername("testuser") 1422 .addPassword("testpass") 1423 .build(); 1424 newTransporter(httpServer.getHttpUrl()); 1425 RecordingTransportListener listener = new RecordingTransportListener(); 1426 PutTask task = 1427 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1428 transporter.put(task); 1429 assertEquals(0L, listener.getDataOffset()); 1430 assertEquals(6L, listener.getDataLength()); 1431 assertEquals(supportsPreemptiveAuth() ? 1 : 2, listener.getStartedCount()); 1432 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1433 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1434 } 1435 1436 @Test 1437 protected void testPut_Authenticated_ExpectContinueRejected() throws Exception { 1438 httpServer.setAuthentication("testuser", "testpass"); 1439 httpServer.setExpectSupport(HttpServer.ExpectContinue.FAIL); 1440 auth = new AuthenticationBuilder() 1441 .addUsername("testuser") 1442 .addPassword("testpass") 1443 .build(); 1444 newTransporter(httpServer.getHttpUrl()); 1445 RecordingTransportListener listener = new RecordingTransportListener(); 1446 PutTask task = 1447 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1448 transporter.put(task); 1449 assertEquals(0L, listener.getDataOffset()); 1450 assertEquals(6L, listener.getDataLength()); 1451 assertEquals(supportsPreemptiveAuth() ? 1 : 2, listener.getStartedCount()); 1452 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1453 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1454 } 1455 1456 @Test 1457 protected void testPut_Authenticated_ExpectContinueDisabled() throws Exception { 1458 session.setConfigProperty(ConfigurationProperties.HTTP_EXPECT_CONTINUE, false); 1459 httpServer.setAuthentication("testuser", "testpass"); 1460 httpServer.setExpectSupport(HttpServer.ExpectContinue.FAIL); // if transport tries Expect/Continue explode 1461 auth = new AuthenticationBuilder() 1462 .addUsername("testuser") 1463 .addPassword("testpass") 1464 .build(); 1465 newTransporter(httpServer.getHttpUrl()); 1466 RecordingTransportListener listener = new RecordingTransportListener(); 1467 PutTask task = 1468 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1469 transporter.put(task); 1470 assertEquals(0L, listener.getDataOffset()); 1471 assertEquals(6L, listener.getDataLength()); 1472 assertEquals( 1473 supportsPreemptiveAuth() ? 1 : 2, 1474 listener.getStartedCount()); // w/ expectContinue enabled would have here 2/3 1475 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1476 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1477 } 1478 1479 @Test 1480 protected void testPut_Authenticated_ExpectContinueRejected_ExplicitlyConfiguredHeader() throws Exception { 1481 Map<String, String> headers = new HashMap<>(); 1482 headers.put("Expect", "100-continue"); 1483 session.setConfigProperty(ConfigurationProperties.HTTP_HEADERS + ".test", headers); 1484 httpServer.setAuthentication("testuser", "testpass"); 1485 httpServer.setExpectSupport(HttpServer.ExpectContinue.FAIL); 1486 auth = new AuthenticationBuilder() 1487 .addUsername("testuser") 1488 .addPassword("testpass") 1489 .build(); 1490 newTransporter(httpServer.getHttpUrl()); 1491 RecordingTransportListener listener = new RecordingTransportListener(); 1492 PutTask task = 1493 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1494 transporter.put(task); 1495 assertEquals(0L, listener.getDataOffset()); 1496 assertEquals(6L, listener.getDataLength()); 1497 assertEquals(1, listener.getStartedCount()); 1498 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1499 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1500 } 1501 1502 @Test 1503 protected void testPut_Unauthenticated() throws Exception { 1504 httpServer.setAuthentication("testuser", "testpass"); 1505 RecordingTransportListener listener = new RecordingTransportListener(); 1506 PutTask task = 1507 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1508 try { 1509 transporter.put(task); 1510 fail("Expected error"); 1511 } catch (HttpTransporterException e) { 1512 assertEquals(401, e.getStatusCode()); 1513 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1514 } 1515 assertEquals(0, listener.getStartedCount()); 1516 assertEquals(0, listener.getProgressedCount()); 1517 } 1518 1519 @Test 1520 protected void testPut_ProxyAuthenticated() throws Exception { 1521 httpServer.setProxyAuthentication("testuser", "testpass"); 1522 Authentication auth = new AuthenticationBuilder() 1523 .addUsername("testuser") 1524 .addPassword("testpass") 1525 .build(); 1526 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); 1527 newTransporter("http://bad.localhost:1/"); 1528 RecordingTransportListener listener = new RecordingTransportListener(); 1529 PutTask task = 1530 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1531 transporter.put(task); 1532 assertEquals(0L, listener.getDataOffset()); 1533 assertEquals(6L, listener.getDataLength()); 1534 assertEquals(supportsPreemptiveAuth() ? 1 : 2, listener.getStartedCount()); 1535 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1536 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1537 } 1538 1539 @Test 1540 protected void testPut_ProxyUnauthenticated() throws Exception { 1541 httpServer.setProxyAuthentication("testuser", "testpass"); 1542 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); 1543 newTransporter("http://bad.localhost:1/"); 1544 RecordingTransportListener listener = new RecordingTransportListener(); 1545 PutTask task = 1546 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1547 try { 1548 transporter.put(task); 1549 fail("Expected error"); 1550 } catch (HttpTransporterException e) { 1551 assertEquals(407, e.getStatusCode()); 1552 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1553 } 1554 assertEquals(0, listener.getStartedCount()); 1555 assertEquals(0, listener.getProgressedCount()); 1556 } 1557 1558 @Test 1559 protected void testPut_SSL() throws Exception { 1560 httpServer.addHttp2ConnectorWithMutualTLS(); 1561 httpServer.setAuthentication("testuser", "testpass"); 1562 auth = new AuthenticationBuilder() 1563 .addUsername("testuser") 1564 .addPassword("testpass") 1565 .build(); 1566 newTransporter(httpServer.getHttpsUrl()); 1567 RecordingTransportListener listener = new RecordingTransportListener(); 1568 PutTask task = 1569 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1570 transporter.put(task); 1571 assertEquals(0L, listener.getDataOffset()); 1572 assertEquals(6L, listener.getDataLength()); 1573 assertEquals(supportsPreemptiveAuth() ? 1 : 2, listener.getStartedCount()); 1574 assertTrue(listener.getProgressedCount() > 0, "Count: " + listener.getProgressedCount()); 1575 assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); 1576 assertEquals( 1577 HttpTransportProperty.SslProtocol.TLS_1_3, 1578 listener.getTransportProperties().get(HttpTransportProperty.Key.SSL_PROTOCOL)); 1579 } 1580 1581 @Test 1582 protected void testPut_FileHandleLeak() throws Exception { 1583 for (int i = 0; i < 100; i++) { 1584 File src = tempFile("upload"); 1585 File dst = new File(repoDir, "file.txt"); 1586 transporter.put(new PutTask(URI.create("repo/file.txt")).setDataPath(src.toPath())); 1587 assertTrue(src.delete(), i + ", " + src.getAbsolutePath()); 1588 assertTrue(dst.delete(), i + ", " + dst.getAbsolutePath()); 1589 } 1590 } 1591 1592 @Test 1593 protected void testPut_Closed() throws Exception { 1594 transporter.close(); 1595 try { 1596 transporter.put(new PutTask(URI.create("repo/missing.txt"))); 1597 fail("Expected error"); 1598 } catch (IllegalStateException e) { 1599 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1600 } 1601 } 1602 1603 @Test 1604 protected void testPut_StartCancelled() throws Exception { 1605 RecordingTransportListener listener = new RecordingTransportListener(); 1606 listener.cancelStart(); 1607 PutTask task = 1608 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1609 try { 1610 transporter.put(task); 1611 fail("Expected error"); 1612 } catch (TransferCancelledException e) { 1613 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1614 } 1615 assertEquals(0L, listener.getDataOffset()); 1616 assertEquals(6L, listener.getDataLength()); 1617 assertEquals(1, listener.getStartedCount()); 1618 assertEquals(0, listener.getProgressedCount()); 1619 } 1620 1621 @Test 1622 protected void testPut_ProgressCancelled() throws Exception { 1623 RecordingTransportListener listener = new RecordingTransportListener(); 1624 listener.cancelProgress(); 1625 PutTask task = 1626 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1627 try { 1628 transporter.put(task); 1629 fail("Expected error"); 1630 } catch (TransferCancelledException e) { 1631 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1632 } 1633 assertEquals(0L, listener.getDataOffset()); 1634 assertEquals(6L, listener.getDataLength()); 1635 assertEquals(1, listener.getStartedCount()); 1636 assertEquals(1, listener.getProgressedCount()); 1637 } 1638 1639 @Test 1640 protected void testGetPut_AuthCache() throws Exception { 1641 httpServer.setAuthentication("testuser", "testpass"); 1642 auth = new AuthenticationBuilder() 1643 .addUsername("testuser") 1644 .addPassword("testpass") 1645 .build(); 1646 newTransporter(httpServer.getHttpUrl()); 1647 GetTask get = new GetTask(URI.create("repo/file.txt")); 1648 transporter.get(get); 1649 RecordingTransportListener listener = new RecordingTransportListener(); 1650 PutTask task = 1651 new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); 1652 transporter.put(task); 1653 assertEquals(1, listener.getStartedCount()); 1654 } 1655 1656 @Test 1657 protected void testPut_PreemptiveIsDefault() throws Exception { 1658 httpServer.setAuthentication("testuser", "testpass"); 1659 auth = new AuthenticationBuilder() 1660 .addUsername("testuser") 1661 .addPassword("testpass") 1662 .build(); 1663 newTransporter(httpServer.getHttpUrl()); 1664 PutTask task = new PutTask(URI.create("repo/file.txt")).setDataString("upload"); 1665 transporter.put(task); 1666 assertEquals( 1667 supportsPreemptiveAuth() ? 1 : 2, httpServer.getLogEntries().size()); // put w/ auth 1668 } 1669 1670 @Test 1671 protected void testPut_AuthCache() throws Exception { 1672 session.setConfigProperty(ConfigurationProperties.HTTP_PREEMPTIVE_PUT_AUTH, false); 1673 httpServer.setAuthentication("testuser", "testpass"); 1674 auth = new AuthenticationBuilder() 1675 .addUsername("testuser") 1676 .addPassword("testpass") 1677 .build(); 1678 newTransporter(httpServer.getHttpUrl()); 1679 PutTask task = new PutTask(URI.create("repo/file.txt")).setDataString("upload"); 1680 transporter.put(task); 1681 assertEquals(2, httpServer.getLogEntries().size()); // put (challenged) + put w/ auth 1682 httpServer.getLogEntries().clear(); 1683 task = new PutTask(URI.create("repo/file.txt")).setDataString("upload"); 1684 transporter.put(task); 1685 assertEquals(1, httpServer.getLogEntries().size()); // put w/ auth 1686 } 1687 1688 @Test 1689 protected void testPut_AuthCache_Preemptive() throws Exception { 1690 httpServer.setAuthentication("testuser", "testpass"); 1691 auth = new AuthenticationBuilder() 1692 .addUsername("testuser") 1693 .addPassword("testpass") 1694 .build(); 1695 session.setConfigProperty(ConfigurationProperties.HTTP_PREEMPTIVE_AUTH, true); 1696 newTransporter(httpServer.getHttpUrl()); 1697 PutTask task = new PutTask(URI.create("repo/file.txt")).setDataString("upload"); 1698 transporter.put(task); 1699 assertEquals( 1700 supportsPreemptiveAuth() ? 1 : 2, httpServer.getLogEntries().size()); // put w/ auth 1701 httpServer.getLogEntries().clear(); 1702 task = new PutTask(URI.create("repo/file.txt")).setDataString("upload"); 1703 transporter.put(task); 1704 assertEquals(1, httpServer.getLogEntries().size()); // put w/ auth 1705 } 1706 1707 @Test 1708 protected void testPut_WithResponseBody() throws Exception { 1709 httpServer.setAuthentication("testuser", "testpass"); 1710 httpServer.setResponseBodyForPut("Some dummy response body"); 1711 auth = new AuthenticationBuilder() 1712 .addUsername("testuser") 1713 .addPassword("testpass") 1714 .build(); 1715 newTransporter(httpServer.getHttpUrl()); 1716 PutTask task = new PutTask(URI.create("repo/file.txt")).setDataString("upload"); 1717 transporter.put(task); 1718 // this leads to stuck threads in some transporters if the response body is not consumed 1719 } 1720 1721 @Test 1722 @Timeout(20) 1723 protected void testConcurrency() throws Exception { 1724 httpServer.setAuthentication("testuser", "testpass"); 1725 auth = new AuthenticationBuilder() 1726 .addUsername("testuser") 1727 .addPassword("testpass") 1728 .build(); 1729 newTransporter(httpServer.getHttpUrl()); 1730 final AtomicReference<Throwable> error = new AtomicReference<>(); 1731 Thread[] threads = new Thread[20]; 1732 for (int i = 0; i < threads.length; i++) { 1733 final String path = "repo/file.txt?i=" + i; 1734 threads[i] = new Thread(() -> { 1735 try { 1736 for (int j = 0; j < 100; j++) { 1737 GetTask task = new GetTask(URI.create(path)); 1738 transporter.get(task); 1739 assertEquals("test", task.getDataString()); 1740 } 1741 } catch (Throwable t) { 1742 error.compareAndSet(null, t); 1743 System.err.println(path); 1744 t.printStackTrace(); 1745 } 1746 }); 1747 threads[i].setName("Task-" + i); 1748 } 1749 for (Thread thread : threads) { 1750 thread.start(); 1751 } 1752 for (Thread thread : threads) { 1753 thread.join(); 1754 } 1755 assertNull(error.get(), String.valueOf(error.get())); 1756 } 1757 1758 @Test 1759 @Timeout(10) 1760 protected void testConnectTimeout() throws Exception { 1761 session.setConfigProperty(ConfigurationProperties.CONNECT_TIMEOUT, 100); 1762 int port = 1; 1763 newTransporter("http://localhost:" + port); 1764 try { 1765 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1766 fail("Expected error"); 1767 } catch (Exception e) { 1768 // impl specific "timeout" exception 1769 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1770 } 1771 } 1772 1773 @Test 1774 @Timeout(10) 1775 protected void testRequestTimeout() throws Exception { 1776 session.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, 100); 1777 ServerSocket server = new ServerSocket(0); 1778 try (server) { 1779 newTransporter("http://localhost:" + server.getLocalPort()); 1780 try { 1781 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1782 fail("Expected error"); 1783 } catch (Exception e) { 1784 assertTrue(e.getClass().getSimpleName().contains("Timeout")); 1785 assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); 1786 } 1787 } 1788 } 1789 1790 @Test 1791 protected void testUserAgent() throws Exception { 1792 session.setConfigProperty(ConfigurationProperties.USER_AGENT, "SomeTest/1.0"); 1793 newTransporter(httpServer.getHttpUrl()); 1794 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1795 assertEquals(1, httpServer.getLogEntries().size()); 1796 for (HttpServer.LogEntry log : httpServer.getLogEntries()) { 1797 assertEquals("SomeTest/1.0", log.getRequestHeaders().get("User-Agent")); 1798 } 1799 } 1800 1801 @Test 1802 protected void testCustomHeaders() throws Exception { 1803 Map<String, String> headers = new HashMap<>(); 1804 headers.put("User-Agent", "Custom/1.0"); 1805 headers.put("X-CustomHeader", "Custom-Value"); 1806 session.setConfigProperty(ConfigurationProperties.USER_AGENT, "SomeTest/1.0"); 1807 session.setConfigProperty(ConfigurationProperties.HTTP_HEADERS + ".test", headers); 1808 newTransporter(httpServer.getHttpUrl()); 1809 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1810 assertEquals(1, httpServer.getLogEntries().size()); 1811 for (HttpServer.LogEntry log : httpServer.getLogEntries()) { 1812 for (Map.Entry<String, String> entry : headers.entrySet()) { 1813 assertEquals(entry.getValue(), log.getRequestHeaders().get(entry.getKey()), entry.getKey()); 1814 } 1815 } 1816 } 1817 1818 @Test 1819 protected void testServerAuthScope_NotUsedForProxy() throws Exception { 1820 String username = "testuser", password = "testpass"; 1821 httpServer.setProxyAuthentication(username, password); 1822 auth = new AuthenticationBuilder() 1823 .addUsername(username) 1824 .addPassword(password) 1825 .build(); 1826 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); 1827 newTransporter("http://" + httpServer.getHost() + ":12/"); 1828 try { 1829 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1830 fail("Server auth must not be used as proxy auth"); 1831 } catch (HttpTransporterException e) { 1832 assertEquals(407, e.getStatusCode()); 1833 } catch (IOException e) { 1834 // accepted as well: point is to fail 1835 } 1836 } 1837 1838 @Test 1839 protected void testProxyAuthScope_NotUsedForServer() throws Exception { 1840 String username = "testuser", password = "testpass"; 1841 httpServer.setAuthentication(username, password); 1842 Authentication auth = new AuthenticationBuilder() 1843 .addUsername(username) 1844 .addPassword(password) 1845 .build(); 1846 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); 1847 newTransporter("http://" + httpServer.getHost() + ":12/"); 1848 try { 1849 transporter.get(new GetTask(URI.create("repo/file.txt"))); 1850 fail("Proxy auth must not be used as server auth"); 1851 } catch (HttpTransporterException e) { 1852 assertEquals(401, e.getStatusCode()); 1853 } catch (IOException e) { 1854 // accepted as well: point is to fail 1855 } 1856 } 1857 1858 @Test 1859 protected void testAuthSchemeReuse() throws Exception { 1860 httpServer.setAuthentication("testuser", "testpass"); 1861 httpServer.setProxyAuthentication("proxyuser", "proxypass"); 1862 session.setCache(new DefaultRepositoryCache()); 1863 auth = new AuthenticationBuilder() 1864 .addUsername("testuser") 1865 .addPassword("testpass") 1866 .build(); 1867 Authentication auth = new AuthenticationBuilder() 1868 .addUsername("proxyuser") 1869 .addPassword("proxypass") 1870 .build(); 1871 proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); 1872 newTransporter("http://bad.localhost:1/"); 1873 GetTask task = new GetTask(URI.create("repo/file.txt")); 1874 transporter.get(task); 1875 assertEquals("test", task.getDataString()); 1876 assertEquals(3, httpServer.getLogEntries().size()); 1877 httpServer.getLogEntries().clear(); 1878 newTransporter("http://bad.localhost:1/"); 1879 task = new GetTask(URI.create("repo/file.txt")); 1880 transporter.get(task); 1881 assertEquals("test", task.getDataString()); 1882 assertEquals(1, httpServer.getLogEntries().size()); 1883 assertNotNull(httpServer.getLogEntries().get(0).getRequestHeaders().get("Authorization")); 1884 assertNotNull(httpServer.getLogEntries().get(0).getRequestHeaders().get("Proxy-Authorization")); 1885 } 1886 1887 @Test 1888 protected void testAuthSchemePreemptive() throws Exception { 1889 httpServer.setAuthentication("testuser", "testpass"); 1890 session.setCache(new DefaultRepositoryCache()); 1891 auth = new AuthenticationBuilder() 1892 .addUsername("testuser") 1893 .addPassword("testpass") 1894 .build(); 1895 1896 session.setConfigProperty(ConfigurationProperties.HTTP_PREEMPTIVE_AUTH, false); 1897 newTransporter(httpServer.getHttpUrl()); 1898 GetTask task = new GetTask(URI.create("repo/file.txt")); 1899 transporter.get(task); 1900 assertEquals("test", task.getDataString()); 1901 // there ARE challenge round-trips 1902 assertEquals(2, httpServer.getLogEntries().size()); 1903 httpServer.getLogEntries().clear(); 1904 session.setConfigProperty(ConfigurationProperties.HTTP_PREEMPTIVE_AUTH, true); 1905 newTransporter(httpServer.getHttpUrl()); 1906 task = new GetTask(URI.create("repo/file.txt")); 1907 transporter.get(task); 1908 assertEquals("test", task.getDataString()); 1909 // there are (potentially) NO challenge round-trips, all goes through at first 1910 assertEquals( 1911 supportsPreemptiveAuth() ? 1 : 2, httpServer.getLogEntries().size()); 1912 } 1913 1914 @Test 1915 void testInit_BadProtocol() { 1916 assertThrows(NoTransporterException.class, () -> newTransporter("bad:/void")); 1917 } 1918 1919 @Test 1920 void testInit_BadUrl() { 1921 assertThrows(NoTransporterException.class, () -> newTransporter("http://localhost:NaN")); 1922 } 1923 1924 @Test 1925 void testInit_CaseInsensitiveProtocol() throws Exception { 1926 newTransporter("http://localhost"); 1927 newTransporter("HTTP://localhost"); 1928 newTransporter("Http://localhost"); 1929 newTransporter("https://localhost"); 1930 newTransporter("HTTPS://localhost"); 1931 newTransporter("HttpS://localhost"); 1932 } 1933}