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 b113a338 Avoid logging ignored JNDI property values (f008)
b113a338 is described below

commit b113a3381b415bb0ecd1d70afe74a3a8a891f603
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 22 09:47:19 2026 -0500

    Avoid logging ignored JNDI property values (f008)
    
    Omit unknown and obsolete property values from BasicDataSourceFactory
    diagnostics while preserving property names, log levels, and migration
    guidance.
    
    Reuse one StringBuilder, resetting it to the JNDI name prefix before
    each message. Add comprehensive regression tests, and document the
    behavior.
---
 src/changes/changes.xml                            |   1 +
 .../commons/dbcp2/BasicDataSourceFactory.java      |  26 ++-
 .../commons/dbcp2/TestBasicDataSourceFactory.java  | 176 +++++++++++++++++++++
 3 files changed, 189 insertions(+), 14 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 80020bb8..7d9425bc 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -75,6 +75,7 @@ The <action> type attribute can be add,update,fix,remove.
       <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>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Expose only 
DataSourceMXBean through DynamicMBean when BasicDataSource is registered 
directly with JMX. Retain the Java password accessor and MXBean reference 
mapping for compatibility. Direct registrations resolve empty domains and 
perform cleanup using their owning MBeanServer. Only one direct registration 
may be active at a time; use separate StandardMBean wrappers explicitly 
selecting DataSourceMXBean for multiple registra [...]
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Extend 
Utils.cloneWithoutCredentials(Properties) to omit 
java.naming.security.principal and java.naming.security.credentials in addition 
to user and password. Use the shared filter for SharedPoolDataSource, 
PerUserPoolDataSource, DriverAdapterCPDS, and DriverConnectionFactory 
diagnostic strings without changing configured properties (f006).</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Omit unknown and 
obsolete JNDI property values from BasicDataSourceFactory diagnostics to avoid 
logging credentials supplied under incorrect property names (f008).</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>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
PoolingDriver.Builder and PoolingDriver.builder() to configure delegate access 
when creating drivers, preserving the existing permissive default.</action>
diff --git a/src/main/java/org/apache/commons/dbcp2/BasicDataSourceFactory.java 
b/src/main/java/org/apache/commons/dbcp2/BasicDataSourceFactory.java
index a6be7dff..ee3b159b 100644
--- a/src/main/java/org/apache/commons/dbcp2/BasicDataSourceFactory.java
+++ b/src/main/java/org/apache/commons/dbcp2/BasicDataSourceFactory.java
@@ -435,7 +435,7 @@ public class BasicDataSourceFactory implements 
ObjectFactory {
 
     /**
      * Collects warnings and info messages. Warnings are generated when an 
obsolete property is set. Unknown properties
-     * generate info messages.
+     * generate info messages. Property values are omitted because they may 
contain credentials supplied under a misspelled property name.
      *
      * @param ref
      *            Reference to check properties of
@@ -446,20 +446,20 @@ public class BasicDataSourceFactory implements 
ObjectFactory {
      * @param infoMessages
      *            container for info messages
      */
-    private void validatePropertyNames(final Reference ref, final Name name, 
final List<String> warnMessages,
-            final List<String> infoMessages) {
-        final String nameString = name != null ? "Name = " + name.toString() + 
" " : "";
-        NUPROP_WARNTEXT.forEach((propertyName, value) -> {
+    private void validatePropertyNames(final Reference ref, final Name name, 
final List<String> warnMessages, final List<String> infoMessages) {
+        final StringBuilder stringBuilder = new StringBuilder();
+        if (name != null) {
+            stringBuilder.append("Name = ").append(name).append(' ');
+        }
+        final int nameLength = stringBuilder.length();
+        NUPROP_WARNTEXT.forEach((propertyName, warningText) -> {
             final RefAddr ra = ref.get(propertyName);
             if (ra != null && !ALL_PROPERTY_NAMES.contains(ra.getType())) {
-                final StringBuilder stringBuilder = new 
StringBuilder(nameString);
-                final String propertyValue = Objects.toString(ra.getContent(), 
null);
-                stringBuilder.append(value).append(" You have set value of 
\"").append(propertyValue).append("\" for \"").append(propertyName)
-                        .append("\" property, which is being ignored.");
+                stringBuilder.setLength(nameLength);
+                stringBuilder.append(warningText).append(" You have set a 
value for \"").append(propertyName).append("\" property, which is being 
ignored.");
                 warnMessages.add(stringBuilder.toString());
             }
         });
-
         final Enumeration<RefAddr> allRefAddrs = ref.getAll();
         while (allRefAddrs.hasMoreElements()) {
             final RefAddr ra = allRefAddrs.nextElement();
@@ -467,10 +467,8 @@ public class BasicDataSourceFactory implements 
ObjectFactory {
             // If property name is not in the properties list, we haven't 
warned on it
             // and it is not in the "silent" list, tell user we are ignoring 
it.
             if (!(ALL_PROPERTY_NAMES.contains(propertyName) || 
NUPROP_WARNTEXT.containsKey(propertyName) || 
SILENT_PROPERTIES.contains(propertyName))) {
-                final String propertyValue = Objects.toString(ra.getContent(), 
null);
-                final StringBuilder stringBuilder = new 
StringBuilder(nameString);
-                stringBuilder.append("Ignoring unknown property: 
").append("value of \"").append(propertyValue).append("\" for 
\"").append(propertyName)
-                        .append("\" property");
+                stringBuilder.setLength(nameLength);
+                stringBuilder.append("Ignoring unknown property: 
\"").append(propertyName).append('"');
                 infoMessages.add(stringBuilder.toString());
             }
         }
diff --git 
a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceFactory.java 
b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceFactory.java
index ac4b9ead..cc67d1e0 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceFactory.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceFactory.java
@@ -20,27 +20,67 @@ package org.apache.commons.dbcp2;
 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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.lang.management.ManagementFactory;
 import java.sql.Connection;
+import java.sql.SQLException;
 import java.time.Duration;
 import java.util.List;
 import java.util.Map.Entry;
 import java.util.Properties;
+import java.util.stream.Stream;
 
 import javax.management.MBeanServer;
+import javax.naming.CompositeName;
+import javax.naming.Name;
+import javax.naming.RefAddr;
 import javax.naming.Reference;
 import javax.naming.StringRefAddr;
 
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.logging.impl.SimpleLog;
 import org.apache.commons.pool2.impl.GenericObjectPool;
 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;
 
 /**
  * TestSuite for BasicDataSourceFactory
  */
 public class TestBasicDataSourceFactory {
 
+    static Stream<Arguments> loggingLevels() {
+        return Stream.of(
+                Arguments.of(SimpleLog.LOG_LEVEL_INFO, 3, 3),
+                Arguments.of(SimpleLog.LOG_LEVEL_WARN, 3, 0),
+                Arguments.of(SimpleLog.LOG_LEVEL_ERROR, 0, 0),
+                Arguments.of(SimpleLog.LOG_LEVEL_OFF, 0, 0));
+    }
+
+    static Stream<Arguments> obsoletePropertyValues() {
+        return Stream.of(
+                new String[] {"maxActive", "use maxTotal instead."},
+                new String[] {"removeAbandoned", "use one or both of 
removeAbandonedOnBorrow or removeAbandonedOnMaintenance instead."},
+                new String[] {"maxWait", "use maxWaitMillis instead."})
+                .flatMap(property -> propertyValues().flatMap(value -> 
Stream.of(false, true)
+                        .map(named -> Arguments.of(property[0], property[1], 
value, named))));
+    }
+
+    private static Stream<String> propertyValues() {
+        return Stream.of(null, "", "secret-password", 
"secret-\"quoted\"\r\nforged-log-entry", "secret-p\u00e4ssw\u00f6rd-\u20ac");
+    }
+
+    static Stream<Arguments> unknownPropertyValues() {
+        return Stream.of("passwd", "pwd", "Password", "password ", "apiToken", 
"customProperty")
+                .flatMap(property -> propertyValues().flatMap(value -> 
Stream.of(false, true)
+                        .map(named -> Arguments.of(property, value, named))));
+    }
+
     private void checkConnectionPoolProperties(final 
GenericObjectPool<PoolableConnection> cp) {
         assertEquals(10, cp.getMaxTotal());
         assertEquals(8, cp.getMaxIdle());
@@ -110,6 +150,20 @@ public class TestBasicDataSourceFactory {
         mbs.unregisterMBean(ds.getRegisteredJmxName());
     }
 
+    private List<String> getMessages(final Reference ref, final Name name) 
throws SQLException {
+        try {
+            StackMessageLog.lock();
+            StackMessageLog.clear();
+            try (final BasicDataSource ds = (BasicDataSource) new 
BasicDataSourceFactory().getObjectInstance(ref, name, null, null)) {
+                assertNotNull(ds);
+                return StackMessageLog.getAll();
+            }
+        } finally {
+            StackMessageLog.clear();
+            StackMessageLog.unLock();
+        }
+    }
+
     private Properties getTestProperties() {
         final Properties properties = new Properties();
         properties.setProperty("driverClassName", 
"org.apache.commons.dbcp2.TesterDriver");
@@ -175,6 +229,80 @@ public class TestBasicDataSourceFactory {
         }
     }
 
+    @ParameterizedTest
+    @CsvSource({"passwd, 1", "customProperty, 1", "maxActive, 1", 
"removeAbandoned, 1", "maxWait, 1",
+            "factory, 0", "scope, 0", "singleton, 0", "auth, 0"})
+    void testIgnoredPropertyContentIsNotAccessed(final String propertyName, 
final int messageCount) throws Exception {
+        final Reference ref = new Reference("javax.sql.DataSource", 
BasicDataSourceFactory.class.getName(), null);
+        ref.add(new RefAddr(propertyName) {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            public Object getContent() {
+                throw new AssertionError("Ignored property content must not be 
accessed");
+            }
+        });
+        final List<String> messages = getMessages(ref, null);
+        assertEquals(messageCount, messages.size(), messages.toString());
+        if (messageCount != 0) {
+            assertTrue(messages.get(0).contains(propertyName), 
messages.toString());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("loggingLevels")
+    void testMixedPropertiesPreserveConfigurationAndLogLevels(final int level, 
final int warningCount, final int infoCount) throws Exception {
+        final StackMessageLog log = (StackMessageLog) 
LogFactory.getLog(BasicDataSourceFactory.class);
+        StackMessageLog.lock();
+        final int originalLevel = log.getLevel();
+        try {
+            StackMessageLog.clear();
+            log.setLevel(level);
+            final Reference ref = new Reference("javax.sql.DataSource", 
BasicDataSourceFactory.class.getName(), null);
+            ref.add(new StringRefAddr("username", "secret-username"));
+            ref.add(new StringRefAddr("password", "secret-password"));
+            ref.add(new StringRefAddr("url", 
"jdbc:apache:commons:testdriver"));
+            ref.add(new StringRefAddr("maxTotal", "17"));
+            ref.add(new StringRefAddr("maxWaitMillis", "123"));
+            ref.add(new StringRefAddr("removeAbandonedOnBorrow", "true"));
+            for (final String property : new String[] {"maxActive", 
"removeAbandoned", "maxWait", "passwd", "customProperty",
+                    "factory", "scope", "singleton", "auth"}) {
+                ref.add(new StringRefAddr(property, "secret-" + property));
+            }
+            ref.add(new StringRefAddr("passwd", "secret-duplicate"));
+            ref.add(new StringRefAddr("maxWait", "secret-duplicate-obsolete"));
+            final Name name = new CompositeName("jdbc/test");
+            try (final BasicDataSource ds = (BasicDataSource) new 
BasicDataSourceFactory().getObjectInstance(ref, name, null, null)) {
+                assertEquals("secret-username", ds.getUsername());
+                assertEquals("secret-password", ds.getPassword());
+                assertEquals("jdbc:apache:commons:testdriver", ds.getUrl());
+                assertEquals(17, ds.getMaxTotal());
+                assertEquals(Duration.ofMillis(123), ds.getMaxWaitDuration());
+                assertTrue(ds.getRemoveAbandonedOnBorrow());
+                assertNull(ds.getConnectionPool());
+                final List<String> messages = StackMessageLog.getAll();
+                assertEquals(warningCount + infoCount, messages.size(), 
messages.toString());
+                assertEquals(warningCount, messages.stream().filter(message -> 
message.startsWith("Name = jdbc/test Property ")).count());
+                assertEquals(infoCount, messages.stream().filter(message -> 
message.startsWith("Name = jdbc/test Ignoring unknown property: ")).count());
+                if (warningCount != 0) {
+                    assertTrue(messages.get(0).startsWith("Name = jdbc/test 
Property maxActive "), messages.toString());
+                    assertTrue(messages.get(1).startsWith("Name = jdbc/test 
Property removeAbandoned "), messages.toString());
+                    assertTrue(messages.get(2).startsWith("Name = jdbc/test 
Property maxWait "), messages.toString());
+                }
+                if (infoCount != 0) {
+                    assertEquals("Name = jdbc/test Ignoring unknown property: 
\"passwd\"", messages.get(3));
+                    assertEquals("Name = jdbc/test Ignoring unknown property: 
\"customProperty\"", messages.get(4));
+                    assertEquals("Name = jdbc/test Ignoring unknown property: 
\"passwd\"", messages.get(5));
+                }
+                messages.forEach(message -> 
assertFalse(message.contains("secret-"), message));
+            }
+        } finally {
+            log.setLevel(originalLevel);
+            StackMessageLog.clear();
+            StackMessageLog.unLock();
+        }
+    }
+
     @Test
     void testNoProperties() throws Exception {
         final Properties properties = new Properties();
@@ -183,6 +311,23 @@ public class TestBasicDataSourceFactory {
         }
     }
 
+    @ParameterizedTest
+    @MethodSource("obsoletePropertyValues")
+    void testObsoletePropertyValuesAreNotLogged(final String propertyName, 
final String guidance, final String value,
+            final boolean named) throws Exception {
+        final Reference ref = new Reference("javax.sql.DataSource", 
BasicDataSourceFactory.class.getName(), null);
+        ref.add(new StringRefAddr(propertyName, value));
+        final List<String> messages = getMessages(ref, named ? new 
CompositeName("jdbc/test") : null);
+        assertEquals(1, messages.size(), messages.toString());
+        final String message = messages.get(0);
+        assertTrue(message.startsWith((named ? "Name = jdbc/test " : "") + 
"Property " + propertyName + " is not used in DBCP2"), message);
+        assertTrue(message.contains(guidance), message);
+        assertTrue(message.endsWith("You have set a value for \"" + 
propertyName + "\" property, which is being ignored."), message);
+        if (value != null && !value.isEmpty()) {
+            assertFalse(message.contains(value), message);
+        }
+    }
+
     @Test
     void testProperties() throws Exception {
         try (final BasicDataSource ds = 
BasicDataSourceFactory.createDataSource(getTestProperties())) {
@@ -190,6 +335,16 @@ public class TestBasicDataSourceFactory {
         }
     }
 
+    @ParameterizedTest
+    @MethodSource("unknownPropertyValues")
+    void testUnknownPropertyValuesAreNotLogged(final String propertyName, 
final String value, final boolean named) throws Exception {
+        final Reference ref = new Reference("javax.sql.DataSource", 
BasicDataSourceFactory.class.getName(), null);
+        ref.add(new StringRefAddr(propertyName, value));
+        final List<String> messages = getMessages(ref, named ? new 
CompositeName("jdbc/test") : null);
+        assertEquals(1, messages.size(), messages.toString());
+        assertEquals((named ? "Name = jdbc/test " : "") + "Ignoring unknown 
property: \"" + propertyName + "\"", messages.get(0));
+    }
+
     @Test
     void testValidateProperties() throws Exception {
         try {
@@ -216,4 +371,25 @@ public class TestBasicDataSourceFactory {
             StackMessageLog.unLock();
         }
     }
+
+    @Test
+    void testValuesAreNotLoggedWhenDataSourceCreationFails() {
+        try {
+            StackMessageLog.lock();
+            StackMessageLog.clear();
+            final Reference ref = new Reference("javax.sql.DataSource", 
BasicDataSourceFactory.class.getName(), null);
+            ref.add(new StringRefAddr("passwd", "secret-password"));
+            ref.add(new StringRefAddr("maxWait", "secret-obsolete"));
+            ref.add(new StringRefAddr("maxTotal", "invalid-integer"));
+            assertThrows(NumberFormatException.class, () -> new 
BasicDataSourceFactory().getObjectInstance(ref, null, null, null));
+            final List<String> messages = StackMessageLog.getAll();
+            assertEquals(2, messages.size(), messages.toString());
+            assertTrue(messages.get(0).contains("use maxWaitMillis instead."), 
messages.toString());
+            assertEquals("Ignoring unknown property: \"passwd\"", 
messages.get(1));
+            messages.forEach(message -> 
assertFalse(message.contains("secret-"), message));
+        } finally {
+            StackMessageLog.clear();
+            StackMessageLog.unLock();
+        }
+    }
 }

Reply via email to