From d361f42f2fccf7b6f4e23691d0a40f17969e2ec1 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Sat, 28 Nov 2026 09:48:43 +0000
Subject: [PATCH] [#278] Publish missing ADS instance certificates after replication starts (#1338)

---
 opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java                          |   59 ++++++++++++++
 opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java                      |   53 +++++++++++-
 opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationDomain.java         |    2 
 opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerSync.java                      |   27 +++++-
 opendj-server-legacy/src/test/java/org/opends/server/replication/InstanceKeyStartupReplicationTest.java |   94 +++++++++++++++++++++++
 5 files changed, 222 insertions(+), 13 deletions(-)

diff --git a/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java b/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
index a3a453d..78f2c36 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
@@ -58,6 +58,7 @@
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import javax.management.MBeanServer;
@@ -796,6 +797,7 @@
       checkSubsystemIsInitialized(SubSystem.INIT_CRYPTO);
       checkSubsystemIsInitialized(SubSystem.ADMIN_USERS);
       new CryptoManagerSync();
+      CryptoManagerSync.publishInstanceKeyEntryInADS(false);
     }
 
     private void setupAdminBackends() throws InitializationException
@@ -1531,6 +1533,9 @@
 
       workQueue = new WorkQueueConfigManager(serverContext).initializeWorkQueue();
 
+      // The ADS replication domain can now record the ADD of a missing instance key.
+      final boolean instanceKeyPublished = CryptoManagerSync.publishInstanceKeyEntryInADS(false);
+
       PluginResult.Startup startupPluginResult = pluginConfigManager.invokeStartupPlugins();
       if (! startupPluginResult.continueProcessing())
       {
@@ -1581,6 +1586,42 @@
       deleteUnnecessaryFiles();
 
       isRunning = true;
+      if (!instanceKeyPublished)
+      {
+        scheduleInstanceKeyPublication();
+      }
+    }
+  }
+
+  private void scheduleInstanceKeyPublication()
+  {
+    synchronized (LIFECYCLE_LOCK)
+    {
+      if (!shuttingDown)
+      {
+        cronExecutorService.schedule(this::retryInstanceKeyPublication, 1, TimeUnit.SECONDS);
+      }
+    }
+  }
+
+  private void retryInstanceKeyPublication()
+  {
+    if (!shuttingDown)
+    {
+      try
+      {
+        if (!CryptoManagerSync.publishInstanceKeyEntryInADS(true))
+        {
+          scheduleInstanceKeyPublication();
+        }
+      }
+      catch (InitializationException e)
+      {
+        if (!shuttingDown)
+        {
+          logger.error(e.getMessageObject());
+        }
+      }
     }
   }
 
@@ -4150,6 +4191,11 @@
     ServerShutdownMonitor shutdownMonitor = new ServerShutdownMonitor();
     shutdownMonitor.start();
 
+    if (directoryServer.cronExecutorService != null)
+    {
+      directoryServer.cronExecutorService.shutdownNow();
+    }
+
     // Release connection-handler threads that are waiting for queue space.
     if (directoryServer.workQueue != null)
     {
@@ -4182,6 +4228,19 @@
       provider.finalizeSynchronizationProvider();
     }
 
+    // Replication shutdown releases an in-flight certificate publication before backend shutdown.
+    if (directoryServer.cronExecutorService != null)
+    {
+      try
+      {
+        directoryServer.cronExecutorService.awaitTermination(ServerShutdownMonitor.WAIT_TIME, TimeUnit.MILLISECONDS);
+      }
+      catch (InterruptedException e)
+      {
+        Thread.currentThread().interrupt();
+      }
+    }
+
     // Call the shutdown plugins, and then finalize all the plugins defined in
     // the server.
     if (directoryServer.pluginConfigManager != null)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java b/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
index 9c85361..38cb6a4 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
@@ -101,6 +101,9 @@
 import org.opends.server.protocols.ldap.ExtendedResponseProtocolOp;
 import org.opends.server.protocols.ldap.LDAPMessage;
 import org.opends.server.protocols.ldap.LDAPResultCode;
