This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/maven-4.0.x by this push:
     new 1fa50e4e5e [4.0.x] Complete server repositoryOrigins support: session 
extenders, ApiRunner, settings warnings, core IT (#13837)
1fa50e4e5e is described below

commit 1fa50e4e5e73637084e0b1f8c4231ca375646847
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Fri Nov 6 08:38:52 2026 +0100

    [4.0.x] Complete server repositoryOrigins support: session extenders, 
ApiRunner, settings warnings, core IT (#13837)
---
 .../apache/maven/cling/invoker/LookupInvoker.java  |  14 +-
 .../DefaultRepositorySystemSessionFactory.java     |   7 +-
 .../DefaultRepositorySystemSessionFactoryTest.java |  26 ++
 .../maven/impl/DefaultSettingsValidator.java       |   2 +-
 .../OriginBoundAuthenticationSelector.java         |  35 ++-
 .../apache/maven/impl/standalone/ApiRunner.java    |  57 ++++-
 .../OriginBoundAuthenticationSelectorTest.java     |   2 +-
 .../impl/standalone/ApiRunnerSettingsTest.java     |  39 +++
 .../MavenITgh13265ServerRepositoryOriginsTest.java | 267 +++++++++++++++++++++
 .../it/MavenITmng8379SettingsDecryptTest.java      |   4 +-
 .../project/pom-template.xml                       |  37 +++
 .../project/settings-template.xml                  |  29 +++
 .../repo/.gitattributes                            |   2 +
 .../maven/its/gh13265/parent/1.0/parent-1.0.pom    |  27 +++
 .../its/gh13265/parent/1.0/parent-1.0.pom.sha1     |   1 +
 15 files changed, 516 insertions(+), 33 deletions(-)

diff --git 
a/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
 
b/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
index 478bd0a51b..52eb14ea44 100644
--- 
a/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
+++ 
b/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
@@ -741,12 +741,18 @@ protected Runnable settings(C context, boolean 
emitSettingsWarnings, SettingsBui
             int totalProblems = 
settingsResult.getProblems().totalProblemsReported();
             context.logger.info("");
             context.logger.info(String.format(
-                    "%s %s encountered while building the effective settings 
(use -e to see details)",
+                    "%s %s encountered while building the effective settings",
                     totalProblems, (totalProblems == 1) ? "problem was" : 
"problems were"));
 
-            if (context.options().showErrors().orElse(false)) {
-                for (BuilderProblem problem :
-                        settingsResult.getProblems().problems().toList()) {
+            // print the problems themselves by default, as Maven 3 does: a 
settings element that is skipped (unknown
+            // to this settings model, or misspelt) can change what 
credentials are sent where, and must not go
+            // unnoticed; -e adds the stack trace of the underlying exception
+            boolean showErrors = context.options().showErrors().orElse(false);
+            for (BuilderProblem problem :
+                    settingsResult.getProblems().problems().toList()) {
+                if (showErrors && problem.getException() != null) {
+                    context.logger.warn(problem.getMessage() + " @ " + 
problem.getLocation(), problem.getException());
+                } else {
                     context.logger.warn(problem.getMessage() + " @ " + 
problem.getLocation());
                 }
             }
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
index 49dddabaec..758a2824df 100644
--- 
a/impl/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
@@ -41,6 +41,7 @@
 import org.apache.maven.eventspy.internal.EventSpyDispatcher;
 import org.apache.maven.execution.MavenExecutionRequest;
 import org.apache.maven.impl.resolver.MavenSessionBuilderSupplier;
+import org.apache.maven.impl.resolver.OriginBoundAuthenticationSelector;
 import org.apache.maven.internal.xml.XmlPlexusConfiguration;
 import org.apache.maven.model.ModelBase;
 import org.apache.maven.resolver.RepositorySystemSessionFactory;
@@ -120,7 +121,7 @@ public class DefaultRepositorySystemSessionFactory 
implements RepositorySystemSe
      *
      * @since 4.0.0
      */
-    public static final String MAVEN_REPOSITORY_CREDENTIAL_SCOPE = 
"maven.repository.credentialScope";
+    public static final String MAVEN_REPOSITORY_CREDENTIAL_SCOPE = 
OriginBoundAuthenticationSelector.CREDENTIAL_SCOPE;
 
     private static final String WAGON_TRANSPORTER_PRIORITY_KEY = 
"aether.priority.WagonTransporterFactory";
 
@@ -447,8 +448,10 @@ public SessionBuilder 
newRepositorySessionBuilder(MavenExecutionRequest request)
                     
mergedProps.get(Constants.MAVEN_REPO_LOCAL_TAIL_IGNORE_AVAILABILITY));
         }
 
+        // extenders get the origin-bound selector too, so credentials they 
inject (for example into the legacy
+        // ArtifactRepository objects of the request) are subject to the same 
credential scope as resolver's
         for (RepositorySystemSessionExtender extender : 
sessionExtenders.values()) {
-            extender.extend(request, configProps, mirrorSelector, 
proxySelector, authSelector);
+            extender.extend(request, configProps, mirrorSelector, 
proxySelector, effectiveAuthSelector);
         }
 
         // at this point we have "config" with pure MANDATORY resolver config, 
so resolver final config properties are
diff --git 
a/impl/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
 
b/impl/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
index b790747981..d7537313f0 100644
--- 
a/impl/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
+++ 
b/impl/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
@@ -26,6 +26,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
+import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.maven.artifact.InvalidRepositoryException;
 import org.apache.maven.artifact.repository.ArtifactRepository;
@@ -466,6 +467,31 @@ void malformedServerRepositoryOriginIsIgnored() throws 
InvalidRepositoryExceptio
         assertNull(selector.getAuthentication(repository("internal", 
"https://repo.example.org/releases/";)));
     }
 
+    @Test
+    void sessionExtendersReceiveOriginBoundAuthenticationSelector() throws 
InvalidRepositoryException {
+        MavenExecutionRequest request =
+                requestWithServer(serverWithRepositoryOrigins("internal", 
"https://repo.example.org";));
+        AtomicReference<AuthenticationSelector> captured = new 
AtomicReference<>();
+        RepositorySystemSessionExtender extender =
+                (mavenExecutionRequest, configProperties, mirrorSelector, 
proxySelector, authenticationSelector) ->
+                        captured.set(authenticationSelector);
+        DefaultRepositorySystemSessionFactory systemSessionFactory = new 
DefaultRepositorySystemSessionFactory(
+                aetherRepositorySystem,
+                eventSpyDispatcher,
+                information,
+                defaultTypeRegistry,
+                versionScheme,
+                Map.of("capture", extender),
+                versionFilterBuilder);
+
+        systemSessionFactory.newRepositorySession(request);
+
+        AuthenticationSelector selector = captured.get();
+        assertNotNull(selector);
+        assertNotNull(selector.getAuthentication(repository("internal", 
"https://repo.example.org/releases/";)));
+        assertNull(selector.getAuthentication(repository("internal", 
"https://evil.example.org/releases/";)));
+    }
+
     private static Server serverWithRepositoryOrigins(String id, String... 
repositoryOrigins) {
         Server server = new Server();
         server.setId(id);
diff --git 
a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSettingsValidator.java
 
b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSettingsValidator.java
index a276108421..750533d351 100644
--- 
a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSettingsValidator.java
+++ 
b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSettingsValidator.java
@@ -321,7 +321,7 @@ private static void 
validateRepositoryOrigins(ProblemCollector<BuilderProblem> p
 
     /**
      * Parses a {@code <server><repositoryOrigins>} value the way the 
credential scoping does; see
-     * {@code OriginBoundAuthenticationSelector#originOf(String)} in 
maven-core, which is the authority
+     * {@link 
org.apache.maven.impl.resolver.OriginBoundAuthenticationSelector#originOf(String)},
 which is the authority
      * on what an origin is. Returns {@code null} when the value is not a URI 
at all.
      */
     private static URI parseRepositoryOrigin(String value) {
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/aether/OriginBoundAuthenticationSelector.java
 
b/impl/maven-impl/src/main/java/org/apache/maven/impl/resolver/OriginBoundAuthenticationSelector.java
similarity index 88%
rename from 
impl/maven-core/src/main/java/org/apache/maven/internal/aether/OriginBoundAuthenticationSelector.java
rename to 
impl/maven-impl/src/main/java/org/apache/maven/impl/resolver/OriginBoundAuthenticationSelector.java
index a9f16621af..4b50e6903f 100644
--- 
a/impl/maven-core/src/main/java/org/apache/maven/internal/aether/OriginBoundAuthenticationSelector.java
+++ 
b/impl/maven-impl/src/main/java/org/apache/maven/impl/resolver/OriginBoundAuthenticationSelector.java
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.maven.internal.aether;
+package org.apache.maven.impl.resolver;
 
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -44,25 +44,34 @@
  * previous behaviour unless {@code strict} scope is requested, and a warning 
naming the target origin
  * is emitted once per id/origin pair.
  *
- * @see DefaultRepositorySystemSessionFactory#MAVEN_REPOSITORY_CREDENTIAL_SCOPE
+ * <p>
+ * Used by the Maven CLI session factory and by the standalone API runner, so 
both scope credentials the same way.
+ *
+ * @see #CREDENTIAL_SCOPE
  */
-class OriginBoundAuthenticationSelector implements AuthenticationSelector {
+public final class OriginBoundAuthenticationSelector implements 
AuthenticationSelector {
+    /**
+     * User or system property selecting the credential scope: {@value 
#SCOPE_ORIGIN} (default),
+     * {@value #SCOPE_STRICT} or {@value #SCOPE_ID}.
+     */
+    public static final String CREDENTIAL_SCOPE = 
"maven.repository.credentialScope";
+
     /**
      * Credentials are bound to operator-declared origins; ids without a 
declared origin keep legacy
      * behavior, with a warning.
      */
-    static final String SCOPE_ORIGIN = "origin";
+    public static final String SCOPE_ORIGIN = "origin";
 
     /**
      * Credentials are bound to operator-declared origins; ids without a 
declared origin get no
      * credentials.
      */
-    static final String SCOPE_STRICT = "strict";
+    public static final String SCOPE_STRICT = "strict";
 
     /**
      * Legacy behavior: credentials are matched by server id only.
      */
-    static final String SCOPE_ID = "id";
+    public static final String SCOPE_ID = "id";
 
     private final AuthenticationSelector delegate;
 
@@ -91,7 +100,7 @@ private OriginBoundAuthenticationSelector(
      * @param logger logger used to report id/origin mismatches
      * @return the delegate itself for {@link #SCOPE_ID}, an origin-bound 
wrapper otherwise
      */
-    static AuthenticationSelector wrap(
+    public static AuthenticationSelector wrap(
             AuthenticationSelector delegate,
             String credentialScope,
             Map<String, Set<String>> declaredOrigins,
@@ -103,7 +112,7 @@ static AuthenticationSelector wrap(
                     delegate, declaredOrigins, 
SCOPE_STRICT.equals(credentialScope), logger);
         } else {
             throw new IllegalArgumentException("Unknown value '" + 
credentialScope + "' for "
-                    + 
DefaultRepositorySystemSessionFactory.MAVEN_REPOSITORY_CREDENTIAL_SCOPE
+                    + CREDENTIAL_SCOPE
                     + ". Supported values are: " + SCOPE_ORIGIN + ", " + 
SCOPE_STRICT + ", " + SCOPE_ID);
         }
     }
@@ -112,7 +121,7 @@ static AuthenticationSelector wrap(
      * Records the origin of an operator-declared repository or mirror for the 
given id. URLs without a
      * parseable server authority (for example {@code file:} URLs) are ignored.
      */
-    static void addOrigin(Map<String, Set<String>> declaredOrigins, String id, 
String url) {
+    public static void addOrigin(Map<String, Set<String>> declaredOrigins, 
String id, String url) {
         String origin = originOf(url);
         if (id != null && origin != null) {
             declaredOrigins.computeIfAbsent(id, k -> new 
HashSet<>()).add(origin);
@@ -140,7 +149,7 @@ public Authentication getAuthentication(RemoteRepository 
repository) {
                             + ". Add " + originHint(origin)
                             + " to <repositoryOrigins> of that server in 
settings if these credentials belong"
                             + " there, or set "
-                            + 
DefaultRepositorySystemSessionFactory.MAVEN_REPOSITORY_CREDENTIAL_SCOPE + "="
+                            + CREDENTIAL_SCOPE + "="
                             + SCOPE_ID + " to restore legacy id-only 
credential matching.");
             return null;
         }
@@ -151,7 +160,7 @@ public Authentication getAuthentication(RemoteRepository 
repository) {
                     "Not using credentials of server '" + id + "' for 
repository " + repository.getUrl()
                             + ": no repository or mirror with this id is 
declared in settings or on the command"
                             + " line and the server declares no 
<repositoryOrigins>, and "
-                            + 
DefaultRepositorySystemSessionFactory.MAVEN_REPOSITORY_CREDENTIAL_SCOPE
+                            + CREDENTIAL_SCOPE
                             + "=" + SCOPE_STRICT + " is in effect. Declare " + 
originHint(origin)
                             + " in <repositoryOrigins> of that server in 
settings to allow it.");
             return null;
@@ -165,7 +174,7 @@ public Authentication getAuthentication(RemoteRepository 
repository) {
                         + originHint(origin)
                         + " in <repositoryOrigins> of that server in settings 
to bind these credentials"
                         + " explicitly, or set "
-                        + 
DefaultRepositorySystemSessionFactory.MAVEN_REPOSITORY_CREDENTIAL_SCOPE
+                        + CREDENTIAL_SCOPE
                         + "=" + SCOPE_STRICT + " to refuse such credential 
use.");
         return auth;
     }
@@ -184,7 +193,7 @@ private void warnOnce(String id, String origin, String 
message) {
      * Returns the normalized origin ({@code protocol://host[:port]}, 
lower-cased, default http/https
      * ports elided) of the given URL, or {@code null} if the URL has no 
parseable server authority.
      */
-    static String originOf(String url) {
+    public static String originOf(String url) {
         if (url == null) {
             return null;
         }
diff --git 
a/impl/maven-impl/src/main/java/org/apache/maven/impl/standalone/ApiRunner.java 
b/impl/maven-impl/src/main/java/org/apache/maven/impl/standalone/ApiRunner.java
index 0dec9be967..d11da4172d 100644
--- 
a/impl/maven-impl/src/main/java/org/apache/maven/impl/standalone/ApiRunner.java
+++ 
b/impl/maven-impl/src/main/java/org/apache/maven/impl/standalone/ApiRunner.java
@@ -67,6 +67,7 @@
 import org.apache.maven.api.services.VersionParser;
 import org.apache.maven.api.settings.Mirror;
 import org.apache.maven.api.settings.Proxy;
+import org.apache.maven.api.settings.Repository;
 import org.apache.maven.api.settings.Server;
 import org.apache.maven.api.settings.Settings;
 import org.apache.maven.api.spi.TypeProvider;
@@ -80,6 +81,7 @@
 import org.apache.maven.impl.di.SessionScope;
 import org.apache.maven.impl.model.DefaultInterpolator;
 import org.apache.maven.impl.resolver.MavenSessionBuilderSupplier;
+import org.apache.maven.impl.resolver.OriginBoundAuthenticationSelector;
 import org.apache.maven.impl.resolver.scopes.Maven4ScopeManagerConfiguration;
 import org.codehaus.plexus.components.secdispatcher.Cipher;
 import org.codehaus.plexus.components.secdispatcher.Dispatcher;
@@ -95,12 +97,14 @@
 import org.eclipse.aether.RepositorySystem;
 import org.eclipse.aether.RepositorySystemSession;
 import org.eclipse.aether.internal.impl.scope.ScopeManagerImpl;
+import org.eclipse.aether.repository.AuthenticationSelector;
 import org.eclipse.aether.repository.LocalRepository;
 import org.eclipse.aether.repository.LocalRepositoryManager;
 import org.eclipse.aether.util.repository.AuthenticationBuilder;
 import org.eclipse.aether.util.repository.DefaultAuthenticationSelector;
 import org.eclipse.aether.util.repository.DefaultMirrorSelector;
 import org.eclipse.aether.util.repository.DefaultProxySelector;
+import org.slf4j.LoggerFactory;
 
 /**
  * Provides functionality for running Maven API in a standalone mode.
@@ -625,16 +629,6 @@ static Session newSession(RepositorySystem system, Lookup 
lookup, @Nullable Loca
         }
         rsession.setMirrorSelector(mirrorSelector);
 
-        // Apply server authentication from settings
-        DefaultAuthenticationSelector authSelector = new 
DefaultAuthenticationSelector();
-        for (Server server : settings.getServers()) {
-            AuthenticationBuilder authBuilder = new AuthenticationBuilder();
-            
authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword());
-            authBuilder.addPrivateKey(server.getPrivateKey(), 
server.getPassphrase());
-            authSelector.add(server.getId(), authBuilder.build());
-        }
-        rsession.setAuthenticationSelector(authSelector);
-
         // Build repositories from active profiles in settings
         SettingsBuilder settingsBuilder = 
session.getService(SettingsBuilder.class);
         Profile profile = 
settingsBuilder.convert(org.apache.maven.api.settings.Profile.newBuilder()
@@ -645,11 +639,54 @@ static Session newSession(RepositorySystem system, Lookup 
lookup, @Nullable Loca
         List<RemoteRepository> repositories = 
profile.getRepositories().stream()
                 .map(repositoryFactory::createRemote)
                 .toList();
+
+        rsession.setAuthenticationSelector(authenticationSelector(settings, 
properties, userProperties));
         InternalSession s = (InternalSession) 
session.withRemoteRepositories(repositories);
         InternalSession.associate(rsession, s);
         return s;
     }
 
+    /**
+     * Server credentials from settings, scoped to the origins the operator 
declared for each id (mirrors, settings
+     * repositories and {@code <server><repositoryOrigins>}), as the Maven CLI 
does; see
+     * {@link OriginBoundAuthenticationSelector#CREDENTIAL_SCOPE}. Like the 
repositories {@code ApiRunner} builds, the
+     * origins come from the top-level settings repositories only: a 
repository declared in a settings profile is not
+     * counted, which the CLI does.
+     */
+    private static AuthenticationSelector authenticationSelector(
+            Settings settings, Map<String, String> properties, Map<String, 
String> userProperties) {
+        Map<String, Set<String>> declaredRepositoryOrigins = new HashMap<>();
+        for (Mirror mirror : settings.getMirrors()) {
+            
OriginBoundAuthenticationSelector.addOrigin(declaredRepositoryOrigins, 
mirror.getId(), mirror.getUrl());
+        }
+        for (Repository repository : settings.getRepositories()) {
+            OriginBoundAuthenticationSelector.addOrigin(
+                    declaredRepositoryOrigins, repository.getId(), 
repository.getUrl());
+        }
+        for (Repository repository : settings.getPluginRepositories()) {
+            OriginBoundAuthenticationSelector.addOrigin(
+                    declaredRepositoryOrigins, repository.getId(), 
repository.getUrl());
+        }
+        DefaultAuthenticationSelector authSelector = new 
DefaultAuthenticationSelector();
+        for (Server server : settings.getServers()) {
+            AuthenticationBuilder authBuilder = new AuthenticationBuilder();
+            
authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword());
+            authBuilder.addPrivateKey(server.getPrivateKey(), 
server.getPassphrase());
+            authSelector.add(server.getId(), authBuilder.build());
+            for (String repositoryOrigin : server.getRepositoryOrigins()) {
+                OriginBoundAuthenticationSelector.addOrigin(
+                        declaredRepositoryOrigins, server.getId(), 
repositoryOrigin);
+            }
+        }
+        String credentialScope = userProperties.getOrDefault(
+                OriginBoundAuthenticationSelector.CREDENTIAL_SCOPE,
+                properties.getOrDefault(
+                        OriginBoundAuthenticationSelector.CREDENTIAL_SCOPE,
+                        OriginBoundAuthenticationSelector.SCOPE_ORIGIN));
+        return OriginBoundAuthenticationSelector.wrap(
+                authSelector, credentialScope, declaredRepositoryOrigins, 
LoggerFactory.getLogger(ApiRunner.class));
+    }
+
     /**
      * Resolves the Maven configuration directory following the same lookup 
order as the Maven CLI:
      * {@code maven.installation.conf} → {@code maven.conf} → {@code 
${maven.home}/conf} → {@code ${MAVEN_HOME}/conf}.
diff --git 
a/impl/maven-core/src/test/java/org/apache/maven/internal/aether/OriginBoundAuthenticationSelectorTest.java
 
b/impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/OriginBoundAuthenticationSelectorTest.java
similarity index 99%
rename from 
impl/maven-core/src/test/java/org/apache/maven/internal/aether/OriginBoundAuthenticationSelectorTest.java
rename to 
impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/OriginBoundAuthenticationSelectorTest.java
index 794213ab17..fd5103e444 100644
--- 
a/impl/maven-core/src/test/java/org/apache/maven/internal/aether/OriginBoundAuthenticationSelectorTest.java
+++ 
b/impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/OriginBoundAuthenticationSelectorTest.java
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.maven.internal.aether;
+package org.apache.maven.impl.resolver;
 
 import java.util.HashMap;
 import java.util.Map;
diff --git 
a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/ApiRunnerSettingsTest.java
 
b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/ApiRunnerSettingsTest.java
index d4748e0bcc..e858b9894c 100644
--- 
a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/ApiRunnerSettingsTest.java
+++ 
b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/ApiRunnerSettingsTest.java
@@ -33,6 +33,9 @@
 import org.apache.maven.di.Key;
 import org.apache.maven.di.impl.Binding;
 import org.apache.maven.di.impl.InjectorImpl;
+import org.apache.maven.impl.InternalSession;
+import org.eclipse.aether.repository.AuthenticationSelector;
+import org.eclipse.aether.repository.RemoteRepository;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -40,6 +43,7 @@
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
@@ -180,6 +184,41 @@ void testSettingsServersApplied() throws IOException {
         }
     }
 
+    @Test
+    void testServerCredentialsBoundToRepositoryOrigins() throws IOException {
+        Path m2Dir = tempDir.resolve(".m2");
+        Files.createDirectories(m2Dir);
+        Files.writeString(m2Dir.resolve("settings.xml"), """
+                <?xml version="1.0" encoding="UTF-8"?>
+                <settings xmlns="http://maven.apache.org/SETTINGS/1.3.0";>
+                  <servers>
+                    <server>
+                      <id>my-repo</id>
+                      <username>myuser</username>
+                      <password>mypassword</password>
+                      <repositoryOrigins>
+                        
<repositoryOrigin>https://repo.example.org</repositoryOrigin>
+                      </repositoryOrigins>
+                    </server>
+                  </servers>
+                </settings>
+                """);
+
+        String oldHome = System.getProperty("user.home");
+        try {
+            System.setProperty("user.home", tempDir.toString());
+            Session session = ApiRunner.createSession(null, null, 
ApiRunner.SecurityMode.NONE);
+            AuthenticationSelector selector =
+                    ((InternalSession) 
session).getSession().getAuthenticationSelector();
+            assertNotNull(selector.getAuthentication(
+                    new RemoteRepository.Builder("my-repo", "default", 
"https://repo.example.org/releases/";).build()));
+            assertNull(selector.getAuthentication(
+                    new RemoteRepository.Builder("my-repo", "default", 
"https://evil.example.org/releases/";).build()));
+        } finally {
+            System.setProperty("user.home", oldHome);
+        }
+    }
+
     @Test
     void testSettingsMirrorsApplied() throws IOException {
         Path m2Dir = tempDir.resolve(".m2");
diff --git 
a/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh13265ServerRepositoryOriginsTest.java
 
b/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh13265ServerRepositoryOriginsTest.java
new file mode 100644
index 0000000000..d5c56f8c70
--- /dev/null
+++ 
b/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh13265ServerRepositoryOriginsTest.java
@@ -0,0 +1,267 @@
+/*
+ * 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.apache.maven.it;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jetty.security.Constraint;
+import org.eclipse.jetty.security.HashLoginService;
+import org.eclipse.jetty.security.SecurityHandler;
+import org.eclipse.jetty.security.UserStore;
+import org.eclipse.jetty.security.authentication.BasicAuthenticator;
+import org.eclipse.jetty.server.Handler;
+import org.eclipse.jetty.server.NetworkConnector;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.handler.DefaultHandler;
+import org.eclipse.jetty.server.handler.ResourceHandler;
+import org.eclipse.jetty.util.resource.ResourceFactory;
+import org.eclipse.jetty.util.security.Password;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Credentials of a {@code <server>} in settings are sent only to the origins 
the operator declared for its id:
+ * the repositories and mirrors with that id in settings or on the command 
line, and the server's own
+ * {@code <repositoryOrigins>}. See <a 
href="https://github.com/apache/maven/issues/13265";>GH-13265</a>.
+ * <p>
+ * Two password-protected repositories serve the same parent POM, on two ports 
of {@code localhost} and so on two
+ * origins. The project declares a repository with the server's id at one of 
them; whether the build can resolve
+ * the parent shows whether the credentials were sent.
+ */
+class MavenITgh13265ServerRepositoryOriginsTest extends 
AbstractMavenIntegrationTestCase {
+
+    private static final String GROUP_ID = "org.apache.maven.its.gh13265";
+
+    private File testDir;
+
+    private Server declaredServer;
+
+    private Server otherServer;
+
+    MavenITgh13265ServerRepositoryOriginsTest() {
+        // <repositoryOrigins> reached the 4.0.x line after 4.0.0-rc-7 was 
tagged
+        super("[4.0.0-rc-8,)");
+    }
+
+    @BeforeEach
+    void setUp() throws Exception {
+        testDir = extractResources("/gh-13265-repository-origins");
+        declaredServer = startRepository(new File(testDir, "repo"));
+        otherServer = startRepository(new File(testDir, "repo"));
+    }
+
+    @AfterEach
+    void tearDown() throws Exception {
+        for (Server server : new Server[] {declaredServer, otherServer}) {
+            if (server != null) {
+                server.stop();
+                server.join();
+            }
+        }
+    }
+
+    /**
+     * The repository is at the origin the server declares: credentials are 
sent.
+     */
+    @Test
+    void credentialsSentToDeclaredOrigin() throws Exception {
+        Verifier verifier = build("declared", originsOf(declaredServer), 
url(declaredServer), null);
+        verifier.execute();
+        verifier.verifyErrorFreeLog();
+        verifier.verifyTextNotInLog("Not using credentials of server 
'it-repo'");
+    }
+
+    /**
+     * {@code strict} scope still serves a declared origin. 4.0.0-rc-7 refused 
it because it did not read
+     * {@code <repositoryOrigins>}.
+     */
+    @Test
+    void credentialsSentToDeclaredOriginInStrictScope() throws Exception {
+        Verifier verifier = build("declared-strict", 
originsOf(declaredServer), url(declaredServer), "strict");
+        verifier.execute();
+        verifier.verifyErrorFreeLog();
+        verifier.verifyTextNotInLog("Not using credentials of server 
'it-repo'");
+    }
+
+    /**
+     * The repository has the server's id but is at another origin: the 
credentials are not sent. This is the
+     * property the feature exists for.
+     */
+    @Test
+    void credentialsNotSentToOtherOrigin() throws Exception {
+        Verifier verifier = build("other", originsOf(declaredServer), 
url(otherServer), null);
+        assertThrows(VerificationException.class, verifier::execute);
+        verifier.verifyTextInLog("Not using credentials of server 'it-repo' 
for repository " + url(otherServer));
+        verifier.verifyTextInLog("the origins declared for this id are");
+    }
+
+    @Test
+    void credentialsNotSentToOtherOriginInStrictScope() throws Exception {
+        Verifier verifier = build("other-strict", originsOf(declaredServer), 
url(otherServer), "strict");
+        assertThrows(VerificationException.class, verifier::execute);
+        verifier.verifyTextInLog("Not using credentials of server 'it-repo' 
for repository " + url(otherServer));
+    }
+
+    /**
+     * Without {@code <repositoryOrigins>} and with no repository or mirror of 
that id in settings, the default
+     * {@code origin} scope keeps the id-only behaviour of earlier Maven 
versions, with a warning.
+     */
+    @Test
+    void credentialsSentWithWarningWithoutDeclaredOrigins() throws Exception {
+        Verifier verifier = build("undeclared", "", url(otherServer), null);
+        verifier.execute();
+        verifier.verifyErrorFreeLog();
+        verifier.verifyTextInLog("Using credentials of server 'it-repo' for 
repository " + url(otherServer)
+                + ", although no repository or mirror with this id is 
declared");
+    }
+
+    @Test
+    void credentialsNotSentWithoutDeclaredOriginsInStrictScope() throws 
Exception {
+        Verifier verifier = build("undeclared-strict", "", url(otherServer), 
"strict");
+        assertThrows(VerificationException.class, verifier::execute);
+        verifier.verifyTextInLog("no repository or mirror with this id is 
declared in settings");
+    }
+
+    /**
+     * A server alias inherits the origins of the server it is declared on.
+     */
+    @Test
+    void aliasInheritsDeclaredOrigins() throws Exception {
+        String extra = "      <aliases><alias>it-alias</alias></aliases>\n" + 
originsOf(declaredServer);
+        Verifier declared = build("alias-declared", extra, 
url(declaredServer), "strict", "it-alias");
+        declared.execute();
+        declared.verifyErrorFreeLog();
+
+        Verifier other = build("alias-other", extra, url(otherServer), 
"strict", "it-alias");
+        assertThrows(VerificationException.class, other::execute);
+        other.verifyTextInLog("Not using credentials of server 'it-alias' for 
repository " + url(otherServer));
+    }
+
+    /**
+     * A settings element the model does not know is skipped; Maven says so at 
WARNING without {@code -e}, and keeps
+     * the stack trace for {@code -e}.
+     */
+    @Test
+    void unknownServerElementIsReportedWithoutErrorsSwitch() throws Exception {
+        String extra = "      <repositoryOrigin>" + origin(declaredServer) + 
"</repositoryOrigin>";
+        Verifier verifier = build("unknown-element", extra, 
url(declaredServer), null, "it-repo", false);
+        verifier.execute();
+        verifier.verifyTextInLog("[WARNING] Unable to read settings: 
Unrecognised tag: ");
+        verifier.verifyTextInLog("repositoryOrigin' @ ");
+        verifier.verifyTextNotInLog("at 
org.apache.maven.impl.XmlSettingsParser.parse");
+    }
+
+    private Verifier build(String name, String serverExtra, String 
repositoryUrl, String credentialScope)
+            throws Exception {
+        return build(name, serverExtra, repositoryUrl, credentialScope, 
"it-repo");
+    }
+
+    private Verifier build(
+            String name, String serverExtra, String repositoryUrl, String 
credentialScope, String repositoryId)
+            throws Exception {
+        return build(name, serverExtra, repositoryUrl, credentialScope, 
repositoryId, true);
+    }
+
+    private Verifier build(
+            String name,
+            String serverExtra,
+            String repositoryUrl,
+            String credentialScope,
+            String repositoryId,
+            boolean showErrors)
+            throws Exception {
+        Map<String, String> filterProps = new HashMap<>();
+        filterProps.put("@serverExtra@", serverExtra);
+        filterProps.put("@repositoryId@", repositoryId);
+        filterProps.put("@repositoryUrl@", repositoryUrl);
+
+        Verifier verifier;
+        if (showErrors) {
+            verifier = newVerifier(new File(testDir, 
"project").getAbsolutePath());
+        } else {
+            // the default arguments include --errors; keep only --batch-mode 
and the suite's install settings
+            verifier = new Verifier(new File(testDir, 
"project").getAbsolutePath(), List.of("--batch-mode"));
+            String settingsDir = 
System.getProperty("maven.it.global-settings.dir", "");
+            File installSettings = settingsDir.isEmpty()
+                    ? new File("target/test-classes/settings-remote.xml")
+                    : new File(settingsDir, "settings-remote.xml");
+            verifier.addCliArgument("--install-settings");
+            verifier.addCliArgument(installSettings.getAbsolutePath());
+        }
+        verifier.setAutoclean(false);
+        verifier.setLogFileName("log-" + name + ".txt");
+        verifier.deleteArtifacts(GROUP_ID);
+        verifier.filterFile("settings-template.xml", "settings-" + name + 
".xml", filterProps);
+        verifier.filterFile("pom-template.xml", "pom.xml", filterProps);
+        verifier.addCliArgument("--settings");
+        verifier.addCliArgument("settings-" + name + ".xml");
+        if (credentialScope != null) {
+            verifier.addCliArgument("-Dmaven.repository.credentialScope=" + 
credentialScope);
+        }
+        verifier.addCliArgument("validate");
+        return verifier;
+    }
+
+    private static String originsOf(Server server) {
+        return "      <repositoryOrigins>\n        <repositoryOrigin>" + 
origin(server)
+                + "</repositoryOrigin>\n      </repositoryOrigins>";
+    }
+
+    private static String origin(Server server) {
+        return "http://localhost:"; + ((NetworkConnector) 
server.getConnectors()[0]).getLocalPort();
+    }
+
+    private static String url(Server server) {
+        return origin(server) + "/repo";
+    }
+
+    private static Server startRepository(File repoDir) throws Exception {
+        HashLoginService userRealm = new HashLoginService("TestRealm");
+        UserStore userStore = new UserStore();
+        userStore.addUser("testuser", new Password("testtest"), new String[] 
{"user"});
+        userRealm.setUserStore(userStore);
+
+        Server server = new Server(0);
+        SecurityHandler.PathMapped securityHandler = new 
SecurityHandler.PathMapped();
+        securityHandler.setLoginService(userRealm);
+        securityHandler.setAuthenticator(new BasicAuthenticator());
+        securityHandler.put("/*", Constraint.from("auth", 
Constraint.Authorization.SPECIFIC_ROLE, "user"));
+
+        ResourceHandler repoHandler = new ResourceHandler();
+        
repoHandler.setBaseResource(ResourceFactory.of(server).newResource(repoDir.getParentFile().toPath()));
+
+        Handler.Sequence handlerList = new Handler.Sequence();
+        handlerList.addHandler(repoHandler);
+        handlerList.addHandler(new DefaultHandler());
+
+        securityHandler.setHandler(handlerList);
+        server.setHandler(securityHandler);
+        server.start();
+        if (server.isFailed()) {
+            throw new IllegalStateException("Couldn't bind the server socket 
to a free port");
+        }
+        return server;
+    }
+}
diff --git 
a/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8379SettingsDecryptTest.java
 
b/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8379SettingsDecryptTest.java
index c00c2b382c..f7bb148cf3 100644
--- 
a/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8379SettingsDecryptTest.java
+++ 
b/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8379SettingsDecryptTest.java
@@ -47,7 +47,7 @@ void testLegacy() throws Exception {
         verifier.verifyErrorFreeLog();
 
         // there is a warning and all fields decrypted
-        verifier.verifyTextInLog(" encountered while building the effective 
settings (use -e to see details)");
+        verifier.verifyTextInLog(" encountered while building the effective 
settings");
         verifier.verifyTextInLog("<password>testtest</password>");
         verifier.verifyTextInLog("<value>testtest</value>");
     }
@@ -70,7 +70,7 @@ void testModern() throws Exception {
 
         // there is no warning and all fields decrypted
         verifier.verifyTextNotInLog("[WARNING]");
-        verifier.verifyTextNotInLog(" encountered while building the effective 
settings (use -e to see details)");
+        verifier.verifyTextNotInLog(" encountered while building the effective 
settings");
         verifier.verifyTextInLog("<password>testtest</password>");
         verifier.verifyTextInLog("<value>secretHeader</value>");
     }
diff --git 
a/its/core-it-suite/src/test/resources/gh-13265-repository-origins/project/pom-template.xml
 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/project/pom-template.xml
new file mode 100644
index 0000000000..4267b7ffa8
--- /dev/null
+++ 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/project/pom-template.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0";>
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.apache.maven.its.gh13265</groupId>
+    <artifactId>parent</artifactId>
+    <version>1.0</version>
+    <relativePath/>
+  </parent>
+  <artifactId>test</artifactId>
+  <name>Maven Integration Test :: GH-13265</name>
+  <description>Resolves its parent from a repository declared in this POM with 
the id of a server in settings.</description>
+  <repositories>
+    <repository>
+      <id>@repositoryId@</id>
+      <url>@repositoryUrl@</url>
+    </repository>
+  </repositories>
+</project>
diff --git 
a/its/core-it-suite/src/test/resources/gh-13265-repository-origins/project/settings-template.xml
 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/project/settings-template.xml
new file mode 100644
index 0000000000..5dce7b6c3e
--- /dev/null
+++ 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/project/settings-template.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<settings xmlns="http://maven.apache.org/SETTINGS/1.3.0";>
+  <servers>
+    <server>
+      <id>it-repo</id>
+      <username>testuser</username>
+      <password>testtest</password>
+@serverExtra@
+    </server>
+  </servers>
+</settings>
diff --git 
a/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/.gitattributes
 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/.gitattributes
new file mode 100644
index 0000000000..6d6420ce59
--- /dev/null
+++ 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/.gitattributes
@@ -0,0 +1,2 @@
+*.pom    text eol=lf
+maven-metadata.xml    text eol=lf
diff --git 
a/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/org/apache/maven/its/gh13265/parent/1.0/parent-1.0.pom
 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/org/apache/maven/its/gh13265/parent/1.0/parent-1.0.pom
new file mode 100644
index 0000000000..444c8c505c
--- /dev/null
+++ 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/org/apache/maven/its/gh13265/parent/1.0/parent-1.0.pom
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0";>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.maven.its.gh13265</groupId>
+  <artifactId>parent</artifactId>
+  <version>1.0</version>
+  <packaging>pom</packaging>
+  <name>Parent served only by the password-protected test repository</name>
+</project>
diff --git 
a/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/org/apache/maven/its/gh13265/parent/1.0/parent-1.0.pom.sha1
 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/org/apache/maven/its/gh13265/parent/1.0/parent-1.0.pom.sha1
new file mode 100644
index 0000000000..066e81feb2
--- /dev/null
+++ 
b/its/core-it-suite/src/test/resources/gh-13265-repository-origins/repo/org/apache/maven/its/gh13265/parent/1.0/parent-1.0.pom.sha1
@@ -0,0 +1 @@
+97069626af972a664614f7a5f1f0b61d0b447cce
\ No newline at end of file

Reply via email to