View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.transport.jetty;
20  
21  import javax.net.ssl.SSLContext;
22  
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.net.URI;
26  import java.net.URISyntaxException;
27  import java.nio.ByteBuffer;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.nio.file.StandardCopyOption;
31  import java.security.NoSuchAlgorithmException;
32  import java.util.ArrayList;
33  import java.util.Collection;
34  import java.util.HashMap;
35  import java.util.Map;
36  import java.util.TreeSet;
37  import java.util.concurrent.ExecutionException;
38  import java.util.concurrent.TimeUnit;
39  import java.util.concurrent.TimeoutException;
40  import java.util.concurrent.atomic.AtomicBoolean;
41  import java.util.concurrent.atomic.AtomicReference;
42  import java.util.function.Function;
43  import java.util.regex.Matcher;
44  
45  import org.eclipse.aether.ConfigurationProperties;
46  import org.eclipse.aether.ConfigurationProperties.HttpVersion;
47  import org.eclipse.aether.ConfigurationProperties.RedirectMode;
48  import org.eclipse.aether.RepositorySystemSession;
49  import org.eclipse.aether.repository.AuthenticationContext;
50  import org.eclipse.aether.repository.RemoteRepository;
51  import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
52  import org.eclipse.aether.spi.connector.transport.GetTask;
53  import org.eclipse.aether.spi.connector.transport.PeekTask;
54  import org.eclipse.aether.spi.connector.transport.PutTask;
55  import org.eclipse.aether.spi.connector.transport.TransportTask;
56  import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
57  import org.eclipse.aether.spi.connector.transport.http.HttpTransportPropertiesBuilder;
58  import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
59  import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
60  import org.eclipse.aether.spi.io.PathProcessor;
61  import org.eclipse.aether.transfer.HttpTransportProperty;
62  import org.eclipse.aether.transfer.NoTransporterException;
63  import org.eclipse.aether.transfer.TransferCancelledException;
64  import org.eclipse.aether.transfer.TransferEvent;
65  import org.eclipse.aether.util.ConfigUtils;
66  import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
67  import org.eclipse.jetty.client.Authentication;
68  import org.eclipse.jetty.client.BasicAuthentication;
69  import org.eclipse.jetty.client.HttpClient;
70  import org.eclipse.jetty.client.HttpProxy;
71  import org.eclipse.jetty.client.InputStreamResponseListener;
72  import org.eclipse.jetty.client.Request;
73  import org.eclipse.jetty.client.Response;
74  import org.eclipse.jetty.client.transport.HttpClientConnectionFactory;
75  import org.eclipse.jetty.client.transport.HttpClientTransportDynamic;
76  import org.eclipse.jetty.http.HttpField;
77  import org.eclipse.jetty.http.HttpHeader;
78  import org.eclipse.jetty.http2.client.HTTP2Client;
79  import org.eclipse.jetty.http2.client.transport.ClientConnectionFactoryOverHTTP2;
80  import org.eclipse.jetty.http3.client.HTTP3Client;
81  import org.eclipse.jetty.http3.client.HTTP3ClientQuicConfiguration;
82  import org.eclipse.jetty.http3.client.transport.ClientConnectionFactoryOverHTTP3;
83  import org.eclipse.jetty.io.ClientConnectionFactory;
84  import org.eclipse.jetty.io.ClientConnector;
85  import org.eclipse.jetty.io.EndPoint.SslSessionData;
86  import org.eclipse.jetty.quic.quiche.client.QuicheClientQuicConfiguration;
87  import org.eclipse.jetty.quic.quiche.client.QuicheTransport;
88  import org.eclipse.jetty.util.ssl.SslContextFactory;
89  import org.slf4j.Logger;
90  import org.slf4j.LoggerFactory;
91  
92  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.ACCEPT_ENCODING;
93  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_LENGTH;
94  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE;
95  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
96  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.IF_UNMODIFIED_SINCE;
97  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.LAST_MODIFIED;
98  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.MULTIPLE_CHOICES;
99  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.PRECONDITION_FAILED;
100 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.RANGE;
101 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.USER_AGENT;
102 
103 /**
104  * A transporter for HTTP/HTTPS.
105  *
106  * @since 2.0.0
107  */
108 final class JettyTransporter extends AbstractTransporter implements HttpTransporter {
109     private static final Logger LOGGER = LoggerFactory.getLogger(JettyTransporter.class);
110 
111     private static final long MODIFICATION_THRESHOLD = 60L * 1000L;
112 
113     private final RepositorySystemSession session;
114 
115     private final RemoteRepository repository;
116 
117     private final ChecksumExtractor checksumExtractor;
118 
119     private final PathProcessor pathProcessor;
120 
121     private final URI baseUri;
122 
123     private final HttpClient client;
124 
125     private final int connectTimeout;
126 
127     private final int requestTimeout;
128 
129     private final JettyRetryHandler retryHandler;
130 
131     private final Map<String, String> headers;
132 
133     private final boolean preemptiveAuth;
134 
135     private final boolean preemptivePutAuth;
136 
137     private final boolean sendRfc9457Accept;
138 
139     private final boolean insecure;
140 
141     private final AtomicReference<BasicAuthentication.BasicResult> basicServerAuthenticationResult;
142 
143     private final AtomicReference<BasicAuthentication.BasicResult> basicProxyAuthenticationResult;
144 
145     JettyTransporter(
146             RepositorySystemSession session,
147             RemoteRepository repository,
148             ChecksumExtractor checksumExtractor,
149             PathProcessor pathProcessor)
150             throws NoTransporterException {
151         this.session = session;
152         this.repository = repository;
153         this.checksumExtractor = checksumExtractor;
154         this.pathProcessor = pathProcessor;
155         try {
156             this.baseUri = HttpTransporterUtils.getBaseUri(repository);
157         } catch (URISyntaxException e) {
158             throw new NoTransporterException(repository, e.getMessage(), e);
159         }
160 
161         HashMap<String, String> headers = new HashMap<>();
162         String userAgent = HttpTransporterUtils.getUserAgent(session, repository);
163         if (userAgent != null) {
164             headers.put(USER_AGENT, userAgent);
165         }
166         Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
167         if (configuredHeaders != null) {
168             headers.putAll(configuredHeaders);
169         }
170 
171         this.headers = headers;
172 
173         this.connectTimeout = HttpTransporterUtils.getHttpConnectTimeout(session, repository);
174         this.requestTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
175         this.retryHandler = new JettyRetryHandler(session, repository);
176         this.preemptiveAuth = HttpTransporterUtils.isHttpPreemptiveAuth(session, repository);
177         this.preemptivePutAuth = HttpTransporterUtils.isHttpPreemptivePutAuth(session, repository);
178         this.sendRfc9457Accept = HttpTransporterUtils.isHttpSendRfc9457Accept(session, repository);
179         final String httpsSecurityMode = HttpTransporterUtils.getHttpsSecurityMode(session, repository);
180         this.insecure = ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE.equals(httpsSecurityMode);
181 
182         this.basicServerAuthenticationResult = new AtomicReference<>(null);
183         this.basicProxyAuthenticationResult = new AtomicReference<>(null);
184         this.client = createClient();
185     }
186 
187     private void mayApplyPreemptiveAuth(Request request) {
188         if (basicServerAuthenticationResult.get() != null) {
189             basicServerAuthenticationResult.get().apply(request);
190         }
191         if (basicProxyAuthenticationResult.get() != null) {
192             basicProxyAuthenticationResult.get().apply(request);
193         }
194     }
195 
196     private URI resolve(TransportTask task) {
197         return baseUri.resolve(task.getLocation());
198     }
199 
200     /**
201      * Logs that the request is sent again right away, after the given attempt failed without a (retriable) response.
202      */
203     private void logImmediateRetry(Request request, int attempt, Throwable failure) {
204         HttpTransporter.logImmediateRetry(
205                 LOGGER, request.getMethod(), request.getURI(), attempt, retryHandler.getRetryCount() + 1, failure);
206     }
207 
208     /**
209      * Logs and waits until the request is sent again, after the given attempt got a retriable response.
210      */
211     private void waitBeforeRetry(Request request, int attempt, Response response) throws InterruptedException {
212         JettyRetryHandler.Delay delay = retryHandler.getDelay(response.getHeaders(), attempt);
213         HttpTransporter.logRetry(
214                 LOGGER,
215                 request.getMethod(),
216                 request.getURI(),
217                 attempt,
218                 retryHandler.getRetryCount() + 1,
219                 "status " + response.getStatus(),
220                 delay.millis(),
221                 delay.reason());
222         if (delay.millis() > 0L) {
223             Thread.sleep(delay.millis());
224         }
225     }
226 
227     @Override
228     protected void implPeek(PeekTask task) throws Exception {
229         for (int attempt = 0; ; attempt++) {
230             Request request = client.newRequest(resolve(task)).method("HEAD");
231             request.headers(m -> headers.forEach(m::add));
232             if (preemptiveAuth) {
233                 mayApplyPreemptiveAuth(request);
234             }
235             // capture raw response headers as described in https://github.com/jetty/jetty.project/discussions/14404
236             Map<String, HttpField> rawResponseHeaders = new HashMap<>();
237             request.onResponseHeader((r, field) -> {
238                 rawResponseHeaders.put(field.getLowerCaseName(), field);
239                 return true; // continue processing
240             });
241             Response response;
242             try {
243                 response = request.send();
244             } catch (ExecutionException | TimeoutException e) {
245                 Throwable failure = e instanceof ExecutionException ? e.getCause() : e;
246                 if (retryHandler.shouldRetry(attempt, failure)) {
247                     logImmediateRetry(request, attempt, failure);
248                     continue;
249                 }
250                 if (failure instanceof Exception) {
251                     throw (Exception) failure;
252                 } else {
253                     throw new RuntimeException(failure);
254                 }
255             }
256             if (retryHandler.shouldRetry(attempt, response.getStatus())) {
257                 waitBeforeRetry(request, attempt, response);
258                 continue;
259             }
260             Map<TransferEvent.TransportPropertyKey, Object> transportProperties =
261                     createTransportProperties(request, rawResponseHeaders);
262             task.getListener().transportPropertiesAvailable(transportProperties);
263             if (response.getStatus() >= MULTIPLE_CHOICES) {
264                 throw new HttpTransporterException(response.getStatus());
265             }
266             return;
267         }
268     }
269 
270     @Override
271     protected void implGet(GetTask task) throws Exception {
272         boolean resume = task.getResumeOffset() > 0L && task.getDataPath() != null;
273         Response response;
274         InputStreamResponseListener listener;
275 
276         int attempt = 0;
277         while (true) {
278             Request request = client.newRequest(resolve(task)).method("GET");
279             request.headers(m -> headers.forEach(m::add));
280             if (preemptiveAuth) {
281                 mayApplyPreemptiveAuth(request);
282             }
283             if (sendRfc9457Accept) {
284                 JettyRFC9457Reporter.INSTANCE.prepareRequest(request);
285             }
286             if (resume) {
287                 long resumeOffset = task.getResumeOffset();
288                 long lastModified =
289                         Files.getLastModifiedTime(task.getDataPath()).toMillis();
290                 request.headers(h -> {
291                     h.add(RANGE, "bytes=" + resumeOffset + '-');
292                     h.addDateField(IF_UNMODIFIED_SINCE, lastModified - MODIFICATION_THRESHOLD);
293                     h.remove(HttpHeader.ACCEPT_ENCODING);
294                     h.add(ACCEPT_ENCODING, "identity");
295                 });
296             }
297 
298             // capture raw response headers as described in https://github.com/jetty/jetty.project/discussions/14404
299             Map<String, HttpField> rawResponseHeaders = new HashMap<>();
300             request.onResponseHeader((r, field) -> {
301                 rawResponseHeaders.put(field.getLowerCaseName(), field);
302                 return true; // continue processing
303             });
304             listener = new InputStreamResponseListener();
305             request.send(listener);
306             try {
307                 response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
308             } catch (ExecutionException | TimeoutException e) {
309                 Throwable t = e instanceof ExecutionException ? e.getCause() : e;
310                 if (retryHandler.shouldRetry(attempt, t)) {
311                     request.abort(t); // no-op if the request already failed
312                     listener.close();
313                     logImmediateRetry(request, attempt, t);
314                     attempt++;
315                     continue;
316                 }
317                 if (t instanceof Exception) {
318                     throw (Exception) t;
319                 } else {
320                     throw new RuntimeException(t);
321                 }
322             }
323             if (retryHandler.shouldRetry(attempt, response.getStatus())) {
324                 listener.close(); // discards the response body
325                 waitBeforeRetry(request, attempt, response);
326                 attempt++;
327                 continue;
328             }
329             Map<TransferEvent.TransportPropertyKey, Object> transportProperties =
330                     createTransportProperties(request, rawResponseHeaders);
331             task.getListener().transportPropertiesAvailable(transportProperties);
332             if (response.getStatus() >= MULTIPLE_CHOICES) {
333                 if (resume && response.getStatus() == PRECONDITION_FAILED) {
334                     resume = false;
335                     continue;
336                 }
337                 JettyRFC9457Reporter.INSTANCE.generateException(listener, (statusCode, reasonPhrase) -> {
338                     throw new HttpTransporterException(statusCode);
339                 });
340             }
341             break;
342         }
343 
344         long offset = 0L, length = response.getHeaders().getLongField(CONTENT_LENGTH);
345         if (resume) {
346             String range = response.getHeaders().get(CONTENT_RANGE);
347             if (range != null) {
348                 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
349                 if (!m.matches()) {
350                     throw new IOException("Invalid Content-Range header for partial download: " + range);
351                 }
352                 offset = Long.parseLong(m.group(1));
353                 length = Long.parseLong(m.group(2)) + 1L;
354                 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
355                     throw new IOException("Invalid Content-Range header for partial download from offset "
356                             + task.getResumeOffset() + ": " + range);
357                 }
358             }
359         }
360 
361         final boolean downloadResumed = offset > 0L;
362         final Path dataFile = task.getDataPath();
363         if (dataFile == null) {
364             try (InputStream is = listener.getInputStream()) {
365                 utilGet(task, is, true, length, downloadResumed);
366             }
367         } else {
368             try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(dataFile)) {
369                 task.setDataPath(tempFile.getPath(), downloadResumed);
370                 if (downloadResumed && Files.isRegularFile(dataFile)) {
371                     try (InputStream inputStream = Files.newInputStream(dataFile)) {
372                         Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
373                     }
374                 }
375                 try (InputStream is = listener.getInputStream()) {
376                     utilGet(task, is, true, length, downloadResumed);
377                 }
378                 tempFile.move();
379             } finally {
380                 task.setDataPath(dataFile);
381             }
382         }
383         if (task.getDataPath() != null && response.getHeaders().getDateField(LAST_MODIFIED) != -1) {
384             long lastModified =
385                     response.getHeaders().getDateField(LAST_MODIFIED); // note: Wagon also does first not last
386             if (lastModified != -1) {
387                 pathProcessor.setLastModified(
388                         task.getDataPath(), HttpTransporterUtils.clampRemoteLastModified(lastModified));
389             }
390         }
391         Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
392         if (checksums != null && !checksums.isEmpty()) {
393             checksums.forEach(task::setChecksum);
394         }
395     }
396 
397     private Map<TransferEvent.TransportPropertyKey, Object> createTransportProperties(
398             Request request, Map<String, HttpField> rawResponseHeaders) {
399         HttpTransportPropertiesBuilder builder =
400                 new HttpTransportPropertiesBuilder(toHttpVersion(request.getVersion()));
401         SslSessionData sslSessionData = request.getConnection().getSslSessionData();
402         if (sslSessionData != null && sslSessionData.sslSession() != null) {
403             builder.withSslProtocol(sslSessionData.sslSession().getProtocol());
404             builder.withSslCipherSuite(sslSessionData.sslSession().getCipherSuite());
405         }
406         if (rawResponseHeaders.containsKey("content-encoding")) {
407             builder.withContentCoding(rawResponseHeaders.get("content-encoding").getValue());
408         }
409         return builder.build();
410     }
411 
412     static HttpTransportProperty.HttpVersion toHttpVersion(org.eclipse.jetty.http.HttpVersion version) {
413         switch (version) {
414             case HTTP_1_0:
415                 return HttpTransportProperty.HttpVersion.HTTP_1_0;
416             case HTTP_1_1:
417                 return HttpTransportProperty.HttpVersion.HTTP_1_1;
418             case HTTP_2:
419                 return HttpTransportProperty.HttpVersion.HTTP_2;
420             case HTTP_3:
421                 return HttpTransportProperty.HttpVersion.HTTP_3;
422             default:
423                 throw new IllegalArgumentException("Unknown version " + version.toString());
424         }
425     }
426 
427     private static Function<String, String> headerGetter(Response response) {
428         return s -> response.getHeaders().get(s);
429     }
430 
431     @Override
432     protected void implPut(PutTask task) throws Exception {
433         int attempt = 0;
434         while (!put(task, attempt)) {
435             attempt++;
436         }
437     }
438 
439     /**
440      * Sends the PUT request once.
441      *
442      * @param attempt the 0-based number of this attempt
443      * @return {@code true} if the upload is complete, {@code false} if it failed in a way that is worth another attempt
444      */
445     private boolean put(PutTask task, int attempt) throws Exception {
446         Request request = client.newRequest(resolve(task)).method("PUT");
447         request.headers(m -> headers.forEach(m::add));
448         if (sendRfc9457Accept) {
449             JettyRFC9457Reporter.INSTANCE.prepareRequest(request);
450         }
451         if (preemptiveAuth || preemptivePutAuth) {
452             mayApplyPreemptiveAuth(request);
453         }
454         request.body(PutTaskRequestContent.from(task));
455         // capture raw response headers as described in https://github.com/jetty/jetty.project/discussions/14404
456         Map<String, HttpField> rawResponseHeaders = new HashMap<>();
457         request.onResponseHeader((r, field) -> {
458             rawResponseHeaders.put(field.getLowerCaseName(), field);
459             return true; // continue processing
460         });
461         AtomicBoolean started = new AtomicBoolean(false);
462         AtomicBoolean progressed = new AtomicBoolean(false);
463         Response response;
464         try (InputStreamResponseListener listener = new InputStreamResponseListener()) {
465             request.onRequestCommit(r -> {
466                         if (task.getDataLength() == 0) {
467                             if (started.compareAndSet(false, true)) {
468                                 try {
469                                     task.getListener().transportStarted(0, task.getDataLength());
470                                 } catch (TransferCancelledException e) {
471                                     r.abort(e);
472                                 }
473                             }
474                         }
475                     })
476                     .onRequestContent((r, b) -> {
477                         if (started.compareAndSet(false, true)) {
478                             try {
479                                 task.getListener().transportStarted(0, task.getDataLength());
480                             } catch (TransferCancelledException e) {
481                                 r.abort(e);
482                                 return;
483                             }
484                         }
485                         progressed.set(true);
486                         try {
487                             task.getListener().transportProgressed(b);
488                         } catch (TransferCancelledException e) {
489                             r.abort(e);
490                         }
491                     })
492                     .send(listener);
493             response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
494             // On some platforms (macOS) with certain configurations (proxy auth, TLS/HTTP2),
495             // Jetty may complete a small PUT without firing onRequestContent callbacks, leaving
496             // the progress listener uninformed even though the upload was sent.
497             // Fire the missing events regardless of response status so the listener contract
498             // is honoured on both success and error paths. TransferCancelledException from
499             // transportStarted is propagated to the caller (cancelStart must be observable).
500             if (task.getDataLength() > 0 && !progressed.get()) {
501                 if (started.compareAndSet(false, true)) {
502                     // propagate cancellation: even though the bytes are already sent,
503                     // the TransportListener contract requires callers to observe cancelStart
504                     task.getListener().transportStarted(0, task.getDataLength());
505                 }
506                 try (InputStream is = task.newInputStream()) {
507                     byte[] buf = new byte[1024 * 32];
508                     int n;
509                     while ((n = is.read(buf)) != -1) {
510                         try {
511                             task.getListener().transportProgressed(ByteBuffer.wrap(buf, 0, n));
512                         } catch (TransferCancelledException e) {
513                             break; // exit loop; fall through to transportPropertiesAvailable
514                         }
515                     }
516                 }
517             }
518             if (!retryHandler.shouldRetry(attempt, response.getStatus())) {
519                 // transportPropertiesAvailable is called after transportStarted/transportProgressed
520                 // to honour the TransportListener contract: "for remote put tasks this is called
521                 // after transportStarted(long, long)". Placed before the status check so it is
522                 // reachable on both success (2xx) and error (3xx/4xx/5xx) responses.
523                 task.getListener().transportPropertiesAvailable(createTransportProperties(request, rawResponseHeaders));
524                 if (response.getStatus() >= MULTIPLE_CHOICES) {
525                     JettyRFC9457Reporter.INSTANCE.generateException(listener, (statusCode, reasonPhrase) -> {
526                         throw new HttpTransporterException(statusCode);
527                     });
528                 }
529                 return true;
530             }
531         } catch (ExecutionException | TimeoutException e) {
532             Throwable t = e instanceof ExecutionException ? e.getCause() : e;
533             if (retryHandler.shouldRetry(attempt, t)) {
534                 request.abort(t); // no-op if the request already failed
535                 logImmediateRetry(request, attempt, t);
536                 return false;
537             }
538             if (t instanceof IOException ioex) {
539                 if (ioex.getCause() instanceof TransferCancelledException) {
540                     throw (TransferCancelledException) ioex.getCause();
541                 } else {
542                     throw ioex;
543                 }
544             } else if (t instanceof Exception) {
545                 throw (Exception) t;
546             } else {
547                 throw new RuntimeException(t);
548             }
549         }
550         // the listener is closed by now, which discards the response body
551         waitBeforeRetry(request, attempt, response);
552         return false;
553     }
554 
555     @Override
556     protected void implClose() {
557         try {
558             this.client.stop();
559         } catch (Exception e) {
560             throw new RuntimeException(e);
561         }
562     }
563 
564     @SuppressWarnings({"checkstyle:methodlength", "deprecation"})
565     private HttpClient createClient() throws RuntimeException {
566         BasicAuthentication.BasicResult serverAuth = null;
567         BasicAuthentication.BasicResult proxyAuth = null;
568         SSLContext sslContext = null;
569         BasicAuthentication basicAuthentication = null;
570         try (AuthenticationContext repoAuthContext = AuthenticationContext.forRepository(session, repository)) {
571             if (repoAuthContext != null) {
572                 sslContext = repoAuthContext.get(AuthenticationContext.SSL_CONTEXT, SSLContext.class);
573 
574                 String username = repoAuthContext.get(AuthenticationContext.USERNAME);
575                 String password = repoAuthContext.get(AuthenticationContext.PASSWORD);
576 
577                 URI uri = URI.create(repository.getUrl());
578                 basicAuthentication = new BasicAuthentication(uri, Authentication.ANY_REALM, username, password);
579                 if (preemptiveAuth || preemptivePutAuth) {
580                     serverAuth = new BasicAuthentication.BasicResult(uri, HttpHeader.AUTHORIZATION, username, password);
581                 }
582             }
583         }
584 
585         SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
586         if (insecure) {
587             // this is also passed on to Quiche for HTTP/3
588             sslContextFactory.setEndpointIdentificationAlgorithm(null);
589             sslContextFactory.setHostnameVerifier((name, context) -> true);
590             sslContextFactory.setTrustAll(true);
591         } else {
592             try {
593                 if (sslContext == null) {
594                     // use the JVM's default SSL context (potentially with custom keystores/truststores)
595                     // https://github.com/jetty/jetty.project/issues/15378
596                     sslContext = SSLContext.getDefault();
597                 }
598             } catch (NoSuchAlgorithmException e) {
599                 throw new IllegalStateException("SSL Context setup failure", e);
600             }
601         }
602 
603         if (sslContext != null) {
604             // not properly supported by Quiche for HTTP/3, but Jetty will use it for HTTP/2 and HTTP/1.1
605             sslContextFactory.setSslContext(sslContext);
606         }
607 
608         ClientConnector clientConnector = new ClientConnector();
609         clientConnector.setSslContextFactory(sslContextFactory);
610 
611         Collection<ClientConnectionFactory.Info> connectors = new ArrayList<>();
612         if ("https".equalsIgnoreCase(repository.getProtocol())) {
613             HttpVersion httpVersion = HttpTransporterUtils.getHttpVersion(session, repository);
614             switch (httpVersion) {
615                 case MAXIMUM:
616                 case HTTP_3:
617                     QuicheClientQuicConfiguration clientQuicConfig =
618                             HTTP3ClientQuicConfiguration.configure(new QuicheClientQuicConfiguration());
619                     HTTP3Client http3Client = new HTTP3Client(clientQuicConfig, clientConnector);
620                     QuicheTransport transport = new QuicheTransport(clientQuicConfig);
621                     ClientConnectionFactoryOverHTTP3.HTTP3 http3 =
622                             new ClientConnectionFactoryOverHTTP3.HTTP3(http3Client, transport);
623                     connectors.add(http3);
624                     break; // fallback to HTTP/2 not supported yet (https://github.com/jetty/jetty.project/issues/15423)
625                 case HTTP_2:
626                 case DEFAULT:
627                     HTTP2Client http2Client = new HTTP2Client(clientConnector);
628                     ClientConnectionFactoryOverHTTP2.HTTP2 http2 =
629                             new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client);
630                     connectors.add(http2);
631                     break;
632                 default:
633                     break;
634             }
635         }
636         connectors.add(HttpClientConnectionFactory.HTTP11); // HTTP/1.1, always supported but has least priority
637 
638         HttpClientTransportDynamic dynamicTransport = new HttpClientTransportDynamic(
639                 clientConnector, connectors.toArray(new ClientConnectionFactory.Info[0]));
640         HttpClient httpClient = new HttpClient(dynamicTransport);
641         httpClient.setConnectTimeout(connectTimeout);
642         httpClient.setIdleTimeout(requestTimeout);
643         RedirectMode redirectMode = HttpTransporterUtils.getRedirectMode(
644                 session,
645                 repository,
646                 JettyTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS,
647                 JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS);
648         httpClient.setFollowRedirects(redirectMode != RedirectMode.NONE);
649         httpClient.setMaxRedirects(ConfigUtils.getInteger(
650                 session,
651                 JettyTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS,
652                 JettyTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS));
653 
654         boolean followInsecureRedirects = HttpTransporterUtils.isFollowInsecureRedirect(
655                 session, repository, JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS);
656         boolean originScopedHeaders = HttpTransporterUtils.isOriginScopedHeaders(
657                 session, repository, JettyTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS);
658 
659         httpClient.setUserAgentField(null); // we manage it
660 
661         if (basicAuthentication != null) {
662             httpClient.getAuthenticationStore().addAuthentication(basicAuthentication);
663         }
664 
665         if (repository.getProxy() != null) {
666             HttpProxy proxy = new HttpProxy(
667                     repository.getProxy().getHost(), repository.getProxy().getPort());
668 
669             httpClient.getProxyConfiguration().addProxy(proxy);
670             try (AuthenticationContext proxyAuthContext = AuthenticationContext.forProxy(session, repository)) {
671                 if (proxyAuthContext != null) {
672                     String username = proxyAuthContext.get(AuthenticationContext.USERNAME);
673                     String password = proxyAuthContext.get(AuthenticationContext.PASSWORD);
674 
675                     BasicAuthentication proxyAuthentication =
676                             new BasicAuthentication(proxy.getURI(), Authentication.ANY_REALM, username, password);
677 
678                     httpClient.getAuthenticationStore().addAuthentication(proxyAuthentication);
679                     if (preemptiveAuth || preemptivePutAuth) {
680                         proxyAuth = new BasicAuthentication.BasicResult(
681                                 proxy.getURI(), HttpHeader.PROXY_AUTHORIZATION, username, password);
682                     }
683                 }
684             }
685         }
686         if (serverAuth != null) {
687             this.basicServerAuthenticationResult.set(serverAuth);
688         }
689         if (proxyAuth != null) {
690             this.basicProxyAuthenticationResult.set(proxyAuth);
691         }
692 
693         try {
694             httpClient.start();
695 
696             // Register request listeners after start() so that Jetty's content decoder factories are
697             // fully initialized first.
698             if (!followInsecureRedirects && "https".equalsIgnoreCase(repository.getProtocol())) {
699                 // this client serves exactly one repository: any non-https request it ever issues can only be the
700                 // result of following a protocol-downgrading redirect, so refuse it before anything is sent
701                 httpClient.getRequestListeners().addQueuedListener(new InsecureRedirectGuard());
702             }
703             if (redirectMode == RedirectMode.SAME_AUTHORITY) {
704                 httpClient.getRequestListeners().addQueuedListener(new SameAuthorityRedirectGuard(baseUri));
705             }
706             if (originScopedHeaders) {
707                 // Jetty's redirector copies the request headers onto every redirect hop it follows; scope configured
708                 // headers (and preemptively applied Authorization) to the repository origin so a cross-origin redirect
709                 // does not replay them to the redirect target. The copied redirect request passes through the
710                 // client-level request listeners again, same mechanism as the InsecureRedirectGuard above.
711                 // Challenge-based authentication from the authentication store is URI-scoped by Jetty already.
712                 //
713                 // Only register the listener when there are actual credentials or configured headers to protect:
714                 // without preemptive authentication or user-configured headers, there is nothing on the request
715                 // that could leak to a redirect target, so registering the listener would be a no-op.
716                 Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
717                 boolean hasPreemptiveAuth = basicAuthentication != null;
718                 boolean hasConfiguredHeaders = configuredHeaders != null && !configuredHeaders.isEmpty();
719                 if (hasPreemptiveAuth || hasConfiguredHeaders) {
720                     TreeSet<String> scopedHeaderNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
721                     scopedHeaderNames.add(HttpHeader.AUTHORIZATION.asString());
722                     if (hasConfiguredHeaders) {
723                         scopedHeaderNames.addAll(configuredHeaders.keySet());
724                     }
725                     httpClient
726                             .getRequestListeners()
727                             .addHeadersListener(new OriginScopedHeadersListener(baseUri, scopedHeaderNames));
728                 }
729             }
730 
731             return httpClient;
732         } catch (Exception e) {
733             if (e instanceof RuntimeException) {
734                 throw (RuntimeException) e;
735             } else {
736                 throw new IllegalStateException("Jetty client start failure", e);
737             }
738         }
739     }
740 }