From 0af6285cffb4b86365085e584ae1ab24b6366ca1 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Sat, 28 Nov 2026 09:50:06 +0000
Subject: [PATCH] [#487] Suggest a truststore path and read its PIN in dsreplication (#1336)

---
 opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java         |   94 +++++++++++++++++++----
 opendj-server-legacy/src/test/java/org/opends/server/util/cli/LDAPConnectionConsoleInteractionTestCase.java |  135 +++++++++++++++++++++++++++++++++
 opendj-server-legacy/src/messages/org/opends/messages/tool.properties                                       |    1 
 3 files changed, 211 insertions(+), 19 deletions(-)

diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java b/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
index ad08625..3adf948 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
@@ -21,10 +21,13 @@
 
 import static org.opends.messages.ToolMessages.*;
 
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.security.KeyStore;
@@ -1510,41 +1513,96 @@
 
   private void trustCertificatePermanently(final X509Certificate[] chain) throws Exception
   {
+    final String defaultPath = getWritableTrustStorePath();
+    final LocalizableMessage prompt = defaultPath == null ? INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH.get()
+        : INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH_DEFAULT.get(defaultPath);
+    final ValidationCallback<String> validatePath = filePathValidationCallback(!ALLOW_EMPTY_PATH, !FILE_MUST_EXISTS);
     app.println();
-    final String trustStorePath = app.readValidatedInput(
-        INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH.get(),
-        filePathValidationCallback(!ALLOW_EMPTY_PATH, !FILE_MUST_EXISTS));
+    final String path = app.readValidatedInput(prompt, (console, input) ->
+        defaultPath != null && input.trim().isEmpty() ? defaultPath : validatePath.validate(console, input));
+    final File trustStore = new File(path);
 
-    // Read the password from the stdin.
-    final String trustStorePasswordStr = readPassword(
-        INFO_LDAP_CONN_PROMPT_SECURITY_KEYSTORE_PASSWORD.get(trustStorePath));
     final KeyStore keyStore = KeyStore.getInstance("JKS");
-    final char[] trustStorePassword = trustStorePasswordStr.toCharArray();
-    loadKeyStoreFromFile(keyStore, trustStorePath, trustStorePassword);
-
+    final char[] password = loadTrustStoreForUpdate(keyStore, trustStore);
     for (final X509Certificate cert : chain)
     {
       keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
     }
 
-    try (final FileOutputStream trustStoreOutputFile = new FileOutputStream(trustStorePath))
+    try (FileOutputStream output = new FileOutputStream(trustStore))
     {
-      keyStore.store(trustStoreOutputFile, trustStorePassword);
+      keyStore.store(output, password);
     }
   }
 
-  private void loadKeyStoreFromFile(
-      final KeyStore keyStore, final String trustStorePath, final char[] trustStorePassword) throws Exception
+  private String getWritableTrustStorePath()
   {
-      try (FileInputStream inputStream = new FileInputStream(trustStorePath))
+    if (state.truststorePath == null)
+    {
+      return null;
+    }
+    final File file = new File(state.truststorePath);
+    return file.isFile() && file.canRead() && file.canWrite() ? state.truststorePath : null;
+  }
+
+  private char[] loadTrustStoreForUpdate(KeyStore keyStore, File trustStore) throws Exception
+  {
+    final char[] password;
+    if (state.truststorePassword != null && state.truststorePath != null
+        && trustStore.getCanonicalFile().equals(new File(state.truststorePath).getCanonicalFile()))
+    {
+      password = state.truststorePassword.toCharArray();
+    }
+    else
+    {
+      final char[] pin = readTrustStorePin(trustStore);
+      if (pin != null)
       {
-        keyStore.load(inputStream, trustStorePassword);
+        try
+        {
+          loadKeyStoreFromFile(keyStore, trustStore, pin);
+          return pin;
+        }
+        catch (IOException ignored)
+        {
+          // The optional PIN was rejected. Let the user enter the password.
+        }
       }
-      catch (FileNotFoundException ignored)
+      password = readPassword(INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PASSWORD.get(trustStore)).toCharArray();
+    }
+    loadKeyStoreFromFile(keyStore, trustStore, password);
+    return password;
+  }
+
+  private char[] readTrustStorePin(File trustStore)
+  {
+    final File pinFile = new File(trustStore.getPath() + ".pin");
+    if (pinFile.isFile())
+    {
+      try (BufferedReader reader = new BufferedReader(new FileReader(pinFile)))
       {
-        // create empty keystore
-        keyStore.load(null, trustStorePassword);
+        final String pin = reader.readLine();
+        return pin != null ? pin.toCharArray() : null;
       }
+      catch (IOException ignored)
+      {
+        // Fall back to the console if the optional PIN file cannot be read.
+      }
+    }
+    return null;
+  }
+
+  private void loadKeyStoreFromFile(KeyStore keyStore, File trustStore, char[] password) throws Exception
+  {
+    try (FileInputStream input = new FileInputStream(trustStore))
+    {
+      keyStore.load(input, password);
+    }
+    catch (FileNotFoundException ignored)
+    {
+      // Create an empty keystore.
+      keyStore.load(null, password);
+    }
   }
 
   /**
diff --git a/opendj-server-legacy/src/messages/org/opends/messages/tool.properties b/opendj-server-legacy/src/messages/org/opends/messages/tool.properties
index 9eb82ba..388f69d 100644
--- a/opendj-server-legacy/src/messages/org/opends/messages/tool.properties
+++ b/opendj-server-legacy/src/messages/org/opends/messages/tool.properties
@@ -2644,6 +2644,7 @@
 INFO_LDAP_CONN_PROMPT_SECURITY_USE_START_TLS=LDAP with StartTLS
 INFO_LDAP_CONN_PROMPT_SECURITY_USE_TRUST_ALL=Automatically trust
 INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH=Truststore path:
+INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH_DEFAULT=Truststore path [%s]:
 INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PASSWORD=Password for truststore '%s':
 INFO_LDAP_CONN_PROMPT_SECURITY_KEYSTORE_PATH=Keystore path:
 INFO_LDAP_CONN_PROMPT_SECURITY_KEYSTORE_PASSWORD=Password for keystore '%s':
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/util/cli/LDAPConnectionConsoleInteractionTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/util/cli/LDAPConnectionConsoleInteractionTestCase.java
index 5a4fef5..101e172 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/util/cli/LDAPConnectionConsoleInteractionTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/util/cli/LDAPConnectionConsoleInteractionTestCase.java
@@ -15,15 +15,37 @@
  */
 package org.opends.server.util.cli;
 
+import static com.forgerock.opendj.cli.Utils.MAX_LINE_WIDTH;
+import static com.forgerock.opendj.cli.Utils.wrapText;
+
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.opends.messages.ToolMessages.INFO_CERTIFICATE_NAME_MISMATCH_TEXT_CLI;
 import static org.opends.messages.ToolMessages.INFO_CERTIFICATE_NOT_TRUSTED_TEXT_CLI;
+import static org.opends.messages.ToolMessages.INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PASSWORD;
+import static org.opends.server.TestCaseUtils.getTestResource;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.security.cert.X509Certificate;
+
+import org.forgerock.i18n.LocalizableMessageBuilder;
 import org.opends.admin.ads.util.ApplicationTrustManager;
 import org.opends.server.DirectoryServerTestCase;
+import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
+import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
-/** Tests the message shown when the certificate presented by a server is rejected. */
+import com.forgerock.opendj.cli.ConsoleApplication;
+import com.forgerock.opendj.cli.FileBasedArgument;
+
+/** Tests the console interaction when the certificate presented by a server is rejected. */
 @SuppressWarnings("javadoc")
 public class LDAPConnectionConsoleInteractionTestCase extends DirectoryServerTestCase
 {
@@ -52,6 +74,117 @@
         .isNotEqualTo(rejectionMessage(ApplicationTrustManager.Cause.HOST_NAME_MISMATCH));
   }
 
+  @DataProvider
+  public Object[][] trustStorePasswords()
+  {
+    return new Object[][] {
+        { "JKS", "password\nignored\n", false, "", true },
+        { "JKS", "stale\n", false, "password\n", true },
+        { "JKS", null, false, "password\n", true },
+        { "JKS", "stale\n", true, "", true },
+        { "PKCS12", "\uFEFFpassword\n", false, "password\n", true },
+        { "PKCS12", "\uFEFFpassword\n", false, "wrong-password\n", false }
+    };
+  }
+
+  @Test(dataProvider = "trustStorePasswords")
+  public void testSavingCertificateToSuggestedTrustStore(String storeType, String pinContents,
+      boolean explicitPasswordFile, String passwordInput, boolean shouldPersist) throws Exception
+  {
+    final Path directory = Files.createTempDirectory("cli-trust-");
+    final Path trustStore = directory.resolve("admin-truststore");
+    final Path pin = directory.resolve("admin-truststore.pin");
+    final Path passwordFile = directory.resolve("cli-password");
+    final char[] password = "password".toCharArray();
+    try
+    {
+      final KeyStore store = KeyStore.getInstance(storeType);
+      store.load(null, password);
+      try (OutputStream output = Files.newOutputStream(trustStore))
+      {
+        store.store(output, password);
+      }
+      final byte[] originalContents = Files.readAllBytes(trustStore);
+      if (pinContents != null)
+      {
+        Files.writeString(pin, pinContents);
+      }
+
+      final SecureConnectionCliArgs args = new SecureConnectionCliArgs(true);
+      args.createGlobalArguments();
+      args.getTrustStorePathArg().addValue(trustStore.toString());
+      if (explicitPasswordFile)
+      {
+        Files.writeString(passwordFile, "password\n");
+        args.getTrustStorePathArg().setPresent(true);
+        final FileBasedArgument fileArg = args.getTrustStorePasswordFileArg();
+        assertThat(fileArg.valueIsAcceptable(passwordFile.toString(), new LocalizableMessageBuilder()))
+            .isTrue();
+        fileArg.addValue(passwordFile.toString());
+        fileArg.setPresent(true);
+      }
+
+      final X509Certificate certificate = loadServerCertificate();
+      final String input = (explicitPasswordFile ? "" : "3\n") + "3\n\n" + passwordInput;
+      final ByteArrayOutputStream output = new ByteArrayOutputStream();
+      final ConsoleApplication app = createConsole(input, output);
+      assertThat(new LDAPConnectionConsoleInteraction(app, args)
+          .checkServerCertificate(new X509Certificate[] { certificate }, "RSA", HOST)).isTrue();
+
+      final String transcript = output.toString(StandardCharsets.UTF_8);
+      assertThat(transcript).contains("[" + trustStore + "]");
+      if (!passwordInput.isEmpty())
+      {
+        assertThat(transcript).contains(wrapText(
+            INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PASSWORD.get(trustStore.toFile()), MAX_LINE_WIDTH));
+      }
+      if (shouldPersist)
+      {
+        try (InputStream saved = Files.newInputStream(trustStore))
+        {
+          store.load(saved, password);
+        }
+        assertThat(store.getCertificate(certificate.getSubjectX500Principal().getName())).isEqualTo(certificate);
+      }
+      else
+      {
+        assertThat(Files.readAllBytes(trustStore)).isEqualTo(originalContents);
+      }
+    }
+    finally
+    {
+      Files.deleteIfExists(passwordFile);
+      Files.deleteIfExists(pin);
+      Files.deleteIfExists(trustStore);
+      Files.delete(directory);
+    }
+  }
+
+  private static X509Certificate loadServerCertificate() throws Exception
+  {
+    final KeyStore fixture = KeyStore.getInstance("JKS");
+    try (InputStream input = Files.newInputStream(getTestResource("server.keystore").toPath()))
+    {
+      fixture.load(input, "password".toCharArray());
+    }
+    return (X509Certificate) fixture.getCertificate("server-cert");
+  }
+
+  private static ConsoleApplication createConsole(String input, ByteArrayOutputStream output)
+  {
+    final InputStream stdin = System.in;
+    final PrintStream printStream = new PrintStream(output, false, StandardCharsets.UTF_8);
+    try
+    {
+      System.setIn(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)));
+      return new ConsoleApplication(printStream, printStream) { };
+    }
+    finally
+    {
+      System.setIn(stdin);
+    }
+  }
+
   private static String rejectionMessage(ApplicationTrustManager.Cause cause)
   {
     return LDAPConnectionConsoleInteraction.getCertificateRejectionMessage(cause, HOST, PORT).toString();

--
Gitblit v1.10.0