/* * 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.forgerock.opendj.reactive; import static org.forgerock.opendj.ldap.spi.LdapMessages.newRequestEnvelope; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import io.reactivex.rxjava3.subscribers.TestSubscriber; import org.forgerock.opendj.io.ASN1; import org.forgerock.opendj.ldap.ByteString; import org.forgerock.opendj.ldap.ByteStringBuilder; import org.forgerock.opendj.ldap.DereferenceAliasesPolicy; import org.forgerock.opendj.ldap.LDAPClientContext; import org.forgerock.opendj.ldap.ResultCode; import org.forgerock.opendj.ldap.SearchScope; import org.forgerock.opendj.ldap.responses.BindResult; import org.forgerock.opendj.ldap.responses.Response; import org.forgerock.opendj.ldap.responses.SearchResultEntry; import org.forgerock.opendj.ldap.spi.LdapMessages.LdapRequestEnvelope; import org.opends.server.DirectoryServerTestCase; import org.opends.server.TestCaseUtils; import org.opends.server.core.DirectoryServer; import org.opends.server.core.PersistentSearch; import org.opends.server.core.QueueingStrategy; import org.opends.server.core.SearchOperation; import org.opends.server.protocols.ldap.BindRequestProtocolOp; import org.opends.server.protocols.ldap.LDAPFilter; import org.opends.server.protocols.ldap.LDAPMessage; import org.opends.server.protocols.ldap.ProtocolOp; import org.opends.server.protocols.ldap.SearchRequestProtocolOp; import org.opends.server.types.AuthenticationInfo; import org.opends.server.types.DirectoryException; import org.opends.server.types.DisconnectReason; import org.opends.server.types.Operation; import org.opends.server.workflowelement.localbackend.LocalBackendSearchOperation; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Checks Bind and Search response ordering with a controlled subscriber and work queue. */ @Test(groups = { "precommit" }, sequential = true) public class LDAPBindResponseOrderTest extends DirectoryServerTestCase { private LDAPClientConnection2 connection; @BeforeClass public void startServer() throws Exception { TestCaseUtils.startServer(); } @BeforeMethod public void openConnection() { final LDAPConnectionHandler2 handler = DirectoryServer.getConnectionHandlers().stream() .filter(LDAPConnectionHandler2.class::isInstance) .map(LDAPConnectionHandler2.class::cast) .findFirst().orElseThrow(); final LDAPClientContext context = mock(LDAPClientContext.class); final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 389); when(context.getPeerAddress()).thenReturn(address); when(context.getLocalAddress()).thenReturn(address); connection = new LDAPClientConnection2(handler, context, "LDAP", false); } @AfterMethod public void closeConnection() { connection.disconnect(DisconnectReason.CLIENT_DISCONNECT, false, null); } @DataProvider public Object[][] bindResults() { return new Object[][] { { ResultCode.SUCCESS, true }, { ResultCode.BUSY, true }, { ResultCode.BUSY, false } }; } @Test(dataProvider = "bindResults") public void bindWaitsForAnOrdinarySearchResponseHandoff(ResultCode expected, boolean searchCompleted) throws Exception { final PausedSearchResponses searchResponses = new PausedSearchResponses(); final AtomicBoolean searchHandedOffBeforeBind = new AtomicBoolean(); final TestSubscriber bindResponses = new TestSubscriber() { @Override public void onNext(Response response) { searchHandedOffBeforeBind.set(searchResponses.responseHandedOff); super.onNext(response); } }; try { final SearchOperation search = submitSearch(1, searchResponses); final org.opends.server.types.SearchResultEntry entry = searchEntry(); final CompletableFuture firstEntry = CompletableFuture.runAsync(() -> connection.sendSearchEntry(search, entry)); searchResponses.responseStarted.get(5, TimeUnit.SECONDS); connection.sendSearchEntry(search, entry); if (searchCompleted) { search.setResultCode(ResultCode.SUCCESS); search.sendSearchResultDone(); search.operationCompleted(); assertNull(connection.getOperationInProgress(1)); } final LdapRequestEnvelope bindRequest = bindRequest(); final QueueingStrategy queue = operation -> { if (expected == ResultCode.BUSY) { throw new DirectoryException(ResultCode.BUSY, ResultCode.BUSY.getName()); } operation.run(); operation.operationCompleted(); }; // The request handler must return even while the earlier writer remains in the subscriber. CompletableFuture.runAsync(() -> connection.handle(queue, bindRequest).subscribe(bindResponses)) .get(5, TimeUnit.SECONDS); bindResponses.assertEmpty(); searchResponses.finishResponse.complete(null); firstEntry.get(5, TimeUnit.SECONDS); bindResponses.awaitDone(5, TimeUnit.SECONDS) .assertValue(response -> response instanceof BindResult && ((BindResult) response).getResultCode() == expected) .assertComplete().assertNoErrors(); assertTrue(searchHandedOffBeforeBind.get(), "BindResponse arrived before the Search handoff"); searchResponses.request(Long.MAX_VALUE); searchResponses.assertValueCount(1).assertValueAt(0, SearchResultEntry.class::isInstance) .assertComplete().assertNoErrors(); if (!searchCompleted) { assertNotNull(search.getCancelRequest(), "The rejected Bind left a Search without its response stream"); assertNull(connection.getOperationInProgress(1)); } final TestSubscriber nextResponses = new TestSubscriber<>(); try { final SearchOperation nextSearch = submitSearch(1, nextResponses); assertNotNull(nextSearch); if (!searchCompleted) { search.operationCompleted(); assertSame(connection.getOperationInProgress(1), nextSearch); } } finally { nextResponses.cancel(); } } finally { searchResponses.finishResponse.complete(null); bindResponses.cancel(); searchResponses.cancel(); } } @Test public void disconnectCompletesADeferredBindWithoutEnqueueingIt() throws Exception { final PausedSearchResponses searchResponses = new PausedSearchResponses(); final TestSubscriber bindResponses = new TestSubscriber<>(); try { final SearchOperation search = submitSearch(1, searchResponses); final org.opends.server.types.SearchResultEntry entry = searchEntry(); final CompletableFuture firstEntry = CompletableFuture.runAsync(() -> connection.sendSearchEntry(search, entry)); searchResponses.responseStarted.get(5, TimeUnit.SECONDS); final LdapRequestEnvelope bindRequest = bindRequest(); final QueueingStrategy queue = operation -> fail("Disconnected Bind reached the work queue"); CompletableFuture.runAsync(() -> connection.handle(queue, bindRequest).subscribe(bindResponses)) .get(5, TimeUnit.SECONDS); bindResponses.assertEmpty(); connection.disconnect(DisconnectReason.CLIENT_DISCONNECT, false, null); searchResponses.finishResponse.complete(null); firstEntry.get(5, TimeUnit.SECONDS); bindResponses.awaitDone(5, TimeUnit.SECONDS).assertResult(); } finally { searchResponses.finishResponse.complete(null); searchResponses.cancel(); bindResponses.cancel(); } } private static final class PausedSearchResponses extends TestSubscriber { private final CompletableFuture responseStarted = new CompletableFuture<>(); private final CompletableFuture finishResponse = new CompletableFuture<>(); private volatile boolean responseHandedOff; PausedSearchResponses() { super(1); } @Override public void onNext(Response response) { responseStarted.complete(null); finishResponse.join(); super.onNext(response); responseHandedOff = true; } } @Test public void queueRejectedBindWithoutSearchClearsAuthorizationAndSaslState() throws Exception { connection.setAuthenticationInfo(new AuthenticationInfo( TestCaseUtils.makeEntry("dn: cn=bound-user", "objectClass: top", "cn: bound-user"), false)); connection.setSASLAuthStateInfo(new Object()); assertTrue(connection.getAuthenticationInfo().isAuthenticated()); final TestSubscriber bindResponses = new TestSubscriber<>(); final AtomicReference authenticationAtResponse = new AtomicReference<>(); final AtomicReference saslStateAtResponse = new AtomicReference<>(); connection.handle(operation -> { throw new DirectoryException(ResultCode.BUSY, ResultCode.BUSY.getName()); }, bindRequest()).onNext(response -> { authenticationAtResponse.set(connection.getAuthenticationInfo()); saslStateAtResponse.set(connection.getSASLAuthStateInfo()); }).subscribe(bindResponses); bindResponses.assertValue(response -> response instanceof BindResult && ((BindResult) response).getResultCode() == ResultCode.BUSY).assertComplete().assertNoErrors(); assertFalse(authenticationAtResponse.get().isAuthenticated()); assertNull(authenticationAtResponse.get().getAuthorizationDN()); assertNull(saslStateAtResponse.get()); final TestSubscriber searchResponses = new TestSubscriber<>(); try { assertNotNull(submitSearch(1, searchResponses)); assertFalse(connection.getAuthenticationInfo().isAuthenticated()); } finally { searchResponses.cancel(); } } @Test public void latePersistentSearchCancellationKeepsReplacementWithReusedMessageId() throws Exception { final TestSubscriber originalResponses = new TestSubscriber<>(); final TestSubscriber replacementResponses = new TestSubscriber<>(); final SearchOperation original = submitSearch(1, originalResponses); original.operationCompleted(); final SearchOperation replacement = submitSearch(1, replacementResponses); // Backend registrations can wrap the same logical operation independently. final PersistentSearch oldSearch = new PersistentSearch( new LocalBackendSearchOperation(original), Collections.emptySet(), true, false); final PersistentSearch sibling = new PersistentSearch( new LocalBackendSearchOperation(original), Collections.emptySet(), true, false); final PersistentSearch replacementSearch = new PersistentSearch( new LocalBackendSearchOperation(replacement), Collections.emptySet(), true, false); replacementSearch.enable(); oldSearch.enable(); sibling.enable(); try { oldSearch.cancel(); assertEquals(connection.getPersistentSearches(), Collections.singletonList(replacementSearch)); } finally { connection.getPersistentSearches().forEach(PersistentSearch::cancel); originalResponses.cancel(); replacementResponses.cancel(); replacement.operationCompleted(); } } private static org.opends.server.types.SearchResultEntry searchEntry() throws Exception { return new org.opends.server.types.SearchResultEntry( TestCaseUtils.makeEntry("dn: cn=test", "objectClass: top", "cn: test")); } private static LdapRequestEnvelope bindRequest() throws IOException { return request(2, new BindRequestProtocolOp(ByteString.empty(), 3, ByteString.empty())); } private SearchOperation submitSearch(int messageId, TestSubscriber responses) throws Exception { final AtomicReference operation = new AtomicReference<>(); final SearchRequestProtocolOp search = new SearchRequestProtocolOp(ByteString.empty(), SearchScope.BASE_OBJECT, DereferenceAliasesPolicy.NEVER, 0, 0, false, LDAPFilter.decode("(objectClass=*)"), Collections.emptySet()); connection.handle(operation::set, request(messageId, search)).subscribe(responses); return (SearchOperation) operation.get(); } private static LdapRequestEnvelope request(int messageId, ProtocolOp protocolOp) throws IOException { final ByteStringBuilder encoded = new ByteStringBuilder(); new LDAPMessage(messageId, protocolOp).write(ASN1.getWriter(encoded)); return newRequestEnvelope(protocolOp.getType(), messageId, 3, null, ASN1.getReader(encoded.toByteString())); } }