You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by cs...@apache.org on 2026/08/31 11:30:07 UTC
(maven-resolver) branch master updated: fix: bind credentials to origin and reject TLS downgrade redirects (#2085)
This is an automated email from the ASF dual-hosted git repository.
cstamas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-resolver.git
The following commit(s) were added to refs/heads/master by this push:
new 89da7279c fix: bind credentials to origin and reject TLS downgrade redirects (#2085)
89da7279c is described below
commit 89da7279c501fdc495829fadd451c9b7eb43eb86
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Mon Aug 31 13:30:01 2026 +0200
fix: bind credentials to origin and reject TLS downgrade redirects (#2085)
## Summary
Fixes 5 findings from the maven-resolver security audit (scan-maven-resolver-20260811):
| Finding | Severity | Description |
|---------|----------|-------------|
| f002 | MEDIUM | Settings credentials attached by bare ID to POM-declared repositories |
| f008 | MEDIUM | Apache transport silently follows https-to-http downgrade redirects |
| f009 | MEDIUM | JDK transport Authenticator hands credentials to any challenging host |
| f016 | MEDIUM | Jetty transport follows https-to-http redirects without a downgrade guard |
| f027 | LOW | Operator-configured static auth headers follow redirects cross-origin |
**Root cause:** Credential release decisions ignore where the request is actually going: selectors match on bare repository id with no host binding, authenticators answer any challenger, redirect handling follows cross-origin and https-to-http hops.
**Fix:** Enforce one rule across all transports: credentials go only to the configured origin, and https never silently becomes http.
---
.../eclipse/aether/ConfigurationProperties.java | 9 +
.../aether/transport/apache/ApacheTransporter.java | 37 ++-
.../apache/ApacheTransporterConfigurationKeys.java | 33 +++
.../apache/OriginScopedHeadersInterceptor.java | 90 ++++++++
.../transport/apache/ResolverRedirectStrategy.java | 86 +++++++
.../apache/OriginScopedHeadersInterceptorTest.java | 138 +++++++++++
.../apache/ResolverRedirectStrategyTest.java | 133 +++++++++++
.../aether/transport/jdk/JdkTransporter.java | 256 ++++++++++++++++++++-
.../jdk/JdkTransporterConfigurationKeys.java | 37 +++
.../transport/jdk/JdkTransporterRedirectTest.java | 182 +++++++++++++++
.../transport/jdk/ScopedAuthenticatorTest.java | 121 ++++++++++
.../transport/jetty/InsecureRedirectGuard.java | 48 ++++
.../aether/transport/jetty/JettyTransporter.java | 46 ++++
.../jetty/JettyTransporterConfigurationKeys.java | 33 +++
.../jetty/OriginScopedHeadersListener.java | 99 ++++++++
.../transport/jetty/InsecureRedirectGuardTest.java | 81 +++++++
.../jetty/OriginScopedHeadersListenerTest.java | 147 ++++++++++++
17 files changed, 1564 insertions(+), 12 deletions(-)
diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java b/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java
index 2ba552d1e..9883780c7 100644
--- a/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java
+++ b/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java
@@ -247,6 +247,15 @@ public final class ConfigurationProperties {
* specify headers for a specific remote repository by appending the suffix {@code .<repoId>} to this key when
* storing the headers map. The repository-specific headers map is supposed to be complete, i.e. is not merged with
* the general headers map.
+ * <p>
+ * <strong>Security note:</strong> configured headers are attached to every request the transport sends for the
+ * repository and, depending on the transport implementation, may be re-sent when the repository responds with
+ * a redirect - including redirects that leave the repository origin. Avoid placing credentials (for example
+ * {@code Authorization}, cookies or private token headers) in this map where repository authentication can be
+ * used instead: repository authentication is negotiated per host. All shipped HTTP transports scope configured
+ * headers to the repository origin by default, see the per-transport {@code originScopedHeaders} configuration
+ * keys ({@code aether.transport.apache.originScopedHeaders}, {@code aether.transport.jdk.originScopedHeaders},
+ * {@code aether.transport.jetty.originScopedHeaders}).
*
* @configurationSource {@link RepositorySystemSession#getConfigProperties()}
* @configurationType {@link java.util.Map}
diff --git a/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporter.java b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporter.java
index defae1430..34765c82e 100644
--- a/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporter.java
+++ b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporter.java
@@ -85,7 +85,6 @@ import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
@@ -119,11 +118,13 @@ import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
+import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_NAME;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_USE_SYSTEM_PROPERTIES;
+import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_FOLLOW_INSECURE_REDIRECTS;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED;
import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS;
@@ -234,6 +235,11 @@ final class ApacheTransporter extends AbstractTransporter implements HttpTranspo
DEFAULT_FOLLOW_REDIRECTS,
CONFIG_PROP_FOLLOW_REDIRECTS + "." + repository.getId(),
CONFIG_PROP_FOLLOW_REDIRECTS);
+ boolean followInsecureRedirects = ConfigUtils.getBoolean(
+ session,
+ DEFAULT_FOLLOW_INSECURE_REDIRECTS,
+ CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS + "." + repository.getId(),
+ CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS);
String userAgent = HttpTransporterUtils.getUserAgent(session, repository);
Charset credentialsCharset = HttpTransporterUtils.getHttpCredentialsEncoding(session, repository);
@@ -279,7 +285,7 @@ final class ApacheTransporter extends AbstractTransporter implements HttpTranspo
HttpClientBuilder builder = HttpClientBuilder.create()
.setUserAgent(userAgent)
- .setRedirectStrategy(LaxRedirectStrategy.INSTANCE)
+ .setRedirectStrategy(new ResolverRedirectStrategy(followInsecureRedirects))
.setDefaultSocketConfig(socketConfig)
.setDefaultRequestConfig(requestConfig)
.setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
@@ -289,6 +295,16 @@ final class ApacheTransporter extends AbstractTransporter implements HttpTranspo
.setConnectionManagerShared(true)
.setDefaultCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext))
.setProxy(proxy);
+ if (ConfigUtils.getBoolean(
+ session,
+ ApacheTransporterConfigurationKeys.DEFAULT_ORIGIN_SCOPED_HEADERS,
+ ApacheTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS + "." + repository.getId(),
+ ApacheTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS)) {
+ // Configured headers are per-repository data and frequently carry credentials; scope them to the
+ // repository origin so a cross-origin redirect hop does not replay them to the redirect target.
+ // Challenge-based credentials are host-scoped by the credentials provider already.
+ builder.addInterceptorLast(new OriginScopedHeadersInterceptor(server, this.headers.keySet()));
+ }
final boolean useSystemProperties = ConfigUtils.getBoolean(
session,
DEFAULT_USE_SYSTEM_PROPERTIES,
@@ -348,7 +364,8 @@ final class ApacheTransporter extends AbstractTransporter implements HttpTranspo
private static CredentialsProvider toCredentialsProvider(
HttpHost server, AuthenticationContext serverAuthCtx, HttpHost proxy, AuthenticationContext proxyAuthCtx) {
- CredentialsProvider provider = toCredentialsProvider(server.getHostName(), AuthScope.ANY_PORT, serverAuthCtx);
+ CredentialsProvider provider =
+ toCredentialsProvider(server.getHostName(), effectivePort(server), serverAuthCtx);
if (proxy != null) {
CredentialsProvider p = toCredentialsProvider(proxy.getHostName(), proxy.getPort(), proxyAuthCtx);
provider = new DemuxCredentialsProvider(provider, p, proxy);
@@ -356,6 +373,20 @@ final class ApacheTransporter extends AbstractTransporter implements HttpTranspo
return provider;
}
+ /**
+ * Determines the effective port of the given host: the explicit port if present, otherwise the default port
+ * implied by the scheme. Used to bind repository credentials to the repository's own origin (host and port)
+ * instead of {@link AuthScope#ANY_PORT}: with any-port scoping, a request landing on the same host but a
+ * different port - for example after an https-to-http downgrade redirect - would still be eligible to
+ * receive the credentials.
+ */
+ static int effectivePort(HttpHost host) {
+ if (host.getPort() >= 0) {
+ return host.getPort();
+ }
+ return "https".equalsIgnoreCase(host.getSchemeName()) ? 443 : 80;
+ }
+
private static CredentialsProvider toCredentialsProvider(String host, int port, AuthenticationContext ctx) {
DeferredCredentialsProvider provider = new DeferredCredentialsProvider();
if (ctx != null) {
diff --git a/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporterConfigurationKeys.java b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporterConfigurationKeys.java
index 9948e6cbf..fdfaf0efc 100644
--- a/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporterConfigurationKeys.java
+++ b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ApacheTransporterConfigurationKeys.java
@@ -109,6 +109,24 @@ public final class ApacheTransporterConfigurationKeys {
public static final boolean DEFAULT_FOLLOW_REDIRECTS = true;
+ /**
+ * If enabled (default), operator-configured request headers ({@code aether.transport.http.headers}) are only
+ * sent on requests targeting the repository origin (the scheme, host and port the repository URL denotes).
+ * Apache HttpClient re-sends the original request headers on redirects, so without origin scoping a
+ * cross-origin redirect replays the configured headers - which frequently carry credentials such as
+ * {@code Authorization}, cookies or private token headers - to the redirect target host. Disable only when a
+ * redirect target legitimately requires the configured headers.
+ *
+ * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
+ * @configurationType {@link Boolean}
+ * @configurationDefaultValue {@link #DEFAULT_ORIGIN_SCOPED_HEADERS}
+ * @configurationRepoIdSuffix Yes
+ * @since 2.0.23
+ */
+ public static final String CONFIG_PROP_ORIGIN_SCOPED_HEADERS = CONFIG_PROPS_PREFIX + "originScopedHeaders";
+
+ public static final boolean DEFAULT_ORIGIN_SCOPED_HEADERS = true;
+
/**
* The max redirect count to follow.
*
@@ -121,4 +139,19 @@ public final class ApacheTransporterConfigurationKeys {
public static final String CONFIG_PROP_MAX_REDIRECTS = CONFIG_PROPS_PREFIX + "maxRedirects";
public static final int DEFAULT_MAX_REDIRECTS = 5;
+
+ /**
+ * If enabled, Apache HttpClient will follow redirects that downgrade the protocol from https to http. Disabled
+ * by default: such a downgrade strips transport encryption from artifact and checksum bytes and makes repository
+ * credentials eligible for transmission over plaintext, so a downgrading redirect fails the transfer instead.
+ *
+ * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
+ * @configurationType {@link Boolean}
+ * @configurationDefaultValue {@link #DEFAULT_FOLLOW_INSECURE_REDIRECTS}
+ * @configurationRepoIdSuffix Yes
+ * @since 2.0.23
+ */
+ public static final String CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS = CONFIG_PROPS_PREFIX + "followInsecureRedirects";
+
+ public static final boolean DEFAULT_FOLLOW_INSECURE_REDIRECTS = false;
}
diff --git a/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/OriginScopedHeadersInterceptor.java b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/OriginScopedHeadersInterceptor.java
new file mode 100644
index 000000000..7d21fb043
--- /dev/null
+++ b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/OriginScopedHeadersInterceptor.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.apache;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpRequestInterceptor;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpCoreContext;
+
+/**
+ * Scopes operator-configured request headers ({@code aether.transport.http.headers}) to the repository origin.
+ * <p>
+ * Configured headers are stamped on every request the transport creates and frequently carry credentials
+ * ({@code Authorization}, cookies, private token headers). Apache HttpClient's redirect execution re-sends the
+ * original request headers on each redirect hop, including hops that leave the repository origin, which would
+ * replay those credentials to the redirect target. This interceptor runs in the protocol layer - which HttpClient
+ * re-enters for every redirect hop - and removes the configured headers from any request whose target host is not
+ * the repository origin (same scheme, host and effective port). Challenge- and preemptive-authentication headers
+ * are attached below the protocol layer and are host-scoped by the credentials provider already; they are not
+ * affected by this interceptor.
+ *
+ * @since 2.0.23
+ */
+final class OriginScopedHeadersInterceptor implements HttpRequestInterceptor {
+ private final HttpHost origin;
+
+ private final Set<String> headerNames;
+
+ OriginScopedHeadersInterceptor(HttpHost origin, Collection<?> headerNames) {
+ this.origin = origin;
+ this.headerNames = new HashSet<>();
+ for (Object headerName : headerNames) {
+ if (headerName != null) {
+ this.headerNames.add(String.valueOf(headerName));
+ }
+ }
+ }
+
+ @Override
+ public void process(HttpRequest request, HttpContext context) {
+ if (headerNames.isEmpty()) {
+ return;
+ }
+ Object attribute = context != null ? context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST) : null;
+ // fail closed: when the target host cannot be determined, do not attach configured headers
+ if (!(attribute instanceof HttpHost) || !isSameOrigin(origin, (HttpHost) attribute)) {
+ for (String headerName : headerNames) {
+ request.removeHeaders(headerName);
+ }
+ }
+ }
+
+ static boolean isSameOrigin(HttpHost origin, HttpHost target) {
+ return origin.getSchemeName().equalsIgnoreCase(target.getSchemeName())
+ && origin.getHostName().equalsIgnoreCase(target.getHostName())
+ && schemeDefaultPort(origin) == schemeDefaultPort(target);
+ }
+
+ /**
+ * Determines the effective port of the given host: the explicit port if present, otherwise the default port
+ * implied by the scheme.
+ */
+ static int schemeDefaultPort(HttpHost host) {
+ if (host.getPort() >= 0) {
+ return host.getPort();
+ }
+ return "https".equalsIgnoreCase(host.getSchemeName()) ? 443 : 80;
+ }
+}
diff --git a/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ResolverRedirectStrategy.java b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ResolverRedirectStrategy.java
new file mode 100644
index 000000000..9f8579056
--- /dev/null
+++ b/maven-resolver-transport-apache/src/main/java/org/eclipse/aether/transport/apache/ResolverRedirectStrategy.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.apache;
+
+import java.net.URI;
+
+import org.apache.http.Header;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.ProtocolException;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.LaxRedirectStrategy;
+import org.apache.http.protocol.HttpContext;
+
+/**
+ * A redirect strategy that refuses protocol downgrades: a redirect from an {@code https} URL to an {@code http}
+ * URL strips transport encryption from artifact and checksum bytes and makes repository credentials eligible for
+ * transmission over plaintext, so it fails the transfer instead of being followed silently, unless explicitly
+ * allowed via {@link ApacheTransporterConfigurationKeys#CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS}. All other
+ * redirects behave exactly as {@link LaxRedirectStrategy} handled them before.
+ *
+ * @since 2.0.23
+ */
+final class ResolverRedirectStrategy extends LaxRedirectStrategy {
+ private final boolean followInsecureRedirects;
+
+ ResolverRedirectStrategy(boolean followInsecureRedirects) {
+ this.followInsecureRedirects = followInsecureRedirects;
+ }
+
+ @Override
+ public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
+ throws ProtocolException {
+ boolean redirected = super.isRedirected(request, response, context);
+ if (redirected && !followInsecureRedirects) {
+ Header locationHeader = response.getFirstHeader("location");
+ if (locationHeader != null) {
+ URI location = createLocationURI(locationHeader.getValue());
+ String locationScheme = location.getScheme();
+ String currentScheme = currentScheme(request, context);
+ if (locationScheme != null
+ && "https".equalsIgnoreCase(currentScheme)
+ && !"https".equalsIgnoreCase(locationScheme)) {
+ throw new ProtocolException("Insecure redirect to '" + location
+ + "' not followed: protocol downgrade from https to " + locationScheme
+ + " would expose credentials and artifact content; set the configuration property "
+ + ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS
+ + "=true to allow it");
+ }
+ }
+ }
+ return redirected;
+ }
+
+ private static String currentScheme(HttpRequest request, HttpContext context) {
+ HttpHost target = context != null ? HttpClientContext.adapt(context).getTargetHost() : null;
+ if (target != null) {
+ return target.getSchemeName();
+ }
+ if (request instanceof HttpUriRequest) {
+ URI uri = ((HttpUriRequest) request).getURI();
+ if (uri != null && uri.isAbsolute()) {
+ return uri.getScheme();
+ }
+ }
+ return null;
+ }
+}
diff --git a/maven-resolver-transport-apache/src/test/java/org/eclipse/aether/transport/apache/OriginScopedHeadersInterceptorTest.java b/maven-resolver-transport-apache/src/test/java/org/eclipse/aether/transport/apache/OriginScopedHeadersInterceptorTest.java
new file mode 100644
index 000000000..afc426e83
--- /dev/null
+++ b/maven-resolver-transport-apache/src/test/java/org/eclipse/aether/transport/apache/OriginScopedHeadersInterceptorTest.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.apache;
+
+import java.util.Arrays;
+
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.message.BasicHttpRequest;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpCoreContext;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * UT for {@link OriginScopedHeadersInterceptor}: configured headers must only be sent to the repository origin;
+ * any other target (cross-host, downgraded scheme or different port - e.g. after a redirect) must not receive them.
+ */
+public class OriginScopedHeadersInterceptorTest {
+ private static final HttpHost ORIGIN = new HttpHost("repo.example.com", -1, "https");
+
+ private final OriginScopedHeadersInterceptor interceptor =
+ new OriginScopedHeadersInterceptor(ORIGIN, Arrays.asList("Authorization", "Private-Token"));
+
+ private static HttpRequest newRequestWithConfiguredHeaders() {
+ HttpRequest request = new BasicHttpRequest("GET", "/base/g/a/1.0/a-1.0.jar");
+ request.setHeader("Authorization", "Bearer s3cr3t");
+ request.setHeader("Private-Token", "t0ken");
+ request.setHeader("Accept", "*/*");
+ return request;
+ }
+
+ private static HttpContext contextTargeting(HttpHost target) {
+ HttpCoreContext context = HttpCoreContext.create();
+ if (target != null) {
+ context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
+ }
+ return context;
+ }
+
+ private static void assertConfiguredHeadersPresent(HttpRequest request) {
+ assertTrue(request.containsHeader("Authorization"));
+ assertTrue(request.containsHeader("Private-Token"));
+ assertTrue(request.containsHeader("Accept"));
+ }
+
+ private static void assertConfiguredHeadersStripped(HttpRequest request) {
+ assertFalse(request.containsHeader("Authorization"));
+ assertFalse(request.containsHeader("Private-Token"));
+ // headers not coming from the configured map are left alone
+ assertTrue(request.containsHeader("Accept"));
+ }
+
+ @Test
+ void keepsHeadersForOrigin() throws Exception {
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(new HttpHost("repo.example.com", -1, "https")));
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void keepsHeadersForOriginWithExplicitDefaultPort() throws Exception {
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(new HttpHost("repo.example.com", 443, "https")));
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void keepsHeadersForOriginWithDifferentHostCase() throws Exception {
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(new HttpHost("REPO.Example.COM", -1, "HTTPS")));
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void stripsHeadersForCrossHostTarget() throws Exception {
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(new HttpHost("cdn.example.net", -1, "https")));
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void stripsHeadersForSchemeDowngradeOnSameHost() throws Exception {
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(new HttpHost("repo.example.com", -1, "http")));
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void stripsHeadersForDifferentPortOnSameHost() throws Exception {
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(new HttpHost("repo.example.com", 8443, "https")));
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void stripsHeadersWhenTargetHostUnknown() throws Exception {
+ // fail closed: no determinable target means configured headers are not attached
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ interceptor.process(request, contextTargeting(null));
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void noConfiguredHeadersIsNoOp() throws Exception {
+ OriginScopedHeadersInterceptor empty =
+ new OriginScopedHeadersInterceptor(ORIGIN, Arrays.asList(new Object[] {null}));
+ HttpRequest request = newRequestWithConfiguredHeaders();
+ empty.process(request, contextTargeting(new HttpHost("cdn.example.net", -1, "https")));
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void effectivePortFollowsScheme() {
+ assertEquals(443, OriginScopedHeadersInterceptor.schemeDefaultPort(new HttpHost("h", -1, "https")));
+ assertEquals(80, OriginScopedHeadersInterceptor.schemeDefaultPort(new HttpHost("h", -1, "http")));
+ assertEquals(8081, OriginScopedHeadersInterceptor.schemeDefaultPort(new HttpHost("h", 8081, "https")));
+ }
+}
diff --git a/maven-resolver-transport-apache/src/test/java/org/eclipse/aether/transport/apache/ResolverRedirectStrategyTest.java b/maven-resolver-transport-apache/src/test/java/org/eclipse/aether/transport/apache/ResolverRedirectStrategyTest.java
new file mode 100644
index 000000000..756bcc11c
--- /dev/null
+++ b/maven-resolver-transport-apache/src/test/java/org/eclipse/aether/transport/apache/ResolverRedirectStrategyTest.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.apache;
+
+import org.apache.http.HttpHost;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpVersion;
+import org.apache.http.ProtocolException;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.message.BasicHttpResponse;
+import org.apache.http.message.BasicStatusLine;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpCoreContext;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * UT for {@link ResolverRedirectStrategy}: https-to-http downgrade redirects must not be followed silently, and
+ * repository credentials must be bound to the repository's scheme-implied port.
+ */
+class ResolverRedirectStrategyTest {
+ private static HttpResponse redirectResponse(String location) {
+ HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 302, "Found"));
+ response.setHeader("Location", location);
+ return response;
+ }
+
+ private static HttpContext contextWithTarget(HttpHost target) {
+ HttpClientContext context = HttpClientContext.create();
+ context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
+ return context;
+ }
+
+ @Test
+ void httpsToHttpRedirectRefusedByDefault() {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(false);
+ HttpGet request = new HttpGet("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("http://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpContext context = contextWithTarget(new HttpHost("repo.example.com", 443, "https"));
+
+ ProtocolException e =
+ assertThrows(ProtocolException.class, () -> strategy.isRedirected(request, response, context));
+ assertTrue(e.getMessage().contains(ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS));
+ }
+
+ @Test
+ void httpsToHttpCrossHostRedirectRefusedByDefault() {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(false);
+ HttpGet request = new HttpGet("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("http://evil.example.org/g/a/1.0/a-1.0.jar");
+ HttpContext context = contextWithTarget(new HttpHost("repo.example.com", 443, "https"));
+
+ assertThrows(ProtocolException.class, () -> strategy.isRedirected(request, response, context));
+ }
+
+ @Test
+ void httpsToHttpsRedirectFollowed() throws ProtocolException {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(false);
+ HttpGet request = new HttpGet("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("https://mirror.example.com/g/a/1.0/a-1.0.jar");
+ HttpContext context = contextWithTarget(new HttpHost("repo.example.com", 443, "https"));
+
+ assertTrue(strategy.isRedirected(request, response, context));
+ }
+
+ @Test
+ void relativeRedirectFollowed() throws ProtocolException {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(false);
+ HttpGet request = new HttpGet("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("/elsewhere/a-1.0.jar");
+ HttpContext context = contextWithTarget(new HttpHost("repo.example.com", 443, "https"));
+
+ assertTrue(strategy.isRedirected(request, response, context));
+ }
+
+ @Test
+ void httpToHttpRedirectFollowed() throws ProtocolException {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(false);
+ HttpGet request = new HttpGet("http://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("http://mirror.example.com/g/a/1.0/a-1.0.jar");
+ HttpContext context = contextWithTarget(new HttpHost("repo.example.com", 80, "http"));
+
+ assertTrue(strategy.isRedirected(request, response, context));
+ }
+
+ @Test
+ void httpsToHttpRedirectFollowedWhenExplicitlyAllowed() throws ProtocolException {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(true);
+ HttpGet request = new HttpGet("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("http://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpContext context = contextWithTarget(new HttpHost("repo.example.com", 443, "https"));
+
+ assertTrue(strategy.isRedirected(request, response, context));
+ }
+
+ @Test
+ void currentSchemeFallsBackToRequestUriWithoutContextTarget() {
+ ResolverRedirectStrategy strategy = new ResolverRedirectStrategy(false);
+ HttpGet request = new HttpGet("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ HttpResponse response = redirectResponse("http://repo.example.com/g/a/1.0/a-1.0.jar");
+
+ assertThrows(
+ ProtocolException.class, () -> strategy.isRedirected(request, response, HttpClientContext.create()));
+ }
+
+ @Test
+ void repositoryCredentialScopeIsBoundToSchemeImpliedPort() {
+ assertEquals(443, ApacheTransporter.effectivePort(new HttpHost("repo.example.com", -1, "https")));
+ assertEquals(80, ApacheTransporter.effectivePort(new HttpHost("repo.example.com", -1, "http")));
+ assertEquals(8443, ApacheTransporter.effectivePort(new HttpHost("repo.example.com", 8443, "https")));
+ assertEquals(8081, ApacheTransporter.effectivePort(new HttpHost("repo.example.com", 8081, "http")));
+ }
+}
diff --git a/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporter.java b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporter.java
index 49203ef49..2ce6137b8 100644
--- a/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporter.java
+++ b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporter.java
@@ -64,6 +64,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.util.TreeSet;
import java.util.concurrent.Semaphore;
import java.util.function.Function;
import java.util.regex.Matcher;
@@ -110,7 +111,9 @@ import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.RANG
import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.USER_AGENT;
import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.CONFIG_PROP_HTTP_VERSION;
import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.CONFIG_PROP_MAX_CONCURRENT_REQUESTS;
+import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.CONFIG_PROP_UNSCOPED_AUTHENTICATION;
import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.DEFAULT_MAX_CONCURRENT_REQUESTS;
+import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.DEFAULT_UNSCOPED_AUTHENTICATION;
/**
* JDK Transport using {@link HttpClient}.
@@ -133,6 +136,14 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
private static final long MODIFICATION_THRESHOLD = 60L * 1000L;
+ /**
+ * Maximum redirect hops followed when this transporter follows redirects itself (origin-scoped headers mode);
+ * same limit as the JDK {@link HttpClient}'s own default ({@code jdk.httpclient.redirects.retrylimit}).
+ */
+ private static final int MAX_REDIRECTS = 5;
+
+ private static final String LOCATION = "Location";
+
/**
* Classes of IOExceptions that should not be retried (because they are permanent failures).
* Same as in <a href="https://github.com/apache/httpcomponents-client/blob/54900db4653d7f207477e6ee40135b88e9bcf832/httpclient/src/main/java/org/apache/http/impl/client/DefaultHttpRequestRetryHandler.java#L102">
@@ -155,6 +166,10 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
private final Map<String, String> headers;
+ private final boolean originScopedHeaders;
+
+ private final Set<String> crossOriginExcludedHeaders;
+
private final int connectTimeout;
private final int requestTimeout;
@@ -225,6 +240,19 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
this.preemptivePutAuth = HttpTransporterUtils.isHttpPreemptivePutAuth(session, repository);
this.sendRfc9457Accept = HttpTransporterUtils.isHttpSendRfc9457Accept(session, repository);
+ this.originScopedHeaders = ConfigUtils.getBoolean(
+ session,
+ JdkTransporterConfigurationKeys.DEFAULT_ORIGIN_SCOPED_HEADERS,
+ JdkTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS + "." + repository.getId(),
+ JdkTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS);
+ TreeSet<String> crossOriginExcludedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+ // preemptively applied Authorization (see #prepare) must never leave the repository origin either
+ crossOriginExcludedHeaders.add("Authorization");
+ if (configuredHeaders != null) {
+ crossOriginExcludedHeaders.addAll(configuredHeaders.keySet());
+ }
+ this.crossOriginExcludedHeaders = crossOriginExcludedHeaders;
+
this.headers = headers;
this.client = createClient(session, repository, insecure);
}
@@ -482,12 +510,131 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
throws Exception {
maxConcurrentRequests.acquire();
try {
- return client.send(request, responseBodyHandler);
+ if (!originScopedHeaders) {
+ return client.send(request, responseBodyHandler);
+ }
+ // the client is configured with Redirect.NEVER: follow redirects here instead, so that configured
+ // headers (and preemptively applied Authorization) can be scoped to the repository origin per hop -
+ // the JDK client itself re-sends all user-set headers on every hop it follows, with no per-hop hook
+ HttpRequest current = request;
+ int redirects = 0;
+ while (true) {
+ HttpResponse<T> response =
+ client.send(current, discardingOnFollowedRedirect(responseBodyHandler, current.uri()));
+ URI target = followableRedirect(
+ response.statusCode(),
+ current.uri(),
+ response.headers().firstValue(LOCATION).orElse(null));
+ if (target == null) {
+ return response;
+ }
+ redirects++;
+ if (redirects > MAX_REDIRECTS) {
+ throw new IOException("Too many redirects for " + request.uri() + " (max " + MAX_REDIRECTS
+ + "), last redirect target: " + target);
+ }
+ current = redirectRequest(current, response.statusCode(), target, baseUri, crossOriginExcludedHeaders);
+ }
} finally {
maxConcurrentRequests.release();
}
}
+ /**
+ * Body handler that discards the body of responses this transporter is about to follow as redirect (the
+ * caller only ever sees the final response of the hop chain), delegating everything else to the original
+ * handler.
+ */
+ private static <T> HttpResponse.BodyHandler<T> discardingOnFollowedRedirect(
+ HttpResponse.BodyHandler<T> delegate, URI requestUri) {
+ return responseInfo -> {
+ String location = responseInfo.headers().firstValue(LOCATION).orElse(null);
+ if (followableRedirect(responseInfo.statusCode(), requestUri, location) != null) {
+ return HttpResponse.BodySubscribers.mapping(HttpResponse.BodySubscribers.discarding(), v -> null);
+ }
+ return delegate.apply(responseInfo);
+ };
+ }
+
+ /**
+ * Returns the resolved redirect target if the response is a redirect this transporter follows, otherwise
+ * {@code null}. Follow rules mirror {@link HttpClient.Redirect#NORMAL}: redirect status with a resolvable
+ * {@code Location}, {@code http}/{@code https} targets only, and never a downgrade from https to http.
+ */
+ static URI followableRedirect(int statusCode, URI requestUri, String locationHeader) {
+ if (!isRedirect(statusCode) || locationHeader == null) {
+ return null;
+ }
+ final URI target;
+ try {
+ target = requestUri.resolve(locationHeader);
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ String scheme = target.getScheme();
+ if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
+ return null;
+ }
+ if ("https".equalsIgnoreCase(requestUri.getScheme()) && !"https".equalsIgnoreCase(scheme)) {
+ return null;
+ }
+ return target;
+ }
+
+ static boolean isRedirect(int statusCode) {
+ return statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307 || statusCode == 308;
+ }
+
+ /**
+ * Builds the next-hop request: the previous request re-targeted at the redirect target, with the origin-scoped
+ * headers (operator-configured headers and preemptively applied {@code Authorization}) removed when the target
+ * is not the repository origin (same scheme, case-insensitive host and effective port). Method rewriting
+ * mirrors {@link HttpClient.Redirect#NORMAL}.
+ */
+ static HttpRequest redirectRequest(
+ HttpRequest previous, int statusCode, URI target, URI baseUri, Set<String> crossOriginExcludedHeaders) {
+ HttpRequest.Builder builder = HttpRequest.newBuilder().uri(target).expectContinue(previous.expectContinue());
+ previous.version().ifPresent(builder::version);
+ previous.timeout().ifPresent(builder::timeout);
+ boolean sameOrigin = isSameOrigin(baseUri, target);
+ previous.headers().map().forEach((name, values) -> {
+ if (sameOrigin || !crossOriginExcludedHeaders.contains(name)) {
+ for (String value : values) {
+ builder.header(name, value);
+ }
+ }
+ });
+ String method = previous.method();
+ if (statusCode == 303 && !"HEAD".equals(method)) {
+ builder.method("GET", HttpRequest.BodyPublishers.noBody());
+ } else if ((statusCode == 301 || statusCode == 302) && "POST".equals(method)) {
+ builder.method("GET", HttpRequest.BodyPublishers.noBody());
+ } else {
+ builder.method(method, previous.bodyPublisher().orElse(HttpRequest.BodyPublishers.noBody()));
+ }
+ return builder.build();
+ }
+
+ static boolean isSameOrigin(URI origin, URI target) {
+ if (origin.getScheme() == null
+ || origin.getHost() == null
+ || target.getScheme() == null
+ || target.getHost() == null) {
+ return false;
+ }
+ return origin.getScheme().equalsIgnoreCase(target.getScheme())
+ && origin.getHost().equalsIgnoreCase(target.getHost())
+ && effectivePort(origin.getScheme(), origin.getPort())
+ == effectivePort(target.getScheme(), target.getPort());
+ }
+
+ static int effectivePort(String scheme, int port) {
+ if (port >= 0) {
+ return port;
+ }
+ return "https".equalsIgnoreCase(scheme) ? 443 : 80;
+ }
+
@Override
protected void implClose() {
if (client != null) {
@@ -614,7 +761,10 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
Methanol.Builder builder = Methanol.newBuilder()
.version(httpVersion)
- .followRedirects(HttpClient.Redirect.NORMAL)
+ // with origin-scoped headers (default) the transporter follows redirects itself (see #send) so
+ // that configured headers can be dropped on hops leaving the repository origin; the JDK client
+ // has no per-hop hook and re-sends all user-set headers on every hop it follows
+ .followRedirects(originScopedHeaders ? HttpClient.Redirect.NEVER : HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofMillis(connectTimeout))
// this only considers the time until the response header is received, see
// https://bugs.openjdk.org/browse/JDK-8208693
@@ -632,8 +782,9 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
builder,
HttpTransporterUtils.getHttpLocalAddress(session, repository).orElse(null));
+ InetSocketAddress proxyAddress = null;
if (repository.getProxy() != null) {
- InetSocketAddress proxyAddress = new InetSocketAddress(
+ proxyAddress = new InetSocketAddress(
repository.getProxy().getHost(), repository.getProxy().getPort());
if (proxyAddress.isUnresolved()) {
throw new IllegalStateException(
@@ -652,12 +803,22 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
}
if (!authentications.isEmpty()) {
- builder.authenticator(new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return authentications.get(getRequestorType());
- }
- });
+ boolean unscopedAuthentication = ConfigUtils.getBoolean(
+ session,
+ DEFAULT_UNSCOPED_AUTHENTICATION,
+ CONFIG_PROP_UNSCOPED_AUTHENTICATION + "." + repository.getId(),
+ CONFIG_PROP_UNSCOPED_AUTHENTICATION);
+ if (unscopedAuthentication) {
+ // legacy behavior, explicit opt-in only: hands out credentials to ANY challenging host
+ builder.authenticator(new Authenticator() {
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return authentications.get(getRequestorType());
+ }
+ });
+ } else {
+ builder.authenticator(new ScopedAuthenticator(baseUri, proxyAddress, authentications));
+ }
}
configureRetryHandler(session, repository, builder);
@@ -665,6 +826,83 @@ final class JdkTransporter extends AbstractTransporter implements HttpTransporte
return builder.build();
}
+ /**
+ * An {@link Authenticator} that only hands out credentials to the origin it was configured for. The JDK
+ * {@link HttpClient} consults the authenticator for any host that answers with an authentication challenge -
+ * including hosts reached by following redirects off the repository - so the requesting protocol, host and
+ * port must be verified against the repository base URI (or, for proxy challenges, against the configured
+ * proxy address) before any credential is returned. Legacy unscoped behavior is available as explicit opt-in
+ * via {@link JdkTransporterConfigurationKeys#CONFIG_PROP_UNSCOPED_AUTHENTICATION}.
+ */
+ static final class ScopedAuthenticator extends Authenticator {
+ private final URI baseUri;
+
+ private final InetSocketAddress proxyAddress;
+
+ private final Map<RequestorType, PasswordAuthentication> authentications;
+
+ ScopedAuthenticator(
+ URI baseUri,
+ InetSocketAddress proxyAddress,
+ Map<RequestorType, PasswordAuthentication> authentications) {
+ this.baseUri = Objects.requireNonNull(baseUri);
+ this.proxyAddress = proxyAddress;
+ this.authentications = new HashMap<>(authentications);
+ }
+
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ PasswordAuthentication authentication = authentications.get(getRequestorType());
+ if (authentication == null) {
+ return null;
+ }
+ if (getRequestorType() == RequestorType.PROXY) {
+ if (proxyAddress == null
+ || getRequestingHost() == null
+ || !proxyAddress.getHostString().equalsIgnoreCase(getRequestingHost())
+ || proxyAddress.getPort() != getRequestingPort()) {
+ LOGGER.warn(
+ "Refusing to send proxy credentials to '{}:{}': not the configured proxy '{}'",
+ getRequestingHost(),
+ getRequestingPort(),
+ proxyAddress);
+ return null;
+ }
+ return authentication;
+ }
+ // RequestorType.SERVER: the challenge must originate from the repository itself
+ if (!originMatchesBaseUri(getRequestingProtocol(), getRequestingHost(), getRequestingPort())) {
+ LOGGER.warn(
+ "Refusing to send repository credentials to '{}://{}:{}': it does not match the repository"
+ + " base URI '{}' (a redirect may have left the repository host); set the"
+ + " configuration property {}=true to restore the legacy unscoped behavior",
+ getRequestingProtocol(),
+ getRequestingHost(),
+ getRequestingPort(),
+ baseUri,
+ CONFIG_PROP_UNSCOPED_AUTHENTICATION);
+ return null;
+ }
+ return authentication;
+ }
+
+ private boolean originMatchesBaseUri(String protocol, String host, int port) {
+ if (protocol == null || host == null || baseUri.getScheme() == null || baseUri.getHost() == null) {
+ return false;
+ }
+ return protocol.equalsIgnoreCase(baseUri.getScheme())
+ && host.equalsIgnoreCase(baseUri.getHost())
+ && effectivePort(protocol, port) == effectivePort(baseUri.getScheme(), baseUri.getPort());
+ }
+
+ private static int effectivePort(String protocol, int port) {
+ if (port >= 0) {
+ return port;
+ }
+ return "https".equalsIgnoreCase(protocol) ? 443 : 80;
+ }
+ }
+
private static class RetryLoggingListener implements RetryInterceptor.Listener {
private final int maxNumRetries;
diff --git a/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporterConfigurationKeys.java b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporterConfigurationKeys.java
index bee35ed72..b00ea592d 100644
--- a/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporterConfigurationKeys.java
+++ b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/main/java/org/eclipse/aether/transport/jdk/JdkTransporterConfigurationKeys.java
@@ -60,4 +60,41 @@ public final class JdkTransporterConfigurationKeys {
public static final String CONFIG_PROP_MAX_CONCURRENT_REQUESTS = CONFIG_PROPS_PREFIX + "maxConcurrentRequests";
public static final int DEFAULT_MAX_CONCURRENT_REQUESTS = 100;
+
+ /**
+ * If enabled, restores the legacy behavior where the transporter's {@link java.net.Authenticator} handed out
+ * the repository (or proxy) credentials to any host that issued an authentication challenge - including hosts
+ * reached by following a redirect off the repository. When disabled (the default), credentials are only
+ * returned when the challenging origin (protocol, host and port) matches the repository base URI, or, for
+ * proxy challenges, the configured proxy address.
+ *
+ * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
+ * @configurationType {@link java.lang.Boolean}
+ * @configurationDefaultValue {@link #DEFAULT_UNSCOPED_AUTHENTICATION}
+ * @configurationRepoIdSuffix Yes
+ * @since 2.0.23
+ */
+ public static final String CONFIG_PROP_UNSCOPED_AUTHENTICATION = CONFIG_PROPS_PREFIX + "unscopedAuthentication";
+
+ public static final boolean DEFAULT_UNSCOPED_AUTHENTICATION = false;
+
+ /**
+ * If enabled (default), operator-configured request headers ({@code aether.transport.http.headers}) and
+ * preemptively applied {@code Authorization} are only sent on requests targeting the repository origin (the
+ * scheme, host and port the repository URL denotes). The JDK {@link java.net.http.HttpClient} re-sends all
+ * user-set headers on every redirect hop it follows - including hops that leave the repository origin - so
+ * with this enabled the transporter configures the client with {@code Redirect.NEVER} and follows redirects
+ * itself, dropping those headers on any hop that leaves the origin. Disable only when a redirect target
+ * legitimately requires the configured headers; disabling restores the JDK client's own redirect handling
+ * ({@code Redirect.NORMAL}) and the legacy header replay.
+ *
+ * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
+ * @configurationType {@link java.lang.Boolean}
+ * @configurationDefaultValue {@link #DEFAULT_ORIGIN_SCOPED_HEADERS}
+ * @configurationRepoIdSuffix Yes
+ * @since 2.0.23
+ */
+ public static final String CONFIG_PROP_ORIGIN_SCOPED_HEADERS = CONFIG_PROPS_PREFIX + "originScopedHeaders";
+
+ public static final boolean DEFAULT_ORIGIN_SCOPED_HEADERS = true;
}
diff --git a/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/test/java/org/eclipse/aether/transport/jdk/JdkTransporterRedirectTest.java b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/test/java/org/eclipse/aether/transport/jdk/JdkTransporterRedirectTest.java
new file mode 100644
index 000000000..69b253e3d
--- /dev/null
+++ b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/test/java/org/eclipse/aether/transport/jdk/JdkTransporterRedirectTest.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.jdk;
+
+import java.net.URI;
+import java.net.http.HttpRequest;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * UT for the origin-scoped manual redirect following of {@link JdkTransporter}: configured headers (and
+ * preemptively applied {@code Authorization}) must only ever ride along to the repository origin; a redirect hop
+ * that leaves the origin (cross-host, scheme downgrade or different port) must not carry them. No network is
+ * involved: the hop-request construction and follow decisions are exercised directly.
+ */
+class JdkTransporterRedirectTest {
+ private static final URI BASE_URI = URI.create("https://repo.example.com/maven2/");
+
+ private static Set<String> excludedHeaders() {
+ TreeSet<String> excluded = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+ excluded.add("Authorization");
+ excluded.add("Private-Token");
+ return excluded;
+ }
+
+ private static HttpRequest requestWithConfiguredHeaders() {
+ return HttpRequest.newBuilder()
+ .uri(BASE_URI.resolve("g/a/1.0/a-1.0.jar"))
+ .header("Authorization", "Bearer s3cr3t")
+ .header("Private-Token", "t0ken")
+ .header("Cache-Control", "no-cache, no-store")
+ .GET()
+ .build();
+ }
+
+ @Test
+ void crossHostHopDropsScopedHeaders() {
+ HttpRequest hop = JdkTransporter.redirectRequest(
+ requestWithConfiguredHeaders(),
+ 302,
+ URI.create("https://cdn.example.net/pool/a-1.0.jar"),
+ BASE_URI,
+ excludedHeaders());
+ assertFalse(hop.headers().firstValue("Authorization").isPresent());
+ assertFalse(hop.headers().firstValue("Private-Token").isPresent());
+ // headers not coming from the scoped set are left alone
+ assertTrue(hop.headers().firstValue("Cache-Control").isPresent());
+ assertEquals("GET", hop.method());
+ }
+
+ @Test
+ void schemeDowngradeOrOtherPortHopDropsScopedHeaders() {
+ HttpRequest hop = JdkTransporter.redirectRequest(
+ requestWithConfiguredHeaders(),
+ 302,
+ URI.create("http://repo.example.com/maven2/a-1.0.jar"),
+ BASE_URI,
+ excludedHeaders());
+ assertFalse(hop.headers().firstValue("Authorization").isPresent());
+
+ hop = JdkTransporter.redirectRequest(
+ requestWithConfiguredHeaders(),
+ 302,
+ URI.create("https://repo.example.com:8443/maven2/a-1.0.jar"),
+ BASE_URI,
+ excludedHeaders());
+ assertFalse(hop.headers().firstValue("Authorization").isPresent());
+ }
+
+ @Test
+ void sameOriginHopKeepsAllHeaders() {
+ HttpRequest hop = JdkTransporter.redirectRequest(
+ requestWithConfiguredHeaders(),
+ 302,
+ BASE_URI.resolve("g/a/1.0/a-1.0.jar.moved"),
+ BASE_URI,
+ excludedHeaders());
+ assertEquals("Bearer s3cr3t", hop.headers().firstValue("Authorization").orElse(null));
+ assertEquals("t0ken", hop.headers().firstValue("Private-Token").orElse(null));
+ assertTrue(hop.headers().firstValue("Cache-Control").isPresent());
+ }
+
+ @Test
+ void sameOriginComparisonIsCaseInsensitiveAndPortAware() {
+ HttpRequest hop = JdkTransporter.redirectRequest(
+ requestWithConfiguredHeaders(),
+ 302,
+ URI.create("HTTPS://REPO.EXAMPLE.COM:443/maven2/a-1.0.jar"),
+ BASE_URI,
+ excludedHeaders());
+ assertTrue(hop.headers().firstValue("Authorization").isPresent());
+ }
+
+ @Test
+ void scopedHeaderNameMatchingIsCaseInsensitive() {
+ HttpRequest previous = HttpRequest.newBuilder()
+ .uri(BASE_URI.resolve("a.jar"))
+ .header("AUTHORIZATION", "Bearer s3cr3t")
+ .GET()
+ .build();
+ HttpRequest hop = JdkTransporter.redirectRequest(
+ previous, 302, URI.create("https://cdn.example.net/a.jar"), BASE_URI, excludedHeaders());
+ assertFalse(hop.headers().firstValue("Authorization").isPresent());
+ }
+
+ @Test
+ void seeOtherBecomesGetWhileTemporaryRedirectKeepsMethod() {
+ HttpRequest put = HttpRequest.newBuilder()
+ .uri(BASE_URI.resolve("a.jar"))
+ .PUT(HttpRequest.BodyPublishers.ofString("payload"))
+ .build();
+ assertEquals(
+ "GET",
+ JdkTransporter.redirectRequest(put, 303, BASE_URI.resolve("b.jar"), BASE_URI, excludedHeaders())
+ .method());
+ assertEquals(
+ "PUT",
+ JdkTransporter.redirectRequest(put, 307, BASE_URI.resolve("b.jar"), BASE_URI, excludedHeaders())
+ .method());
+ }
+
+ @Test
+ void followableRedirectResolvesAbsoluteAndRelativeLocations() {
+ URI requestUri = BASE_URI.resolve("g/a/1.0/a-1.0.jar");
+ assertEquals(
+ URI.create("https://cdn.example.net/pool/a-1.0.jar"),
+ JdkTransporter.followableRedirect(302, requestUri, "https://cdn.example.net/pool/a-1.0.jar"));
+ assertEquals(
+ URI.create("https://repo.example.com/maven2/g/a/1.0/other.jar"),
+ JdkTransporter.followableRedirect(301, requestUri, "other.jar"));
+ }
+
+ @Test
+ void nonRedirectsAreNotFollowed() {
+ URI requestUri = BASE_URI.resolve("a.jar");
+ // not a redirect status
+ assertNull(JdkTransporter.followableRedirect(200, requestUri, "https://cdn.example.net/a.jar"));
+ assertNull(JdkTransporter.followableRedirect(404, requestUri, "https://cdn.example.net/a.jar"));
+ // redirect status without Location
+ assertNull(JdkTransporter.followableRedirect(302, requestUri, null));
+ // parity with HttpClient.Redirect.NORMAL: no https -> http downgrade
+ assertNull(JdkTransporter.followableRedirect(302, requestUri, "http://repo.example.com/maven2/a.jar"));
+ // only http(s) targets
+ assertNull(JdkTransporter.followableRedirect(302, requestUri, "ftp://repo.example.com/a.jar"));
+ assertNotNull(JdkTransporter.followableRedirect(308, requestUri, "https://cdn.example.net/a.jar"));
+ }
+
+ @Test
+ void effectivePortFollowsScheme() {
+ assertEquals(443, JdkTransporter.effectivePort("https", -1));
+ assertEquals(80, JdkTransporter.effectivePort("http", -1));
+ assertEquals(8081, JdkTransporter.effectivePort("https", 8081));
+ assertTrue(JdkTransporter.isSameOrigin(
+ URI.create("https://repo.example.com/maven2/"), URI.create("https://repo.example.com:443/other")));
+ assertFalse(JdkTransporter.isSameOrigin(
+ URI.create("https://repo.example.com/maven2/"), URI.create("https://repo.example.com:8443/other")));
+ }
+}
diff --git a/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/test/java/org/eclipse/aether/transport/jdk/ScopedAuthenticatorTest.java b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/test/java/org/eclipse/aether/transport/jdk/ScopedAuthenticatorTest.java
new file mode 100644
index 000000000..82510c9a4
--- /dev/null
+++ b/maven-resolver-transport-jdk-parent/maven-resolver-transport-jdk11/src/test/java/org/eclipse/aether/transport/jdk/ScopedAuthenticatorTest.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.jdk;
+
+import java.net.Authenticator;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * UT for {@link JdkTransporter.ScopedAuthenticator}: repository credentials must only ever be handed out for
+ * challenges originating from the repository base URI itself (and proxy credentials only for the configured
+ * proxy), never for arbitrary hosts reached via redirects.
+ */
+class ScopedAuthenticatorTest {
+ private static JdkTransporter.ScopedAuthenticator authenticator(String baseUri, InetSocketAddress proxy) {
+ Map<Authenticator.RequestorType, PasswordAuthentication> authentications = new HashMap<>();
+ authentications.put(
+ Authenticator.RequestorType.SERVER, new PasswordAuthentication("user", "pass".toCharArray()));
+ authentications.put(
+ Authenticator.RequestorType.PROXY, new PasswordAuthentication("proxyUser", "proxyPass".toCharArray()));
+ return new JdkTransporter.ScopedAuthenticator(URI.create(baseUri), proxy, authentications);
+ }
+
+ private static PasswordAuthentication challenge(
+ Authenticator authenticator, String protocol, String host, int port, Authenticator.RequestorType type) {
+ return authenticator.requestPasswordAuthenticationInstance(
+ host, null, port, protocol, "prompt", "basic", null, type);
+ }
+
+ @Test
+ void serverCredentialsReturnedForRepositoryOrigin() {
+ Authenticator subject = authenticator("https://repo.example.com/maven2/", null);
+
+ PasswordAuthentication authentication =
+ challenge(subject, "https", "repo.example.com", 443, Authenticator.RequestorType.SERVER);
+ assertNotNull(authentication);
+ assertEquals("user", authentication.getUserName());
+
+ // implicit port (JDK may pass -1 when the URI carries no explicit port)
+ assertNotNull(challenge(subject, "https", "repo.example.com", -1, Authenticator.RequestorType.SERVER));
+ // host comparison is case-insensitive
+ assertNotNull(challenge(subject, "HTTPS", "REPO.EXAMPLE.COM", 443, Authenticator.RequestorType.SERVER));
+ }
+
+ @Test
+ void serverCredentialsRefusedForForeignHost() {
+ Authenticator subject = authenticator("https://repo.example.com/maven2/", null);
+
+ assertNull(challenge(subject, "https", "evil.example.org", 443, Authenticator.RequestorType.SERVER));
+ }
+
+ @Test
+ void serverCredentialsRefusedForProtocolDowngrade() {
+ Authenticator subject = authenticator("https://repo.example.com/maven2/", null);
+
+ assertNull(challenge(subject, "http", "repo.example.com", 80, Authenticator.RequestorType.SERVER));
+ assertNull(challenge(subject, "http", "repo.example.com", 443, Authenticator.RequestorType.SERVER));
+ }
+
+ @Test
+ void serverCredentialsRefusedForOtherPort() {
+ Authenticator subject = authenticator("https://repo.example.com/maven2/", null);
+
+ assertNull(challenge(subject, "https", "repo.example.com", 8443, Authenticator.RequestorType.SERVER));
+ }
+
+ @Test
+ void serverCredentialsHonorExplicitBasePort() {
+ Authenticator subject = authenticator("https://repo.example.com:8443/maven2/", null);
+
+ assertNotNull(challenge(subject, "https", "repo.example.com", 8443, Authenticator.RequestorType.SERVER));
+ assertNull(challenge(subject, "https", "repo.example.com", 443, Authenticator.RequestorType.SERVER));
+ assertNull(challenge(subject, "https", "repo.example.com", -1, Authenticator.RequestorType.SERVER));
+ }
+
+ @Test
+ void proxyCredentialsOnlyForConfiguredProxy() {
+ InetSocketAddress proxy = InetSocketAddress.createUnresolved("proxy.example.com", 3128);
+ Authenticator subject = authenticator("https://repo.example.com/maven2/", proxy);
+
+ PasswordAuthentication authentication =
+ challenge(subject, "http", "proxy.example.com", 3128, Authenticator.RequestorType.PROXY);
+ assertNotNull(authentication);
+ assertEquals("proxyUser", authentication.getUserName());
+
+ assertNull(challenge(subject, "http", "other.example.com", 3128, Authenticator.RequestorType.PROXY));
+ assertNull(challenge(subject, "http", "proxy.example.com", 8080, Authenticator.RequestorType.PROXY));
+ }
+
+ @Test
+ void proxyCredentialsRefusedWithoutConfiguredProxy() {
+ Authenticator subject = authenticator("https://repo.example.com/maven2/", null);
+
+ assertNull(challenge(subject, "http", "proxy.example.com", 3128, Authenticator.RequestorType.PROXY));
+ }
+}
diff --git a/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/InsecureRedirectGuard.java b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/InsecureRedirectGuard.java
new file mode 100644
index 000000000..b81f7e246
--- /dev/null
+++ b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/InsecureRedirectGuard.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.jetty;
+
+import java.io.IOException;
+
+import org.eclipse.jetty.client.Request;
+
+/**
+ * A client-level request listener that refuses protocol downgrades for repositories configured with an
+ * {@code https} URL. With redirect following enabled (the default), a compromised or malicious repository can
+ * answer with a {@code Location: http://...} redirect; Jetty follows it with no scheme constraint, stripping
+ * transport encryption from artifact and checksum bytes and making preemptively applied credentials eligible for
+ * transmission over plaintext. Since each Jetty transporter instance is bound to exactly one repository, any
+ * non-https request issued by its client can only be the result of such a redirect, and is aborted before
+ * anything is sent, unless explicitly allowed via
+ * {@link JettyTransporterConfigurationKeys#CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS}.
+ *
+ * @since 2.0.23
+ */
+final class InsecureRedirectGuard implements Request.QueuedListener {
+ @Override
+ public void onQueued(Request request) {
+ if (!"https".equalsIgnoreCase(request.getScheme())) {
+ request.abort(new IOException("Insecure redirect to '" + request.getURI()
+ + "' not followed: protocol downgrade from https to " + request.getScheme()
+ + " would expose credentials and artifact content; set the configuration property "
+ + JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS
+ + "=true to allow it"));
+ }
+ }
+}
diff --git a/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporter.java b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporter.java
index 33801f29c..f2be78483 100644
--- a/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporter.java
+++ b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporter.java
@@ -32,6 +32,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
+import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -521,6 +522,18 @@ final class JettyTransporter extends AbstractTransporter implements HttpTranspor
JettyTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS,
JettyTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS));
+ boolean followInsecureRedirects = ConfigUtils.getBoolean(
+ session,
+ JettyTransporterConfigurationKeys.DEFAULT_FOLLOW_INSECURE_REDIRECTS,
+ JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS + "." + repository.getId(),
+ JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS);
+
+ boolean originScopedHeaders = ConfigUtils.getBoolean(
+ session,
+ JettyTransporterConfigurationKeys.DEFAULT_ORIGIN_SCOPED_HEADERS,
+ JettyTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS + "." + repository.getId(),
+ JettyTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS);
+
httpClient.setUserAgentField(null); // we manage it
if (basicAuthentication != null) {
@@ -557,6 +570,39 @@ final class JettyTransporter extends AbstractTransporter implements HttpTranspor
try {
httpClient.start();
+
+ // Register request listeners after start() so that Jetty's content decoder factories are
+ // fully initialized first.
+ if (!followInsecureRedirects && "https".equalsIgnoreCase(repository.getProtocol())) {
+ // this client serves exactly one repository: any non-https request it ever issues can only be the
+ // result of following a protocol-downgrading redirect, so refuse it before anything is sent
+ httpClient.getRequestListeners().addQueuedListener(new InsecureRedirectGuard());
+ }
+ if (originScopedHeaders) {
+ // Jetty's redirector copies the request headers onto every redirect hop it follows; scope configured
+ // headers (and preemptively applied Authorization) to the repository origin so a cross-origin redirect
+ // does not replay them to the redirect target. The copied redirect request passes through the
+ // client-level request listeners again, same mechanism as the InsecureRedirectGuard above.
+ // Challenge-based authentication from the authentication store is URI-scoped by Jetty already.
+ //
+ // Only register the listener when there are actual credentials or configured headers to protect:
+ // without preemptive authentication or user-configured headers, there is nothing on the request
+ // that could leak to a redirect target, so registering the listener would be a no-op.
+ Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
+ boolean hasPreemptiveAuth = basicAuthentication != null;
+ boolean hasConfiguredHeaders = configuredHeaders != null && !configuredHeaders.isEmpty();
+ if (hasPreemptiveAuth || hasConfiguredHeaders) {
+ TreeSet<String> scopedHeaderNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+ scopedHeaderNames.add(HttpHeader.AUTHORIZATION.asString());
+ if (hasConfiguredHeaders) {
+ scopedHeaderNames.addAll(configuredHeaders.keySet());
+ }
+ httpClient
+ .getRequestListeners()
+ .addHeadersListener(new OriginScopedHeadersListener(baseUri, scopedHeaderNames));
+ }
+ }
+
return httpClient;
} catch (Exception e) {
if (e instanceof RuntimeException) {
diff --git a/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporterConfigurationKeys.java b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporterConfigurationKeys.java
index 9b321ad3e..c017dd940 100644
--- a/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporterConfigurationKeys.java
+++ b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/JettyTransporterConfigurationKeys.java
@@ -55,4 +55,37 @@ public final class JettyTransporterConfigurationKeys {
public static final String CONFIG_PROP_MAX_REDIRECTS = CONFIG_PROPS_PREFIX + "maxRedirects";
public static final int DEFAULT_MAX_REDIRECTS = 5;
+
+ /**
+ * If enabled, Jetty client will follow redirects that downgrade the protocol from https to http. Disabled by
+ * default: such a downgrade strips transport encryption from artifact and checksum bytes and makes repository
+ * credentials eligible for transmission over plaintext, so a downgrading redirect fails the transfer instead.
+ *
+ * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
+ * @configurationType {@link Boolean}
+ * @configurationDefaultValue {@link #DEFAULT_FOLLOW_INSECURE_REDIRECTS}
+ * @configurationRepoIdSuffix Yes
+ * @since 2.0.23
+ */
+ public static final String CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS = CONFIG_PROPS_PREFIX + "followInsecureRedirects";
+
+ public static final boolean DEFAULT_FOLLOW_INSECURE_REDIRECTS = false;
+
+ /**
+ * If enabled (default), operator-configured request headers ({@code aether.transport.http.headers}) and
+ * preemptively applied {@code Authorization} are only sent on requests targeting the repository origin (the
+ * scheme, host and port the repository URL denotes). Jetty's redirector copies the request headers onto every
+ * redirect hop it follows, so without origin scoping a cross-origin redirect replays the configured headers -
+ * which frequently carry credentials such as {@code Authorization} or private token headers - to the redirect
+ * target host. Disable only when a redirect target legitimately requires the configured headers.
+ *
+ * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
+ * @configurationType {@link Boolean}
+ * @configurationDefaultValue {@link #DEFAULT_ORIGIN_SCOPED_HEADERS}
+ * @configurationRepoIdSuffix Yes
+ * @since 2.0.23
+ */
+ public static final String CONFIG_PROP_ORIGIN_SCOPED_HEADERS = CONFIG_PROPS_PREFIX + "originScopedHeaders";
+
+ public static final boolean DEFAULT_ORIGIN_SCOPED_HEADERS = true;
}
diff --git a/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/OriginScopedHeadersListener.java b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/OriginScopedHeadersListener.java
new file mode 100644
index 000000000..7a7c9a90c
--- /dev/null
+++ b/maven-resolver-transport-jetty/src/main/java/org/eclipse/aether/transport/jetty/OriginScopedHeadersListener.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.jetty;
+
+import java.net.URI;
+import java.util.Collection;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.eclipse.jetty.client.Request;
+
+/**
+ * A client-level request headers listener that scopes operator-configured request headers
+ * ({@code aether.transport.http.headers}) and preemptively applied {@code Authorization} to the repository origin.
+ * <p>
+ * Configured headers are stamped on every request the transporter creates and frequently carry credentials
+ * ({@code Authorization}, cookies, private token headers). Jetty's redirector copies the original request headers
+ * onto every redirect hop it follows - including hops that leave the repository origin - which would replay those
+ * credentials to the redirect target host. Since each Jetty transporter instance is bound to exactly one
+ * repository, and copied redirect requests pass through the client-level request listeners again (the same
+ * mechanism {@link InsecureRedirectGuard} relies on), removing the scoped headers from any request whose target is
+ * not the repository origin (same scheme, case-insensitive host and effective port) confines them to the
+ * repository itself. Challenge-based authentication from the authentication store is URI-scoped by Jetty already
+ * and is unaffected. Can be disabled via
+ * {@link JettyTransporterConfigurationKeys#CONFIG_PROP_ORIGIN_SCOPED_HEADERS}.
+ * <p>
+ * Registered as a {@link Request.HeadersListener} rather than a {@link Request.QueuedListener} so that the
+ * callback fires <em>after</em> Jetty's content decoder factories have populated the {@code Accept-Encoding}
+ * header.
+ *
+ * @since 2.0.23
+ */
+final class OriginScopedHeadersListener implements Request.HeadersListener {
+ private final URI origin;
+
+ private final Set<String> scopedHeaderNames;
+
+ OriginScopedHeadersListener(URI origin, Collection<String> scopedHeaderNames) {
+ this.origin = origin;
+ this.scopedHeaderNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+ this.scopedHeaderNames.addAll(scopedHeaderNames);
+ }
+
+ @Override
+ public void onHeaders(Request request) {
+ if (scopedHeaderNames.isEmpty()) {
+ return;
+ }
+ URI target = request.getURI();
+ // fail closed: when the target cannot be determined, do not send the scoped headers
+ if (target == null || !isSameOrigin(origin, target)) {
+ request.headers(headers -> {
+ for (String scopedHeaderName : scopedHeaderNames) {
+ headers.remove(scopedHeaderName);
+ }
+ });
+ }
+ }
+
+ static boolean isSameOrigin(URI origin, URI target) {
+ if (origin.getScheme() == null
+ || origin.getHost() == null
+ || target.getScheme() == null
+ || target.getHost() == null) {
+ return false;
+ }
+ return origin.getScheme().equalsIgnoreCase(target.getScheme())
+ && origin.getHost().equalsIgnoreCase(target.getHost())
+ && effectivePort(origin.getScheme(), origin.getPort())
+ == effectivePort(target.getScheme(), target.getPort());
+ }
+
+ /**
+ * Determines the effective port: the explicit port if present, otherwise the default port implied by the
+ * scheme.
+ */
+ static int effectivePort(String scheme, int port) {
+ if (port >= 0) {
+ return port;
+ }
+ return "https".equalsIgnoreCase(scheme) ? 443 : 80;
+ }
+}
diff --git a/maven-resolver-transport-jetty/src/test/java/org/eclipse/aether/transport/jetty/InsecureRedirectGuardTest.java b/maven-resolver-transport-jetty/src/test/java/org/eclipse/aether/transport/jetty/InsecureRedirectGuardTest.java
new file mode 100644
index 000000000..00425599d
--- /dev/null
+++ b/maven-resolver-transport-jetty/src/test/java/org/eclipse/aether/transport/jetty/InsecureRedirectGuardTest.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.jetty;
+
+import java.io.File;
+
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.Request;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * UT for {@link InsecureRedirectGuard}: for a repository configured with an https URL, a request over plain http
+ * (which can only arise from following a protocol-downgrading redirect) must be aborted before it is sent.
+ */
+class InsecureRedirectGuardTest {
+ private static HttpClient httpClient;
+
+ @BeforeAll
+ static void startClient() throws Exception {
+ // Ensure java.io.tmpdir exists before starting HttpClient. Jetty's HttpClient loads
+ // compression providers (including Brotli) via ServiceLoader during start(). Brotli4j
+ // extracts a native library to a temp file; if the tmpdir does not exist yet (Surefire
+ // sets it to target/surefire-tmp which is deleted by mvn clean), extraction fails and
+ // Brotli is permanently disabled for the JVM lifetime, breaking later compression tests.
+ new File(System.getProperty("java.io.tmpdir")).mkdirs();
+ httpClient = new HttpClient();
+ httpClient.start();
+ }
+
+ @AfterAll
+ static void stopClient() throws Exception {
+ httpClient.stop();
+ }
+
+ @Test
+ void plainHttpRequestIsAborted() {
+ Request request = httpClient.newRequest("http://repo.example.com/g/a/1.0/a-1.0.jar");
+ new InsecureRedirectGuard().onQueued(request);
+ Throwable cause = request.getAbortCause();
+ assertNotNull(cause, "expected the plain http request to be aborted");
+ assertTrue(
+ cause.getMessage().contains(JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS));
+ }
+
+ @Test
+ void httpsRequestIsNotAborted() {
+ Request request = httpClient.newRequest("https://repo.example.com/g/a/1.0/a-1.0.jar");
+ new InsecureRedirectGuard().onQueued(request);
+ assertNull(request.getAbortCause());
+ }
+
+ @Test
+ void httpsRequestToAnotherHostIsNotAborted() {
+ // cross-host redirects that keep https are still followed (parity with the other transports)
+ Request request = httpClient.newRequest("https://mirror.example.org/g/a/1.0/a-1.0.jar");
+ new InsecureRedirectGuard().onQueued(request);
+ assertNull(request.getAbortCause());
+ }
+}
diff --git a/maven-resolver-transport-jetty/src/test/java/org/eclipse/aether/transport/jetty/OriginScopedHeadersListenerTest.java b/maven-resolver-transport-jetty/src/test/java/org/eclipse/aether/transport/jetty/OriginScopedHeadersListenerTest.java
new file mode 100644
index 000000000..ce88e6839
--- /dev/null
+++ b/maven-resolver-transport-jetty/src/test/java/org/eclipse/aether/transport/jetty/OriginScopedHeadersListenerTest.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.eclipse.aether.transport.jetty;
+
+import java.io.File;
+import java.net.URI;
+import java.util.Arrays;
+
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.Request;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * UT for {@link OriginScopedHeadersListener}: configured headers (and preemptively applied {@code Authorization})
+ * must only be sent to the repository origin; any other target - which, on a client bound to one repository, can
+ * only be a redirect hop - must not receive them. Nothing is sent over the wire: the listener is invoked directly
+ * on requests the way the client-level headers listeners would be.
+ */
+class OriginScopedHeadersListenerTest {
+ private static final URI ORIGIN = URI.create("https://repo.example.com/maven2/");
+
+ private static HttpClient httpClient;
+
+ @BeforeAll
+ static void startClient() throws Exception {
+ // Ensure java.io.tmpdir exists before starting HttpClient. Jetty's HttpClient loads
+ // compression providers (including Brotli) via ServiceLoader during start(). Brotli4j
+ // extracts a native library to a temp file; if the tmpdir does not exist yet (Surefire
+ // sets it to target/surefire-tmp which is deleted by mvn clean), extraction fails and
+ // Brotli is permanently disabled for the JVM lifetime, breaking later compression tests.
+ new File(System.getProperty("java.io.tmpdir")).mkdirs();
+ httpClient = new HttpClient();
+ httpClient.start();
+ }
+
+ @AfterAll
+ static void stopClient() throws Exception {
+ httpClient.stop();
+ }
+
+ private static OriginScopedHeadersListener listener() {
+ return new OriginScopedHeadersListener(ORIGIN, Arrays.asList("Authorization", "Private-Token"));
+ }
+
+ private static Request newRequestWithConfiguredHeaders(String uri) {
+ Request request = httpClient.newRequest(uri);
+ request.headers(h -> {
+ h.add("Authorization", "Bearer s3cr3t");
+ h.add("Private-Token", "t0ken");
+ h.add("Accept", "*/*");
+ });
+ return request;
+ }
+
+ private static void assertConfiguredHeadersPresent(Request request) {
+ assertEquals("Bearer s3cr3t", request.getHeaders().get("Authorization"));
+ assertEquals("t0ken", request.getHeaders().get("Private-Token"));
+ assertNotNull(request.getHeaders().get("Accept"));
+ }
+
+ private static void assertConfiguredHeadersStripped(Request request) {
+ assertNull(request.getHeaders().get("Authorization"));
+ assertNull(request.getHeaders().get("Private-Token"));
+ // headers not coming from the scoped set are left alone
+ assertNotNull(request.getHeaders().get("Accept"));
+ }
+
+ @Test
+ void keepsHeadersForOrigin() {
+ Request request = newRequestWithConfiguredHeaders("https://repo.example.com/maven2/g/a/1.0/a-1.0.jar");
+ listener().onHeaders(request);
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void keepsHeadersForOriginWithExplicitDefaultPort() {
+ Request request = newRequestWithConfiguredHeaders("https://repo.example.com:443/maven2/g/a/1.0/a-1.0.jar");
+ listener().onHeaders(request);
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void keepsHeadersForOriginWithDifferentHostCase() {
+ Request request = newRequestWithConfiguredHeaders("https://REPO.Example.COM/maven2/g/a/1.0/a-1.0.jar");
+ listener().onHeaders(request);
+ assertConfiguredHeadersPresent(request);
+ }
+
+ @Test
+ void stripsHeadersForCrossHostRedirectTarget() {
+ Request request = newRequestWithConfiguredHeaders("https://cdn.example.net/pool/a-1.0.jar");
+ listener().onHeaders(request);
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void stripsHeadersForSchemeDowngradeOnSameHost() {
+ Request request = newRequestWithConfiguredHeaders("http://repo.example.com/maven2/a-1.0.jar");
+ listener().onHeaders(request);
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void stripsHeadersForDifferentPortOnSameHost() {
+ Request request = newRequestWithConfiguredHeaders("https://repo.example.com:8443/maven2/a-1.0.jar");
+ listener().onHeaders(request);
+ assertConfiguredHeadersStripped(request);
+ }
+
+ @Test
+ void scopedHeaderNameMatchingIsCaseInsensitive() {
+ OriginScopedHeadersListener subject = new OriginScopedHeadersListener(ORIGIN, Arrays.asList("private-token"));
+ Request request = newRequestWithConfiguredHeaders("https://cdn.example.net/pool/a-1.0.jar");
+ subject.onHeaders(request);
+ assertNull(request.getHeaders().get("Private-Token"));
+ assertNotNull(request.getHeaders().get("Accept"));
+ }
+
+ @Test
+ void effectivePortFollowsScheme() {
+ assertEquals(443, OriginScopedHeadersListener.effectivePort("https", -1));
+ assertEquals(80, OriginScopedHeadersListener.effectivePort("http", -1));
+ assertEquals(8081, OriginScopedHeadersListener.effectivePort("https", 8081));
+ }
+}