This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-dbcp.git
The following commit(s) were added to refs/heads/master by this push:
new c5eafe6c Add DriverAdapterCPDS JNDI password export control (#556)
c5eafe6c is described below
commit c5eafe6c2bb98d10e2dd0389343d0c97a7967aec
Author: Gary Gregory <[email protected]>
AuthorDate: Sat Nov 21 15:32:15 2026 -0500
Add DriverAdapterCPDS JNDI password export control (#556)
Add exportPasswordAsRefAddr to optionally omit the password address
from JNDI References while preserving existing behavior by default.
Retain the setting through lookup, rebinding, and serialization,
including compatibility with older serialized data sources.
Document credential provisioning requirements
and the option's limitations.
---
src/changes/changes.xml | 1 +
.../dbcp2/cpdsadapter/DriverAdapterCPDS.java | 71 +++-
src/site/xdoc/guide/jndi-howto.xml | 31 ++
.../TestDriverAdapterCPDSReference.java | 365 +++++++++++++++++++++
.../DriverAdapterCPDS-2.14.0.properties | 20 ++
5 files changed, 486 insertions(+), 2 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index c778f432..478902ae 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -73,6 +73,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="Gary Gregory">Detach
PoolingDataSource connection guards from their delegates even when close()
fails, and make abort() on closed DelegatingConnection wrappers a
no-op.</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent infinite
loops when resolving innermost JDBC delegates, invalidating wrapped connections
with BasicDataSource.invalidateConnection(), or checking linked SQLExceptions
for fatal errors.</action>
<!-- ADD -->
+ <action type="add" dev="ggregory" due-to="Gary Gregory">Add
DriverAdapterCPDS.exportPasswordAsRefAddr to optionally omit the password
address from JNDI References. Password export remains enabled by default for
compatibility; the setting survives JNDI lookup and Java serialization.</action>
<!-- UPDATE -->
<action type="update" dev="ggregory" due-to="Gary Gregory">Bump
org.apache.commons:commons-parent from 93 to 107.</action>
<action type="update" dev="ggregory" due-to="Gary Gregory">Bump
org.apache.commons:commons-pool2 from 2.13.0 to 2.13.1.</action>
diff --git
a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
index 27cb0609..3b64a630 100644
--- a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
+++ b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
@@ -93,6 +93,8 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
private static final String KEY_DESCRIPTION = "description";
+ private static final String KEY_EXPORT_PASSWORD_AS_REF_ADDR =
"exportPasswordAsRefAddr";
+
private static final String KEY_ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED =
"accessToUnderlyingConnectionAllowed";
private static final String KEY_MAX_PREPARED_STATEMENTS =
"maxPreparedStatements";
@@ -166,6 +168,12 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
*/
private boolean accessToUnderlyingConnectionAllowed;
+ /**
+ * Omits the password from JNDI References when true. The negative form
preserves password export when reading serialized instances
+ * written before this field existed, for which the field defaults to
false.
+ */
+ private volatile boolean omitPasswordFromReference;
+
/**
* Default no-argument constructor for Serialization
*/
@@ -341,6 +349,11 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
setPassword(getStringContent(ra));
}
+ ra = ref.get(KEY_EXPORT_PASSWORD_AS_REF_ADDR);
+ if (isNotEmpty(ra)) {
+ setExportPasswordAsRefAddr(getBooleanContentString(ra));
+ }
+
ra = ref.get(KEY_POOL_PREPARED_STATEMENTS);
if (isNotEmpty(ra)) {
setPoolPreparedStatements(getBooleanContentString(ra));
@@ -477,7 +490,23 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
}
/**
- * Implements {@link Referenceable}.
+ * Gets a JNDI Reference containing this data source's connection
configuration.
+ *
+ * <p>
+ * By default, the Reference includes the default user's password as a
cleartext {@link StringRefAddr}, preserving authentication
+ * when a naming provider reconstructs this data source. Protect the
Reference and any directory entries, logs, backups, or replication
+ * streams that contain it as credentials. To omit the password address,
call {@link #setExportPasswordAsRefAddr(boolean)} with
+ * {@code false} before creating or binding the Reference. The export
setting is itself included in the Reference and restored on lookup.
+ * </p>
+ *
+ * <p>
+ * This option only controls the dedicated {@code password} address. Other
values, including credentials embedded in the JDBC URL,
+ * are exported unchanged. It does not omit the configured password from
Java serialization or remove passwords from previously created References.
+ * </p>
+ *
+ * @return a Reference describing this data source.
+ * @throws NamingException if the Reference cannot be created.
+ * @see #setExportPasswordAsRefAddr(boolean)
*/
@Override
public Reference getReference() throws NamingException {
@@ -485,11 +514,15 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
final String factory = getClass().getName();
final Reference ref = new Reference(getClass().getName(), factory,
null);
+ final boolean exportPassword = isExportPasswordAsRefAddr();
ref.add(new StringRefAddr(KEY_DESCRIPTION, getDescription()));
ref.add(new StringRefAddr(KEY_DRIVER, getDriver()));
ref.add(new StringRefAddr(KEY_LOGIN_TIMEOUT,
String.valueOf(getLoginTimeout())));
- ref.add(new StringRefAddr(Constants.KEY_PASSWORD, getPassword()));
+ if (exportPassword) {
+ ref.add(new StringRefAddr(Constants.KEY_PASSWORD, getPassword()));
+ }
+ ref.add(new StringRefAddr(KEY_EXPORT_PASSWORD_AS_REF_ADDR,
Boolean.toString(exportPassword)));
ref.add(new StringRefAddr(Constants.KEY_USER, getUser()));
ref.add(new StringRefAddr(KEY_URL, getUrl()));
@@ -553,6 +586,17 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
return this.accessToUnderlyingConnectionAllowed;
}
+ /**
+ * Gets whether {@link #getReference()} includes the default user's
password address.
+ *
+ * @return true (the default) to export the password address, or false to
omit it.
+ * @since 2.15.0
+ * @see #setExportPasswordAsRefAddr(boolean)
+ */
+ public boolean isExportPasswordAsRefAddr() {
+ return !omitPasswordFromReference;
+ }
+
private boolean isNotEmpty(final RefAddr ra) {
return ra != null && ra.getContent() != null;
}
@@ -657,6 +701,29 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
this.durationBetweenEvictionRuns = durationBetweenEvictionRuns;
}
+ /**
+ * Sets whether {@link #getReference()} includes the default user's
password address.
+ *
+ * <p>
+ * The default is {@code true} for compatibility with existing JNDI
deployments. When {@code false}, a newly reconstructed data source
+ * has no default password unless it is supplied separately. Before its
first connection attempt, including an unsuccessful attempt,
+ * provision the password with {@link #setPassword(String)} or {@link
#setPassword(char[])}. Alternatively, supply credentials to
+ * {@link #getPooledConnection(String, String)}. Containers that look up
and immediately use the data source must provide credentials
+ * through their own configuration or retain password export.
+ * </p>
+ *
+ * <p>
+ * This setting can be changed after connections have been requested and
affects subsequent References only. It is retained through
+ * JNDI lookup and Java serialization. It does not clear the configured
password or redact other Reference addresses, such as the URL.
+ * </p>
+ *
+ * @param exportPasswordAsRefAddr true to export the password address, or
false to omit it.
+ * @since 2.15.0
+ */
+ public void setExportPasswordAsRefAddr(final boolean
exportPasswordAsRefAddr) {
+ omitPasswordFromReference = !exportPasswordAsRefAddr;
+ }
+
/**
* Sets the maximum time in seconds that this data source will wait while
attempting to connect to a database. NOT
* USED.
diff --git a/src/site/xdoc/guide/jndi-howto.xml
b/src/site/xdoc/guide/jndi-howto.xml
index 6b0b3e34..5785a6db 100644
--- a/src/site/xdoc/guide/jndi-howto.xml
+++ b/src/site/xdoc/guide/jndi-howto.xml
@@ -72,6 +72,37 @@
]]></source>
</section>
+<section name="DriverAdapterCPDS password export">
+<p>
+ Since 2.15.0,
<code>DriverAdapterCPDS.setExportPasswordAsRefAddr(false)</code> omits the
dedicated
+ <code>password</code> address from References produced by
<code>getReference()</code>, including when a naming provider
+ binds the data source through <code>Referenceable</code>. Export remains
enabled by default for compatibility.
+ Protect References containing credentials and any directory entries, logs,
backups, or replication streams that store them.
+</p>
+<p>
+ When export is disabled, a newly reconstructed data source has no default
password. Supply it with <code>setPassword()</code>
+ before the first connection attempt, even an unsuccessful one, or pass
credentials to <code>getPooledConnection(user, password)</code>.
+ A container that looks up and immediately uses the data source must supply
credentials through its own configuration or retain export.
+ For example, an application that performs the lookup itself can provision
the resolved instance before handing it to its pool:
+</p>
+<source><![CDATA[
+ cpds.setExportPasswordAsRefAddr(false);
+ context.rebind("jdbc/cpds", cpds);
+
+ DriverAdapterCPDS resolved = (DriverAdapterCPDS) context.lookup("jdbc/cpds");
+ resolved.setPassword(passwordFromSecretStore);
+ SharedPoolDataSource pool = new SharedPoolDataSource();
+ pool.setConnectionPoolDataSource(resolved);
+]]></source>
+<p>
+ The export setting is retained through lookup and rebinding, so provisioning
the resolved password does not re-enable export.
+ A manually constructed Reference can configure it with a
<code>StringRefAddr("exportPasswordAsRefAddr", "false")</code>;
+ this controls future exports and does not prevent the factory from reading a
supplied <code>password</code> address.
+ Other addresses, including credentials embedded in JDBC URLs, remain
unchanged. Java serialization still contains the configured
+ password. Changing the setting does not remove credentials from previously
created References or directory entries.
+</p>
+</section>
+
<section name="PerUserPoolDataSource">
<source><![CDATA[
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
diff --git
a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
new file mode 100644
index 00000000..4dcb5d5c
--- /dev/null
+++
b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
@@ -0,0 +1,365 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.dbcp2.cpdsadapter;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Base64;
+import java.util.Hashtable;
+import java.util.Properties;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import javax.naming.Context;
+import javax.naming.Reference;
+import javax.naming.StringRefAddr;
+import javax.naming.spi.NamingManager;
+import javax.sql.PooledConnection;
+
+import org.apache.commons.dbcp2.TesterDriver;
+import org.apache.commons.dbcp2.datasources.SharedPoolDataSource;
+import org.apache.naming.NamingContext;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests password export, JNDI reconstruction, and serialization compatibility.
+ */
+class TestDriverAdapterCPDSReference {
+
+ private static final String EXPORT_PASSWORD = "exportPasswordAsRefAddr";
+
+ private static void assertCanConnect(final DriverAdapterCPDS source)
throws SQLException {
+ assertCanConnect(source.getPooledConnection());
+ }
+
+ private static void assertCanConnect(final PooledConnection pooled) throws
SQLException {
+ try (Connection connection = pooled.getConnection()) {
+ assertFalse(connection.isClosed());
+ } finally {
+ pooled.close();
+ }
+ }
+
+ private static DriverAdapterCPDS deserialize(final byte[] bytes) throws
Exception {
+ try (ObjectInputStream input = new ObjectInputStream(new
ByteArrayInputStream(bytes))) {
+ return (DriverAdapterCPDS) input.readObject();
+ }
+ }
+
+ private static DriverAdapterCPDS newDataSource() throws Exception {
+ final DriverAdapterCPDS source = new DriverAdapterCPDS();
+ source.setDriver(TesterDriver.class.getName());
+ source.setUrl("jdbc:apache:commons:testdriver");
+ source.setUser("u1");
+ source.setPassword("p1");
+ return source;
+ }
+
+ static Stream<Arguments> optionalSettingArguments() {
+ return Stream.of(true, false).flatMap(export -> Stream.of(true, false)
+ .map(includeNullAddress -> Arguments.of(export,
includeNullAddress)));
+ }
+
+ static Stream<Arguments> passwordArguments() {
+ return Stream.of(true, false).flatMap(export -> Stream.of(null, "",
"p1", "s\u00ebcr\u00e8t\u0000=&\n")
+ .flatMap(password -> IntStream.range(0, 4).mapToObj(mode ->
Arguments.of(export, password, mode))));
+ }
+
+ private static void removeAddress(final Reference reference, final String
type) {
+ for (int i = 0; i < reference.size(); i++) {
+ if (type.equals(reference.get(i).getType())) {
+ reference.remove(i);
+ return;
+ }
+ }
+ }
+
+ private static DriverAdapterCPDS resolve(final Reference reference) throws
Exception {
+ return (DriverAdapterCPDS) NamingManager.getObjectInstance(reference,
null, null, null);
+ }
+
+ private static byte[] serialize(final Object source) throws Exception {
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ObjectOutputStream output = new ObjectOutputStream(bytes)) {
+ output.writeObject(source);
+ }
+ return bytes.toByteArray();
+ }
+
+ @Test
+ void testDefaultReferenceReconstructsUsableDataSource() throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ assertTrue(source.isExportPasswordAsRefAddr());
+ final DriverAdapterCPDS resolved = resolve(source.getReference());
+ assertNotSame(source, resolved);
+ assertEquals("p1", resolved.getPassword());
+ assertTrue(resolved.isExportPasswordAsRefAddr());
+ assertCanConnect(resolved);
+ }
+
+ @Test
+ void testExportCanChangeAfterConnectionUse() throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ assertCanConnect(source);
+ source.setExportPasswordAsRefAddr(false);
+ assertNull(source.getReference().get("password"));
+ source.setExportPasswordAsRefAddr(true);
+ assertEquals("p1", source.getReference().get("password").getContent());
+ assertCanConnect(source);
+ }
+
+ @Test
+ void testExportDoesNotRedactUrl() throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ final String url = "jdbc:example:database;password=embedded-secret";
+ source.setUrl(url);
+ source.setExportPasswordAsRefAddr(false);
+ final Reference reference = source.getReference();
+ assertNull(reference.get("password"));
+ assertEquals(url, reference.get("url").getContent());
+ assertEquals(url, resolve(reference).getUrl());
+ }
+
+ @Test
+ void testExportToggleDoesNotChangeExistingReferences() throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ final Reference original = source.getReference();
+ source.setExportPasswordAsRefAddr(false);
+ final Reference omitted = source.getReference();
+ source.setExportPasswordAsRefAddr(true);
+ assertEquals("p1", original.get("password").getContent());
+ assertEquals("true", original.get(EXPORT_PASSWORD).getContent());
+ assertNull(omitted.get("password"));
+ assertEquals("false", omitted.get(EXPORT_PASSWORD).getContent());
+ assertEquals("p1", source.getReference().get("password").getContent());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testExternalCredentialsWorkWithStatementPooling(final boolean
poolStatements) throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setPoolPreparedStatements(poolStatements);
+ source.setExportPasswordAsRefAddr(false);
+ final DriverAdapterCPDS resolved = resolve(source.getReference());
+ assertNull(resolved.getPassword());
+ assertCanConnect(resolved.getPooledConnection("u1", "p1"));
+ assertNull(resolved.getPassword());
+ assertNull(resolved.getReference().get("password"));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true, true", "true, false", "false, true", "false, false"})
+ void testFactoryOverridesExistingExportSetting(final boolean
initialExport, final boolean referenceExport) throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setExportPasswordAsRefAddr(referenceExport);
+ final Reference reference = source.getReference();
+ final DriverAdapterCPDS factory = newDataSource();
+ factory.setExportPasswordAsRefAddr(initialExport);
+ assertSame(factory, factory.getObjectInstance(reference, null, null,
null));
+ assertEquals(referenceExport, factory.isExportPasswordAsRefAddr());
+ final Reference exported = factory.getReference();
+ assertEquals(Boolean.toString(referenceExport),
exported.get(EXPORT_PASSWORD).getContent());
+ assertEquals(referenceExport, exported.get("password") != null);
+ assertCanConnect(factory);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true, true", "TRUE, true", "false, false", "FALSE, false",
"invalid, false", "'', false"})
+ void testFactoryReadsExportSetting(final String setting, final boolean
expected) throws Exception {
+ final Reference reference = newDataSource().getReference();
+ removeAddress(reference, EXPORT_PASSWORD);
+ reference.add(new StringRefAddr(EXPORT_PASSWORD, setting));
+ final DriverAdapterCPDS resolved = resolve(reference);
+ assertEquals(expected, resolved.isExportPasswordAsRefAddr());
+ // An export policy does not prevent importing credentials supplied by
the naming provider.
+ assertEquals("p1", resolved.getPassword());
+ assertCanConnect(resolved);
+ assertEquals(expected, resolved.getReference().get("password") !=
null);
+ }
+
+ @ParameterizedTest
+ @MethodSource("optionalSettingArguments")
+ void testFactoryRetainsSettingWhenAddressHasNoValue(final boolean export,
final boolean includeNullAddress) throws Exception {
+ final DriverAdapterCPDS factory = new DriverAdapterCPDS();
+ factory.setExportPasswordAsRefAddr(export);
+ final Reference reference = newDataSource().getReference();
+ removeAddress(reference, EXPORT_PASSWORD);
+ if (includeNullAddress) {
+ reference.add(new StringRefAddr(EXPORT_PASSWORD, null));
+ }
+ assertSame(factory, factory.getObjectInstance(reference, null, null,
null));
+ assertEquals(export, factory.isExportPasswordAsRefAddr());
+ assertCanConnect(factory);
+ }
+
+ @Test
+ void testLegacyReferenceRetainsPasswordExport() throws Exception {
+ final Reference reference = newDataSource().getReference();
+ removeAddress(reference, EXPORT_PASSWORD);
+ final DriverAdapterCPDS resolved = resolve(reference);
+ assertTrue(resolved.isExportPasswordAsRefAddr());
+ assertEquals("p1",
resolved.getReference().get("password").getContent());
+ assertCanConnect(resolved);
+ }
+
+ @Test
+ void testLegacySerializedDataSourceRetainsPasswordExport() throws
Exception {
+ final Properties fixture = new Properties();
+ try (InputStream input =
getClass().getResourceAsStream("DriverAdapterCPDS-2.14.0.properties")) {
+ assertNotNull(input);
+ fixture.load(input);
+ }
+ final DriverAdapterCPDS restored =
deserialize(Base64.getDecoder().decode(fixture.getProperty("serializedData")));
+ assertTrue(restored.isExportPasswordAsRefAddr());
+ assertEquals("u1", restored.getUser());
+ assertEquals("p1",
restored.getReference().get("password").getContent());
+ restored.setDriver(TesterDriver.class.getName());
+ assertCanConnect(restored);
+ }
+
+ @Test
+ void testMissingPasswordFailsWithoutChangingSourceCredentials() throws
Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setExportPasswordAsRefAddr(false);
+ final DriverAdapterCPDS resolved = resolve(source.getReference());
+ assertThrows(SQLException.class, resolved::getPooledConnection);
+ // Even an unsuccessful attempt ends the existing initialization phase.
+ assertThrows(IllegalStateException.class, () ->
resolved.setPassword("p1"));
+ assertCanConnect(source);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testPasswordProvisioningBeforePoolInitialization(final boolean
useCharArray) throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setExportPasswordAsRefAddr(false);
+ final DriverAdapterCPDS resolved = resolve(source.getReference());
+ assertNull(resolved.getPassword());
+ if (useCharArray) {
+ resolved.setPassword(new char[] {'p', '1'});
+ } else {
+ resolved.setPassword("p1");
+ }
+ try (SharedPoolDataSource pool = new SharedPoolDataSource()) {
+ pool.setConnectionPoolDataSource(resolved);
+ try (Connection connection = pool.getConnection()) {
+ assertFalse(connection.isClosed());
+ }
+ }
+ assertNull(resolved.getReference().get("password"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("passwordArguments")
+ void testPasswordReferenceContents(final boolean export, final String
password, final int mode) throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setPassword((String) null);
+ switch (mode) {
+ case 0:
+ source.setPassword(password);
+ break;
+ case 1:
+ source.setPassword(password == null ? null :
password.toCharArray());
+ break;
+ default:
+ final Properties properties = new Properties();
+ if (password != null) {
+ properties.setProperty("password", password);
+ }
+ source.setConnectionProperties(mode == 2 ? properties : new
Properties(properties));
+ break;
+ }
+ source.setDescription("reference-test");
+ source.setExportPasswordAsRefAddr(export);
+ final Properties before = source.getConnectionProperties() == null ?
null : (Properties) source.getConnectionProperties().clone();
+ final Reference reference = source.getReference();
+ assertEquals(Boolean.toString(export),
reference.get(EXPORT_PASSWORD).getContent());
+ if (export) {
+ assertNotNull(reference.get("password"));
+ assertEquals(password, reference.get("password").getContent());
+ } else {
+ assertNull(reference.get("password"));
+ }
+ assertEquals(password, source.getPassword());
+ assertArrayEquals(password == null ? null : password.toCharArray(),
source.getPasswordCharArray());
+ assertEquals(before, source.getConnectionProperties());
+ assertEquals(source.getUser(), reference.get("user").getContent());
+ assertEquals(source.getUrl(), reference.get("url").getContent());
+ assertEquals(source.getDriver(), reference.get("driver").getContent());
+ assertEquals(source.getDescription(),
reference.get("description").getContent());
+ final DriverAdapterCPDS resolved = resolve(reference);
+ assertEquals(export ? password : null, resolved.getPassword());
+ assertEquals(export, resolved.isExportPasswordAsRefAddr());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testRebindingPreservesExportSetting(final boolean export) throws
Exception {
+ DriverAdapterCPDS source = newDataSource();
+ source.setExportPasswordAsRefAddr(export);
+ final Context context = new NamingContext(new Hashtable<>(),
"referenceTest");
+ try {
+ context.bind("source", source);
+ for (int i = 0; i < 3; i++) {
+ final DriverAdapterCPDS resolved = (DriverAdapterCPDS)
context.lookup("source");
+ assertNotSame(source, resolved);
+ assertEquals(export, resolved.isExportPasswordAsRefAddr());
+ assertEquals(export ? "p1" : null, resolved.getPassword());
+ resolved.setPassword("p1");
+ assertCanConnect(resolved);
+ assertEquals(export, resolved.getReference().get("password")
!= null);
+ context.rebind("source", resolved);
+ source = resolved;
+ }
+ } finally {
+ context.close();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testSerializationRetainsPolicyAndCredentials(final boolean export)
throws Exception {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setExportPasswordAsRefAddr(export);
+ final DriverAdapterCPDS restored = deserialize(serialize(source));
+ assertNotSame(source, restored);
+ assertEquals(export, restored.isExportPasswordAsRefAddr());
+ assertEquals("p1", restored.getPassword());
+ assertEquals(export, restored.getReference().get("password") != null);
+ assertCanConnect(restored);
+ }
+}
diff --git
a/src/test/resources/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS-2.14.0.properties
b/src/test/resources/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS-2.14.0.properties
new file mode 100644
index 00000000..d2071ec5
--- /dev/null
+++
b/src/test/resources/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS-2.14.0.properties
@@ -0,0 +1,20 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+##
+# Serialized with commons-dbcp2 2.14.0, before the password export option
existed.
+# DriverAdapterCPDS with URL jdbc:apache:commons:testdriver and test
credentials u1/p1.
+serializedData=rO0ABXNyADZvcmcuYXBhY2hlLmNvbW1vbnMuZGJjcDIuY3Bkc2FkYXB0ZXIuRHJpdmVyQWRhcHRlckNQRFO9Gg8n3+YzfAIAD1oAI2FjY2Vzc1RvVW5kZXJseWluZ0Nvbm5lY3Rpb25BbGxvd2VkWgATZ2V0Q29ubmVjdGlvbkNhbGxlZEkADGxvZ2luVGltZW91dEkAB21heElkbGVJABVtYXhQcmVwYXJlZFN0YXRlbWVudHNJABZudW1UZXN0c1BlckV2aWN0aW9uUnVuWgAWcG9vbFByZXBhcmVkU3RhdGVtZW50c0wAFGNvbm5lY3Rpb25Qcm9wZXJ0aWVzdAAWTGphdmEvdXRpbC9Qcm9wZXJ0aWVzO0wAEGNvbm5lY3Rpb25TdHJpbmd0ABJMamF2YS9sYW5nL1N0cmluZztMAAtkZXNjcmlwdGlvbnEAfgACTAAGZHJpdmVycQB+AAJMABtkd
[...]