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

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


The following commit(s) were added to refs/heads/maven-3.10.x by this push:
     new fabeaeb454 [maven-3.10.x] Explain an unusable master password and warn 
about passwords left encrypted (#14095)
fabeaeb454 is described below

commit fabeaeb454f0ba47bf99709fb490e97920265910
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Fri Nov 27 11:09:55 2026 +0200

    [maven-3.10.x] Explain an unusable master password and warn about passwords 
left encrypted (#14095)
    
    * Explain how to fix an unusable master password in --encrypt-password
    
    A missing settings-security.xml, or a <master> value that is not the
    output of --encrypt-master-password, surfaced as a bare
    FileNotFoundException, BadPaddingException or
    ArrayIndexOutOfBoundsException. The cipher failure is kept as a
    suppressed exception so that only -e prints it.
    
    * Warn when an encrypted server or proxy password is not decrypted
    
    The value was sent to the server as written, with the failure visible only 
at debug level. The warning is limited to values shaped like --encrypt-password 
output: decryption also fails for any plain value with braces in it, such as an 
unresolved ${env.X}, and those work as they are.
---
 .../DefaultRepositorySystemSessionFactory.java     | 38 ++++++++++
 .../DefaultRepositorySystemSessionFactoryTest.java | 61 ++++++++++++++++
 .../main/java/org/apache/maven/cli/MavenCli.java   | 66 ++++++++++++++----
 .../java/org/apache/maven/cli/MavenCliTest.java    | 81 ++++++++++++++++++++++
 4 files changed, 231 insertions(+), 15 deletions(-)

diff --git 
a/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
 
b/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
index 78c32f23e0..fec0621540 100644
--- 
a/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
+++ 
b/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java
@@ -31,6 +31,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 import org.apache.maven.RepositoryUtils;
@@ -185,6 +186,13 @@ public class DefaultRepositorySystemSessionFactory 
implements RepositorySystemSe
 
     private static final String RESOLVER_MAX_PRIORITY = 
String.valueOf(Float.MAX_VALUE);
 
+    /**
+     * The shape of {@code mvn --encrypt-password} output: Base64 text in 
braces. With plexus-cipher 2.0 the
+     * shortest output, for a one character password, has 44 Base64 
characters; check this bound when the cipher
+     * changes, as a longer minimum is harmless and a shorter one would 
silence the warning.
+     */
+    private static final Pattern ENCRYPTED_PASSWORD = 
Pattern.compile("\\{[A-Za-z0-9+/]{34,}={0,2}\\}");
+
     @Inject
     private Logger logger;
 
@@ -216,6 +224,20 @@ public class DefaultRepositorySystemSessionFactory 
implements RepositorySystemSe
 
     private final GenericVersionScheme versionScheme = new 
GenericVersionScheme();
 
+    /**
+     * Warns when a value that has the shape of a Maven encrypted password was 
not decrypted, as it is then
+     * sent to the server as it is written in the settings. Decryption is 
attempted, and fails, for every value
+     * with braces in it, such as <code>${env.TOKEN}</code> or a password that 
contains them: those stay silent.
+     */
+    static void warnIfNotDecrypted(Logger logger, String what, String 
configured, String decrypted) {
+        if (configured != null
+                && configured.equals(decrypted)
+                && ENCRYPTED_PASSWORD.matcher(configured).find()) {
+            logger.warn("Could not decrypt the " + what
+                    + ", using it as written in the settings; run with -X for 
the cause");
+        }
+    }
+
     /**
      * For legacy consumers; hopefully nobody.
      */
@@ -292,6 +314,22 @@ public RepositorySystemSession.SessionBuilder 
newRepositorySessionBuilder(MavenE
                 logger.debug(problem.getMessage(), problem.getException());
             }
         }
+        for (int i = 0; i < request.getServers().size(); i++) {
+            Server server = request.getServers().get(i);
+            Server result = decrypted.getServers().get(i);
+            warnIfNotDecrypted(
+                    logger, "password of server " + server.getId(), 
server.getPassword(), result.getPassword());
+            warnIfNotDecrypted(
+                    logger, "passphrase of server " + server.getId(), 
server.getPassphrase(), result.getPassphrase());
+        }
+        for (int i = 0; i < request.getProxies().size(); i++) {
+            Proxy proxy = request.getProxies().get(i);
+            warnIfNotDecrypted(
+                    logger,
+                    "password of proxy " + proxy.getId(),
+                    proxy.getPassword(),
+                    decrypted.getProxies().get(i).getPassword());
+        }
 
         versionFilterBuilder
                 .buildVersionFilter((String) 
configProps.get(MAVEN_VERSION_FILTER), this::parseVersionConstraint)
diff --git 
a/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
 
b/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
index 7bb8601c16..3ca317d0fb 100644
--- 
a/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
+++ 
b/maven-core/src/test/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactoryTest.java
@@ -21,6 +21,7 @@
 import javax.inject.Inject;
 
 import java.io.File;
+import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -33,6 +34,7 @@
 import org.apache.maven.internal.RepositorySystemSessionFactory;
 import org.apache.maven.settings.Mirror;
 import org.apache.maven.settings.Server;
+import org.codehaus.plexus.logging.Logger;
 import org.codehaus.plexus.testing.PlexusTest;
 import org.eclipse.aether.repository.AuthenticationSelector;
 import org.eclipse.aether.repository.RemoteRepository;
@@ -41,6 +43,9 @@
 import static org.codehaus.plexus.testing.PlexusExtension.getBasedir;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
 
 /**
  * UT for {@link DefaultRepositorySystemSessionFactory}, focused on how server 
credentials are scoped
@@ -116,6 +121,62 @@ void malformedServerRepositoryOriginIsIgnored() throws 
Exception {
         assertNull(selector.getAuthentication(repository("internal", 
"https://repo.example.org/releases/";)));
     }
 
+    @Test
+    void sessionWarnsAboutEncryptedServerPasswordThatCannotBeDecrypted() 
throws Exception {
+        Logger logger = mock(Logger.class);
+        Field loggerField = 
DefaultRepositorySystemSessionFactory.class.getDeclaredField("logger");
+        loggerField.setAccessible(true);
+        Object originalLogger = loggerField.get(systemSessionFactory);
+        String originalSecurityFile = System.getProperty("settings.security");
+        Server server = serverWithRepositoryOrigins("internal");
+        server.setPassword("{ZQHnV2v+3uIHFAJOvC3lR5UwUrt286ghwSlMVyZecU8=}");
+        try {
+            // no settings security file, so nothing can be decrypted, 
whatever the user home holds
+            System.setProperty("settings.security", new File(getBasedir(), 
"target/no-such-file.xml").getPath());
+            loggerField.set(systemSessionFactory, logger);
+
+            authenticationSelector(requestWithServer(server));
+        } finally {
+            loggerField.set(systemSessionFactory, originalLogger);
+            if (originalSecurityFile == null) {
+                System.clearProperty("settings.security");
+            } else {
+                System.setProperty("settings.security", originalSecurityFile);
+            }
+        }
+
+        verify(logger)
+                .warn("Could not decrypt the password of server internal, 
using it as written in the settings;"
+                        + " run with -X for the cause");
+    }
+
+    @Test
+    void encryptedPasswordLeftUndecryptedIsWarnedAbout() {
+        Logger logger = mock(Logger.class);
+        String encrypted = "{ZQHnV2v+3uIHFAJOvC3lR5UwUrt286ghwSlMVyZecU8=}";
+
+        DefaultRepositorySystemSessionFactory.warnIfNotDecrypted(
+                logger, "password of server internal", encrypted, encrypted);
+
+        verify(logger)
+                .warn("Could not decrypt the password of server internal, 
using it as written in the settings;"
+                        + " run with -X for the cause");
+    }
+
+    @Test
+    void decryptedOrPlainValuesAreNotWarnedAbout() {
+        Logger logger = mock(Logger.class);
+
+        DefaultRepositorySystemSessionFactory.warnIfNotDecrypted(
+                logger, "password of server internal", 
"{ZQHnV2v+3uIHFAJOvC3lR5UwUrt286ghwSlMVyZecU8=}", "secret");
+        for (String plain : new String[] {null, "abc123", "${env.TOKEN}", 
"{DESede}y+qq4Cg==", "a{b}c"}) {
+            DefaultRepositorySystemSessionFactory.warnIfNotDecrypted(
+                    logger, "password of server internal", plain, plain);
+        }
+
+        verifyNoInteractions(logger);
+    }
+
     private static Properties strictCredentialScope() {
         Properties properties = new Properties();
         properties.put(
diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java 
b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
index ac2790cc20..7d327b97e4 100644
--- a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
+++ b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
@@ -122,8 +122,10 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
+import org.sonatype.plexus.components.cipher.PlexusCipherException;
 import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
 import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
+import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException;
 import org.sonatype.plexus.components.sec.dispatcher.SecUtil;
 import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity;
 
@@ -162,6 +164,8 @@ public class MavenCli {
 
     private static final String MVN_MAVEN_CONFIG = DOT_MVN + "/maven.config";
 
+    private static final String ENCRYPTION_GUIDE = 
"https://maven.apache.org/guides/mini/guide-encryption.html";;
+
     /**
      * One "distinguished" env variable that we want to make into non-prefixed 
property, if present.
      *
@@ -1011,12 +1015,6 @@ private void encryption(CliRequest cliRequest) throws 
Exception {
 
             throw new ExitException(0);
         } else if 
(cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_PASSWORD)) {
-            String passwd = 
cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_PASSWORD);
-
-            if (passwd == null) {
-                passwd = readPassword(System.console(), System.in, "Password: 
");
-            }
-
             String configurationFile = dispatcher.getConfigurationFile();
 
             if (configurationFile.startsWith("~")) {
@@ -1025,25 +1023,63 @@ private void encryption(CliRequest cliRequest) throws 
Exception {
 
             String file = 
System.getProperty(DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, 
configurationFile);
 
-            String master = null;
+            // check the master password before asking for the password to 
encrypt
+            DefaultPlexusCipher cipher = new DefaultPlexusCipher();
+            String masterPasswd = readMasterPassword(cipher, file);
 
-            SettingsSecurity sec = SecUtil.read(file, true);
-            if (sec != null) {
-                master = sec.getMaster();
-            }
+            String passwd = 
cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_PASSWORD);
 
-            if (master == null) {
-                throw new IllegalStateException("Master password is not set in 
the setting security file: " + file);
+            if (passwd == null) {
+                passwd = readPassword(System.console(), System.in, "Password: 
");
             }
 
-            DefaultPlexusCipher cipher = new DefaultPlexusCipher();
-            String masterPasswd = cipher.decryptDecorated(master, 
DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION);
             System.out.println(cipher.encryptAndDecorate(passwd, 
masterPasswd));
 
             throw new ExitException(0);
         }
     }
 
+    /**
+     * Reads and decrypts the master password, turning every way the settings 
security file can be wrong into a
+     * message that names the file and the way out.
+     */
+    static String readMasterPassword(DefaultPlexusCipher cipher, String file) {
+        // the location may also be a URL, which only SecUtil can tell is 
missing
+        if (!file.contains("://") && !new File(file).exists()) {
+            throw new IllegalStateException("The settings security file " + 
file + " does not exist. Create a master"
+                    + " password with 'mvn --encrypt-master-password' and 
store it in that file first, see "
+                    + ENCRYPTION_GUIDE);
+        }
+
+        SettingsSecurity sec;
+        try {
+            sec = SecUtil.read(file, true);
+        } catch (SecDispatcherException e) {
+            throw new IllegalStateException("Cannot read the settings security 
file " + file, e);
+        }
+
+        String master = sec.getMaster();
+        if (master == null || master.trim().isEmpty()) {
+            throw new IllegalStateException("Master password is not set in the 
settings security file " + file
+                    + ". Create one with 'mvn --encrypt-master-password', see 
" + ENCRYPTION_GUIDE);
+        }
+
+        try {
+            return cipher.decryptDecorated(master, 
DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION);
+        } catch (PlexusCipherException e) {
+            // A value that is not the output of --encrypt-master-password 
fails inside the cipher, which wraps a
+            // BadPaddingException or an ArrayIndexOutOfBoundsException. 
Neither says anything to the user, so it is
+            // kept as suppressed: -e still prints it, the default output does 
not.
+            IllegalStateException failure =
+                    new IllegalStateException("Cannot decrypt the master 
password in the settings security file "
+                            + file + ". The <master> value must be the output 
of 'mvn --encrypt-master-password':"
+                            + " create it again, then encrypt again the 
passwords that used the old one, see "
+                            + ENCRYPTION_GUIDE);
+            failure.addSuppressed(e);
+            throw failure;
+        }
+    }
+
     private int execute(CliRequest cliRequest) throws 
MavenExecutionRequestPopulationException {
         MavenExecutionRequest request = 
executionRequestPopulator.populateDefaults(cliRequest.request);
         request.setRepositoryCache(new DefaultRepositoryCache()); // reset 
caches
diff --git 
a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java 
b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
index 78edda36a9..3c9007cc28 100644
--- a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
+++ b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
@@ -47,6 +47,7 @@
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 import org.mockito.InOrder;
+import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
 
 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -113,6 +114,86 @@ public void testReadPasswordRejectsMissingPassword() {
                         null, new 
ByteArrayInputStream("\n".getBytes(StandardCharsets.UTF_8)), "Password: "));
     }
 
+    @Test
+    public void testReadMasterPassword(@TempDir Path tempDir) throws Exception 
{
+        DefaultPlexusCipher cipher = new DefaultPlexusCipher();
+        Path file = settingsSecurity(tempDir, 
cipher.encryptAndDecorate("master", "settings.security"));
+
+        assertEquals("master", MavenCli.readMasterPassword(cipher, 
file.toString()));
+        // the location may be a URL as well as a path
+        assertEquals(
+                "master",
+                MavenCli.readMasterPassword(cipher, "file://" + 
file.toUri().getPath()));
+    }
+
+    @Test
+    public void testReadMasterPasswordRejectsMissingFile(@TempDir Path 
tempDir) throws Exception {
+        Path file = tempDir.resolve("settings-security.xml");
+
+        String message = masterPasswordFailure(file).getMessage();
+
+        assertTrue(message.contains(file + " does not exist"), message);
+        assertTrue(message.contains("--encrypt-master-password"), message);
+    }
+
+    @Test
+    public void testReadMasterPasswordRejectsUnparsableFile(@TempDir Path 
tempDir) throws Exception {
+        Path file = tempDir.resolve("settings-security.xml");
+        Files.write(file, "not xml".getBytes(StandardCharsets.UTF_8));
+
+        IllegalStateException e = masterPasswordFailure(file);
+
+        assertTrue(e.getMessage().contains("Cannot read the settings security 
file " + file), e.getMessage());
+        assertNotNull(e.getCause());
+    }
+
+    @Test
+    public void testReadMasterPasswordRejectsMissingMaster(@TempDir Path 
tempDir) throws Exception {
+        Path file = tempDir.resolve("settings-security.xml");
+        Files.write(file, 
"<settingsSecurity/>".getBytes(StandardCharsets.UTF_8));
+
+        String message = masterPasswordFailure(file).getMessage();
+
+        assertTrue(message.contains("Master password is not set in the 
settings security file " + file), message);
+    }
+
+    /**
+     * A master password that the built-in key does not decrypt used to 
surface as a {@code BadPaddingException} or an
+     * {@code ArrayIndexOutOfBoundsException} from the cipher, with no hint at 
the file or the fix.
+     */
+    @Test
+    public void testReadMasterPasswordRejectsUndecryptableMaster(@TempDir Path 
tempDir) throws Exception {
+        DefaultPlexusCipher cipher = new DefaultPlexusCipher();
+        String[] masters = {
+            // a server password, encrypted with a master password instead of 
the built-in key
+            cipher.encryptAndDecorate("secret", "master"), 
"plain-text-master", "{not base64 !!}"
+        };
+
+        for (String master : masters) {
+            Path file = settingsSecurity(tempDir, master);
+
+            IllegalStateException e = masterPasswordFailure(file);
+
+            assertTrue(e.getMessage().contains("Cannot decrypt the master 
password"), e.getMessage());
+            assertTrue(e.getMessage().contains(file.toString()), 
e.getMessage());
+            assertTrue(e.getMessage().contains("--encrypt-master-password"), 
e.getMessage());
+            assertNull(e.getCause(), "the cipher failure must not reach the 
default output");
+            assertEquals(1, e.getSuppressed().length);
+        }
+    }
+
+    private static Path settingsSecurity(Path dir, String master) throws 
IOException {
+        Path file = dir.resolve("settings-security.xml");
+        String xml = "<settingsSecurity><master>" + master + 
"</master></settingsSecurity>";
+        return Files.write(file, xml.getBytes(StandardCharsets.UTF_8));
+    }
+
+    private static IllegalStateException masterPasswordFailure(Path file) {
+        return assertThrows(
+                IllegalStateException.class,
+                () -> MavenCli.readMasterPassword(new DefaultPlexusCipher(), 
file.toString()));
+    }
+
     /**
      * An empty or otherwise unparsable extensions descriptor should fail with 
a message naming the file, not a bare
      * {@code EOFException} from the XML parser (MNG-8369).

Reply via email to