mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
16 hours ago 48f3197de5cbfe0cc0110d95b8d53e3d2c527fe4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
 * 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<Response> bindResponses = new TestSubscriber<Response>() {
            @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<Void> 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<Response> 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<Response> bindResponses = new TestSubscriber<>();
        try {
            final SearchOperation search = submitSearch(1, searchResponses);
            final org.opends.server.types.SearchResultEntry entry = searchEntry();
            final CompletableFuture<Void> 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<Response> {
        private final CompletableFuture<Void> responseStarted = new CompletableFuture<>();
        private final CompletableFuture<Void> 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<Response> bindResponses = new TestSubscriber<>();
        final AtomicReference<AuthenticationInfo> authenticationAtResponse = new AtomicReference<>();
        final AtomicReference<Object> 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<Response> searchResponses = new TestSubscriber<>();
        try {
            assertNotNull(submitSearch(1, searchResponses));
            assertFalse(connection.getAuthenticationInfo().isAuthenticated());
        } finally {
            searchResponses.cancel();
        }
    }
 
    @Test
    public void latePersistentSearchCancellationKeepsReplacementWithReusedMessageId() throws Exception {
        final TestSubscriber<Response> originalResponses = new TestSubscriber<>();
        final TestSubscriber<Response> 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<Response> responses) throws Exception {
        final AtomicReference<Operation> 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()));
    }
}