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

Valery Kharseko
yesterday b9b857b0b1f3f9df35ea7ecf9e88e1e5550bd43c
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
 * 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 2024-2026 3A Systems, LLC.
 */
package org.opends.server.backends.jdbc;
 
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteStringBuilder;
import org.forgerock.opendj.server.config.server.JDBCBackendCfg;
import org.opends.server.backends.pluggable.PluggableBackendImplTestCase;
import org.opends.server.backends.pluggable.spi.AccessMode;
import org.opends.server.backends.pluggable.spi.Cursor;
import org.opends.server.backends.pluggable.spi.ReadOperation;
import org.opends.server.backends.pluggable.spi.ReadableTransaction;
import org.opends.server.backends.pluggable.spi.TreeName;
import org.opends.server.backends.pluggable.spi.WriteOperation;
import org.opends.server.backends.pluggable.spi.WriteableTransaction;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
 
import static org.forgerock.opendj.config.ConfigurationMock.mockCfg;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
 
 
 
public abstract class TestCase extends PluggableBackendImplTestCase<JDBCBackendCfg> {
 
    JdbcDatabaseContainer container;
 
    @BeforeClass
    @Override
    public void setUp() throws Exception {
        if(DockerClientFactory.instance().isDockerAvailable()) {
            try {
                container = getContainer();
                container.start();
            } catch (Exception e) {
                // The database container could not be started (e.g. a slow/flaky image
                // pull or DB initialization failure on CI). Skip the test instead of
                // failing the whole build - container startup is an infrastructure
                // concern, not a regression in the JDBC backend under test.
                throw new SkipException(getContainerDockerCommand());
            }
        }
        try(Connection con = DriverManager.getConnection(createBackendCfg().getDBDirectory())){
            dropStaleTrees(con);
        } catch (Exception e) {
            throw new SkipException(getContainerDockerCommand());
        }
        super.setUp();
    }
 
    /**
     * Backend test classes sharing one database map the same tree names to the same tables,
     * so a previous run may leave trees behind — including entries encrypted with a lost cipher key.
     */
    static void dropStaleTrees(Connection con) throws SQLException {
        final List<String> stale = new ArrayList<>();
        try (final ResultSet rs = con.getMetaData().getTables(null, null, null, new String[]{"TABLE"})) {
            while (rs.next()) {
                final String name = rs.getString("TABLE_NAME");
                if (name.toLowerCase().startsWith("opendj_")) {
                    stale.add(name);
                }
            }
        }
        try (final Statement st = con.createStatement()) {
            for (final String name : stale) {
                st.execute("drop table " + name);
            }
        }
    }
 
    @Override
    protected Backend createBackend() {
        return new Backend();
    }
 
    @Override
    protected JDBCBackendCfg createBackendCfg() {
        JDBCBackendCfg backendCfg = mockCfg(JDBCBackendCfg.class);
        when(backendCfg.getBackendId()).thenReturn(getBackendId());
        when(backendCfg.getDBDirectory()).thenReturn(getJdbcUrl());
        return backendCfg;
    }
 
    @AfterClass
    @Override
    public void cleanUp() throws Exception {
        super.cleanUp();
        if(container != null) {
            container.close();
        }
    }
 
    protected abstract JdbcDatabaseContainer<?> getContainer();
 
    protected abstract String getContainerDockerCommand();
 
    protected abstract String getBackendId();
 
    protected abstract String getJdbcUrl();
 
    private static ByteString key(int i) {
        return ByteString.valueOfUtf8(String.format("key%02d", i));
    }
 
    private static ByteString value(int i) {
        return ByteString.valueOfUtf8("value" + i);
    }
 
