This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch maven-3.9.x
in repository https://gitbox.apache.org/repos/asf/maven.git
The following commit(s) were added to refs/heads/maven-3.9.x by this push:
new df0ec49309 [maven-3.9.x] Explain an unusable master password and warn
about passwords left encrypted (#14096)
df0ec49309 is described below
commit df0ec49309e27a9f020d467ca152bab7ce8dfa79
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Fri Nov 27 11:10:06 2026 +0200
[maven-3.9.x] Explain an unusable master password and warn about passwords
left encrypted (#14096)
* 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 | 83 ++++++++++++++++++++++
4 files changed, 233 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 35737ac84c..45c769a50a 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
@@ -29,6 +29,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;
@@ -153,6 +154,13 @@ public class DefaultRepositorySystemSessionFactory {
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;
@@ -179,6 +187,20 @@ public class DefaultRepositorySystemSessionFactory {
@Inject
private RuntimeInformation runtimeInformation;
+ /**
+ * 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");
+ }
+ }
+
@SuppressWarnings("checkstyle:methodlength")
public DefaultRepositorySystemSession
newRepositorySession(MavenExecutionRequest request) {
DefaultRepositorySystemSession session =
MavenRepositorySystemUtils.newSession();
@@ -233,6 +255,22 @@ public DefaultRepositorySystemSession
newRepositorySession(MavenExecutionRequest
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());
+ }
// origins of the repositories and mirrors the operator declared for a
given server id, completed
// below with the origins declared on the servers themselves, used to
scope that id's credentials
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 8e4b2e6d31..1a3d9f492c 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;
@@ -32,6 +33,7 @@
import org.apache.maven.execution.MavenExecutionRequest;
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;
@@ -40,6 +42,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
@@ -115,6 +120,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 06cdde727b..7fb8d11545 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
@@ -119,8 +119,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;
@@ -158,6 +160,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";
+
public static final String STYLE_COLOR_PROPERTY = "style.color";
private ClassWorld classWorld;
@@ -898,12 +902,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("~")) {
@@ -912,25 +910,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 4077b9651c..4d79ff80fe 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
@@ -40,10 +40,13 @@
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;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -102,6 +105,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()));
+ }
+
@Test
public void testCalculateDegreeOfConcurrency() {
assertThrows(IllegalArgumentException.class, () ->
cli.calculateDegreeOfConcurrency("0"));