+import org.opends.server.replication.common.ServerStatus;
+import org.opends.server.replication.plugin.LDAPReplicationDomain;
+import org.opends.server.replication.plugin.MultimasterReplication;
 import org.opends.server.tools.LDAPConnection;
 import org.opends.server.tools.LDAPConnectionOptions;
 import org.opends.server.tools.LDAPReader;
@@ -123,6 +126,7 @@
 import org.opends.server.util.StaticUtils;
 
 import static org.opends.messages.CoreMessages.*;
+import static org.opends.messages.ReplicationMessages.ERR_REPLICATION_COULD_NOT_CONNECT;
 import static org.opends.server.config.ConfigConstants.*;
 import static org.opends.server.protocols.internal.InternalClientConnection.*;
 import static org.opends.server.protocols.internal.Requests.*;
@@ -753,8 +757,20 @@
    @throws CryptoManagerException In case there is a problem
    searching for the entry, or, if necessary, adding it.
    */
-  static void publishInstanceKeyEntryInADS()
-          throws CryptoManagerException {
+  static void publishInstanceKeyEntryInADS() throws CryptoManagerException
+  {
+    publishInstanceKeyEntryInADS(false);
+  }
+
+  /**
+   * Publishes a missing instance key through a usable replication session, if ADS is replicated.
+   *
+   * @param requireReplication whether to wait for an ADS replication domain to be enabled
+   * @return true if the entry exists or was created, or false if publication must wait
+   * @throws CryptoManagerException if the lookup or publication failed
+   */
+  static boolean publishInstanceKeyEntryInADS(boolean requireReplication) throws CryptoManagerException
+  {
     final byte[] instanceKeyCertificate = getInstanceKeyCertificateFromLocalTruststore();
     final String instanceKeyID = getInstanceKeyID(instanceKeyCertificate);
     // Construct the key entry DN.
@@ -770,6 +786,12 @@
           newSearchRequest(entryDN, SearchScope.BASE_OBJECT, FILTER_OC_INSTANCE_KEY).addAttribute("dn");
       final InternalSearchOperation searchOp = icc.processSearch(request);
       if (searchOp.getSearchEntries().isEmpty()) {
+        final LDAPReplicationDomain domain = MultimasterReplication.findDomain(entryDN, null);
+        if (domain == null ? requireReplication : !canPublishInstanceKey(domain))
+        {
+          return false;
+        }
+
         final Entry entry = new Entry(entryDN, null, null, null);
         entry.addObjectClass(CoreSchema.getTopObjectClass());
         entry.addObjectClass(ocInstanceKey);
@@ -785,11 +807,21 @@
         final Attribute certificateAttr = builder.toAttribute();
         entry.addAttribute(certificateAttr);
 
-        AddOperation addOperation = icc.processAdd(entry);
-        if (ResultCode.SUCCESS != addOperation.getResultCode()) {
-          throw new DirectoryException(
-                  addOperation.getResultCode(),
-                  ERR_CRYPTOMGR_FAILED_TO_ADD_INSTANCE_KEY_ENTRY_TO_ADS.get(entry.getName()));
+        final AddOperation add = icc.processAdd(entry);
+        final ResultCode result = add.getResultCode();
+        // Replication may have added the entry while we were preparing the ADD.
+        if (result == ResultCode.ENTRY_ALREADY_EXISTS && !icc.processSearch(request).getSearchEntries().isEmpty()) {
+          return true;
+        }
+        // The session can be lost between the readiness check and the ADD.
+        if (result == ResultCode.UNWILLING_TO_PERFORM && domain != null
+            && ERR_REPLICATION_COULD_NOT_CONNECT.get(domain.getBaseDN()).toString()
+                .contentEquals(add.getErrorMessage()))
+        {
+          return false;
+        }
+        if (result != ResultCode.SUCCESS) {
+          throw new DirectoryException(result, ERR_CRYPTOMGR_FAILED_TO_ADD_INSTANCE_KEY_ENTRY_TO_ADS.get(entryDN));
         }
       }
     } catch (DirectoryException ex) {
@@ -798,6 +830,13 @@
               ERR_CRYPTOMGR_FAILED_TO_PUBLISH_INSTANCE_KEY_ENTRY.get(
                       getExceptionMessage(ex)), ex);
     }
+    return true;
+  }
+
+  private static boolean canPublishInstanceKey(LDAPReplicationDomain domain)
+  {
+    final ServerStatus status = domain.getStatus();
+    return domain.isConnected() && (status == ServerStatus.NORMAL_STATUS || status == ServerStatus.DEGRADED_STATUS);
   }
 
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerSync.java b/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerSync.java
index fe8d421..7cc96b5 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerSync.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerSync.java
@@ -110,11 +110,9 @@
   private final ObjectClass ocMacKey;
 
   /**
-   * Creates a new instance of this trust store synchronization thread.
+   * Initializes the local instance certificate and loads certificates and secret keys from ADS.
    *
-   * @throws InitializationException in case an exception occurs during
-   * initialization, such as a failure to publish the instance-key-pair
-   * public-key-certificate in ADS.
+   * @throws InitializationException if the local instance certificate cannot be initialized
    */
   public CryptoManagerSync() throws InitializationException
   {
@@ -126,7 +124,7 @@
         POST_RESPONSE_ADD, POST_RESPONSE_MODIFY, POST_RESPONSE_DELETE),
         true);
     try {
-      CryptoManagerImpl.publishInstanceKeyEntryInADS();
+      CryptoManagerImpl.getInstanceKeyCertificateFromLocalTruststore();
     }
     catch (CryptoManagerException ex) {
       throw new InitializationException(ex.getMessageObject());
@@ -167,6 +165,25 @@
     DirectoryServer.registerInternalPlugin(this);
   }
 