    /**
     * Forward repositioning inside the already-fetched batch must be served from the buffer without SQL,
     * and batch sizes must grow from "fetchsize.initial" to "fetchsize" on sequential reads (#860).
     */
    @Test
    public void testPositionToKeyOrNextServedFromBuffer() throws Exception {
        System.setProperty("org.openidentityplatform.opendj.jdbc.fetchsize", "8");
        System.setProperty("org.openidentityplatform.opendj.jdbc.fetchsize.initial", "2");
        final JDBCStorage storage = new JDBCStorage(createBackendCfg(), null);
        final TreeName tree = new TreeName("testCursorBuffer", "tree");
        try {
            storage.open(AccessMode.READ_WRITE);
            storage.write(new WriteOperation() {
                @Override
                public void run(WriteableTransaction txn) throws Exception {
                    txn.openTree(tree, true);
                    for (int i = 0; i < 40; i++) {
                        txn.put(tree, key(i), value(i));
                    }
                }
            });
            storage.read(new ReadOperation<Void>() {
                @Override
                public Void run(ReadableTransaction txn) throws Exception {
                    try (final Cursor<ByteString, ByteString> cursor = txn.openCursor(tree)) {
                        final JDBCStorage.CursorImpl impl = (JDBCStorage.CursorImpl) cursor;
 
                        assertTrue(cursor.next()); // fetch #1: initial batch of 2 (key00, key01)
                        assertEquals(cursor.getKey(), key(0));
                        assertEquals(impl.fetchCount, 1);
                        assertTrue(cursor.next()); // key01 is buffered
                        assertEquals(impl.fetchCount, 1);
                        assertTrue(cursor.next()); // fetch #2: grown batch of 8 (key02..key09)
                        assertEquals(cursor.getKey(), key(2));
                        assertEquals(impl.fetchCount, 2);
 
                        // forward repositioning within the fetched range must not run SQL
                        assertTrue(cursor.positionToKeyOrNext(key(5)));
                        assertEquals(cursor.getKey(), key(5));
                        assertEquals(cursor.getValue(), value(5));
                        assertEquals(impl.fetchCount, 2);
                        assertTrue(cursor.positionToKeyOrNext(ByteString.valueOfUtf8("key051"))); // between rows
                        assertEquals(cursor.getKey(), key(6));
                        assertEquals(impl.fetchCount, 2);
                        assertTrue(cursor.positionToKeyOrNext(key(9))); // last buffered row
                        assertEquals(cursor.getKey(), key(9));
                        assertEquals(impl.fetchCount, 2);
 
                        assertTrue(cursor.positionToKeyOrNext(key(20))); // fetch #3: beyond the buffer
                        assertEquals(cursor.getKey(), key(20));
                        assertEquals(impl.fetchCount, 3);
                        assertTrue(cursor.positionToKeyOrNext(key(1))); // fetch #4: backward
                        assertEquals(cursor.getKey(), key(1));
                        assertEquals(impl.fetchCount, 4);
 
                        // emulate DN2ID.ChildrenCursor: reposition to currentKey+0x01 for every row.
                        // Before the fix every reposition re-fetched a full batch: 38 fetches here.
                        final long fetchesBefore = impl.fetchCount;
                        int rows = 1; // standing on key01
                        while (cursor.positionToKeyOrNext(
                                new ByteStringBuilder().appendBytes(cursor.getKey()).appendByte(0x01).toByteString())) {
                            rows++;
                        }
                        assertEquals(rows, 39); // key01..key39
                        assertTrue(impl.fetchCount - fetchesBefore <= 8,
                                "sibling scan took " + (impl.fetchCount - fetchesBefore) + " fetches");
                    }
                    return null;
                }
            });
        } finally {
            System.clearProperty("org.openidentityplatform.opendj.jdbc.fetchsize");
            System.clearProperty("org.openidentityplatform.opendj.jdbc.fetchsize.initial");
            try {
                storage.write(new WriteOperation() {
                    @Override
                    public void run(WriteableTransaction txn) throws Exception {
                        txn.deleteTree(tree);
                    }
                });
            } catch (Exception ignored) {}
            storage.close();
        }
    }
 
    /** Buffer-served repositioning relies on the database collating keys in unsigned byte order. */
    @Test
    public void testCursorKeyOrderIsUnsigned() throws Exception {
        final JDBCStorage storage = new JDBCStorage(createBackendCfg(), null);
        final TreeName tree = new TreeName("testCursorOrder", "tree");
        final ByteString low = ByteString.valueOfBytes(new byte[] { 0x7F });
        final ByteString high = ByteString.valueOfBytes(new byte[] { (byte) 0x80, 0x01 });
        try {
            storage.open(AccessMode.READ_WRITE);
            storage.write(new WriteOperation() {
                @Override
                public void run(WriteableTransaction txn) throws Exception {
                    txn.openTree(tree, true);
                    txn.put(tree, low, value(1));
                    txn.put(tree, high, value(2));
                }
            });
            storage.read(new ReadOperation<Void>() {
                @Override
                public Void run(ReadableTransaction txn) throws Exception {
                    try (final Cursor<ByteString, ByteString> cursor = txn.openCursor(tree)) {
                        // with a signed collation 0x80 would sort before 0x7F and these would fail
                        assertTrue(cursor.next());
                        assertEquals(cursor.getKey(), low);
                        assertTrue(cursor.positionToKeyOrNext(ByteString.valueOfBytes(new byte[] { (byte) 0x80 })));
                        assertEquals(cursor.getKey(), high);
                        assertFalse(cursor.next());
                        assertTrue(cursor.positionToLastKey());
                        assertEquals(cursor.getKey(), high);
                    }
                    return null;
                }
            });
        } finally {
            try {
                storage.write(new WriteOperation() {
                    @Override
                    public void run(WriteableTransaction txn) throws Exception {
                        txn.deleteTree(tree);
                    }
                });
            } catch (Exception ignored) {}
            storage.close();
        }
    }
 
    /** Cursor operations must keep working when the tree spans several "fetchsize" batches. */
    @Test
    public void testCursorCrossesFetchSizeBatches() throws Exception {
        System.setProperty("org.openidentityplatform.opendj.jdbc.fetchsize", "2");
        final JDBCStorage storage = new JDBCStorage(createBackendCfg(), null);
        final TreeName tree = new TreeName("testCursorBatch", "tree");
        try {
            storage.open(AccessMode.READ_WRITE);
            storage.write(new WriteOperation() {
                @Override
                public void run(WriteableTransaction txn) throws Exception {
                    txn.openTree(tree, true);
                    for (int i = 0; i < 7; i++) {
                        txn.put(tree, key(i), value(i));
                    }
                }
            });
            storage.read(new ReadOperation<Void>() {
                @Override
                public Void run(ReadableTransaction txn) throws Exception {
                    try (final Cursor<ByteString, ByteString> cursor = txn.openCursor(tree)) {
                        for (int i = 0; i < 7; i++) {
                            assertTrue(cursor.next(), "next() at " + i);
                            assertEquals(cursor.getKey(), key(i));
                            assertEquals(cursor.getValue(), value(i));
                        }
                        assertFalse(cursor.next());
                        assertFalse(cursor.isDefined());
                        try {
                            cursor.getKey();
                            fail("getKey() on undefined cursor must fail");
                        } catch (NoSuchElementException expected) {}
 
                        assertTrue(cursor.positionToKeyOrNext(key(3)));
                        assertEquals(cursor.getKey(), key(3));
                        assertTrue(cursor.positionToKeyOrNext(ByteString.valueOfUtf8("key031")));
                        assertEquals(cursor.getKey(), key(4));
                        assertTrue(cursor.next());
                        assertEquals(cursor.getKey(), key(5));
                        assertTrue(cursor.next());
                        assertEquals(cursor.getKey(), key(6));
                        assertFalse(cursor.next());
                        assertFalse(cursor.positionToKeyOrNext(ByteString.valueOfUtf8("z")));
                        assertFalse(cursor.isDefined());
 
                        assertTrue(cursor.positionToKey(key(5)));
                        assertEquals(cursor.getValue(), value(5));
                        assertTrue(cursor.next());
                        assertEquals(cursor.getKey(), key(6));
                        assertFalse(cursor.positionToKey(ByteString.valueOfUtf8("key99")));
                        assertFalse(cursor.isDefined());
 
                        assertTrue(cursor.positionToIndex(0));
                        assertEquals(cursor.getKey(), key(0));
                        assertTrue(cursor.positionToIndex(5));
                        assertEquals(cursor.getKey(), key(5));
                        assertTrue(cursor.next());
                        assertEquals(cursor.getKey(), key(6));
                        assertFalse(cursor.positionToIndex(7));
                        assertFalse(cursor.positionToIndex(-1));
 
                        assertTrue(cursor.positionToLastKey());
                        assertEquals(cursor.getKey(), key(6));
                        assertFalse(cursor.next());
 
                        assertTrue(cursor.positionToKey(key(0)));
                        try {
                            cursor.delete();
                            fail("delete() on read-only cursor must fail");
                        } catch (UnsupportedOperationException expected) {}
                    }
                    return null;
                }
            });
            storage.write(new WriteOperation() {
                @Override
                public void run(WriteableTransaction txn) throws Exception {
                    try (final Cursor<ByteString, ByteString> cursor = txn.openCursor(tree)) {
                        assertTrue(cursor.positionToKey(key(3)));
                        cursor.delete();
                        assertTrue(cursor.next());
                        assertEquals(cursor.getKey(), key(4));
                    }
                    assertNull(txn.read(tree, key(3)));
                    assertEquals(txn.getRecordCount(tree), 6);
                }
            });
        } finally {
            System.clearProperty("org.openidentityplatform.opendj.jdbc.fetchsize");
            try {
                storage.write(new WriteOperation() {
                    @Override
                    public void run(WriteableTransaction txn) throws Exception {
                        txn.deleteTree(tree);
                    }
                });
            } catch (Exception ignored) {}
            storage.close();
        }
    }
}