+  /**
+   * Publishes the local instance certificate in ADS if its entry is missing.
+   *
+   * @param requireReplication whether to wait for an ADS replication domain to be enabled
+   * @return true if the entry exists or was created, or false if publication must wait
+   * @throws InitializationException if the entry cannot be published
+   */
+  public static boolean publishInstanceKeyEntryInADS(boolean requireReplication) throws InitializationException
+  {
+    try
+    {
+      return CryptoManagerImpl.publishInstanceKeyEntryInADS(requireReplication);
+    }
+    catch (CryptoManagerException ex)
+    {
+      throw new InitializationException(ex.getMessageObject(), ex);
+    }
+  }
+
   private void searchAdminSuffix()
   {
     SearchRequest request = newSearchRequest(adminSuffixDN, SearchScope.WHOLE_SUBTREE, keySearchFilter);
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationDomain.java b/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationDomain.java
index fd04a25..0674180 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationDomain.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationDomain.java
@@ -233,7 +233,7 @@
   }
 
   /** Current status for this replicated domain. */
-  private ServerStatus status = ServerStatus.NOT_CONNECTED_STATUS;
+  private volatile ServerStatus status = ServerStatus.NOT_CONNECTED_STATUS;
   private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
   /** The configuration of the replication domain. */
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/InstanceKeyStartupReplicationTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/InstanceKeyStartupReplicationTest.java
new file mode 100644
index 0000000..3d0dab2
--- /dev/null
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/InstanceKeyStartupReplicationTest.java
@@ -0,0 +1,94 @@
+/*
+ * The contents of this file are subject to the terms of the Common Development and
+ * Distribution License (the License). You may not use this file except in compliance with the
+ * License.
+ *
+ * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
+ * specific language governing permission and limitations under the License.
+ *
+ * When distributing Covered Software, include this CDDL Header Notice in each file and include
+ * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
+ * Header, with the fields enclosed by brackets [] replaced by your own identifying
+ * information: "Portions copyright [year] [name of copyright owner]".
+ *
+ * Copyright 2026 3A Systems, LLC.
+ */
+package org.opends.server.replication;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.opends.server.config.ConfigConstants.ADS_CERTIFICATE_ALIAS;
+import static org.opends.server.config.ConfigConstants.ATTR_CRYPTO_KEY_ID;
+import static org.opends.server.config.ConfigConstants.ATTR_CRYPTO_PUBLIC_KEY_CERTIFICATE;
+import static org.opends.server.config.ConfigConstants.DN_TRUST_STORE_ROOT;
+import static org.opends.server.protocols.internal.InternalClientConnection.getRootConnection;
+import static org.testng.Assert.assertEquals;
+
+import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.ByteString;
+import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.ResultCode;
+import org.opends.admin.ads.ADSContext;
+import org.opends.server.TestCaseUtils;
+import org.opends.server.core.DirectoryServer;
+import org.opends.server.crypto.CryptoManagerImpl;
+import org.opends.server.replication.protocol.AddMsg;
+import org.opends.server.replication.service.ReplicationBroker;
+import org.opends.server.types.Entry;
+import org.testng.annotations.Test;
+
+/** Tests replication of the local instance certificate's ADS entry on restart. */
+public class InstanceKeyStartupReplicationTest extends ReplicationTestCase
+{
+  @Test
+  public void publishesMissingInstanceKeyWhenReplicationConnectsAfterStartup() throws Exception
+  {
+    final DN adminData = ADSContext.getAdministrationSuffixDN();
+    final Entry certificate = DirectoryServer.getEntry(
+        DN.valueOf(ATTR_CRYPTO_KEY_ID + "=" + ADS_CERTIFICATE_ALIAS + "," + DN_TRUST_STORE_ROOT));
+    final ByteString certificateValue = certificate.parseAttribute(ATTR_CRYPTO_PUBLIC_KEY_CERTIFICATE).asByteString();
+    final String keyId = CryptoManagerImpl.getInstanceKeyID(certificateValue.toByteArray());
+    final DN instanceKey = DN.valueOf(ATTR_CRYPTO_KEY_ID + "=" + keyId + ",cn=instance keys," + adminData);
+
+    // Keep the certificate used for TLS. Only the ADS entry is missing on restart.
+    assertThat(connection.processDelete(instanceKey).getResultCode()).isEqualTo(ResultCode.SUCCESS);
+
+    final int port = TestCaseUtils.findFreePort();
+    final Entry replicationServer = TestCaseUtils.entryFromLdifString(
+        "dn: cn=Replication Server, " + SYNCHRO_PLUGIN_DN + "\n"
+            + "objectClass: ds-cfg-replication-server\n"
+            + "cn: Replication Server\n"
+            + "ds-cfg-replication-port: " + port + "\n"
+            + "ds-cfg-replication-db-directory: InstanceKeyStartupReplicationTest\n"
+            + "ds-cfg-replication-server-id: 2781\n");
+    addSynchroServerEntry(
+        "dn: cn=admin data, cn=domains, " + SYNCHRO_PLUGIN_DN + "\n"
+            + "objectClass: ds-cfg-replication-domain\n"
+            + "cn: admin data\n"
+            + "ds-cfg-base-dn: " + adminData + "\n"
+            + "ds-cfg-replication-server: localhost:" + port + "\n"
+            + "ds-cfg-server-id: 2782\n");
+
+    TestCaseUtils.getServer().stop(getClass().getName(), LocalizableMessage.raw("Restart without a replication server"));
+    TestCaseUtils.getServer().start();
+    connection = getRootConnection();
+    assertThat(DirectoryServer.getEntry(instanceKey)).isNull();
+
+    assertThat(connection.processAdd(replicationServer).getResultCode()).isEqualTo(ResultCode.SUCCESS);
+    configEntriesToCleanup.add(replicationServer.getName());
+    replServerEntry = replicationServer;
+
+    final ReplicationBroker peer = openReplicationSession(adminData, 2783, 10, port, 5000);
+    try
+    {
+      final AddMsg publishedKey = waitForSpecificMsg(peer, AddMsg.class);
+      assertEquals(publishedKey.getDN(), instanceKey);
+      assertThat(publishedKey.getAttributes()).anyMatch(attribute ->
+          attribute.getAttributeDescription().getAttributeType().hasNameOrOID(ATTR_CRYPTO_PUBLIC_KEY_CERTIFICATE)
+              && attribute.contains(certificateValue));
+    }
+    finally
+    {
+      stop(peer);
+    }
+  }
+}

--
Gitblit v1.10.0