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 7b773fbb Centralize JDBC and JNDI credential redaction (f006) (#558)
7b773fbb is described below

commit 7b773fbbcbbba722995d637e3fbafd6b9decf386
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 22 07:34:31 2026 -0500

    Centralize JDBC and JNDI credential redaction (f006) (#558)
    
    Extend Utils.cloneWithoutCredentials() to remove JNDI principal and
    credentials alongside user and password. Reuse the filter for datasource
    diagnostics without modifying configured properties.
    
    Document all four filtered keys and shallow-clone behavior. Add focused
    utility and caller tests covering redaction, configuration preservation,
    and continued JDBC/JNDI access.
---
 src/changes/changes.xml                            |   3 +-
 src/main/java/org/apache/commons/dbcp2/Utils.java  |  30 +-
 .../dbcp2/datasources/InstanceKeyDataSource.java   |  20 +-
 .../commons/dbcp2/TestCredentialRedaction.java     | 366 +++++++++++++++++++++
 .../TestInstanceKeyDataSourceToString.java         | 287 ++++++++++++++++
 5 files changed, 701 insertions(+), 5 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 0704ee2f..f5676717 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -72,7 +72,8 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Apply 
accessToUnderlyingConnectionAllowed consistently to delegate getters and JDBC 
unwrap/isWrapperFor on connections, statements, result sets, and database 
metadata. Internal pool access remains available. Applications requiring 
vendor-specific delegate access must enable this property; configure 
BasicDataSource before pool initialization.</action>
       <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>
-      <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">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>
       <!-- 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 -->
diff --git a/src/main/java/org/apache/commons/dbcp2/Utils.java 
b/src/main/java/org/apache/commons/dbcp2/Utils.java
index ebe0cce5..f8b93cfc 100644
--- a/src/main/java/org/apache/commons/dbcp2/Utils.java
+++ b/src/main/java/org/apache/commons/dbcp2/Utils.java
@@ -33,6 +33,8 @@ import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Predicate;
 
+import javax.naming.Context;
+
 import org.apache.commons.pool2.PooledObject;
 
 /**
@@ -131,10 +133,30 @@ public final class Utils {
     }
 
     /**
-     * Clones the given {@link Properties} without the standard "user" or 
"password" entries.
+     * Clones the given {@link Properties} without standard credential entries.
+     *
+     * <p>
+     * Removes direct entries with the following exact, case-sensitive keys 
from the clone:
+     * </p>
+     * <ul>
+     * <li>{@code user}</li>
+     * <li>{@code password}</li>
+     * <li>{@link Context#SECURITY_PRINCIPAL 
java.naming.security.principal}</li>
+     * <li>{@link Context#SECURITY_CREDENTIALS 
java.naming.security.credentials}</li>
+     * </ul>
+     *
+     * <p>
+     * The input is unchanged. This is a shallow clone: other entries, 
including provider-specific credential keys, are retained without filtering.
+     * Inherited defaults remain shared with the input, including any 
credential defaults. Defaults are not included in {@link Properties#toString()},
+     * but remain accessible through {@link Properties#getProperty(String)}.
+     * </p>
+     *
+     * <p>
+     * Removal of the two JNDI entries was added in 2.15.0.
+     * </p>
      *
-     * @param properties may be null
-     * @return A clone of the input without the standard "user" or "password" 
entries.
+     * @param properties the properties to clone, may be null.
+     * @return a shallow clone without the four direct credential entries, or 
null if the input is null.
      * @since 2.8.0
      */
     public static Properties cloneWithoutCredentials(final Properties 
properties) {
@@ -142,6 +164,8 @@ public final class Utils {
             final Properties temp = (Properties) properties.clone();
             temp.remove(Constants.KEY_USER);
             temp.remove(Constants.KEY_PASSWORD);
+            temp.remove(Context.SECURITY_PRINCIPAL);
+            temp.remove(Context.SECURITY_CREDENTIALS);
             return temp;
         }
         return properties;
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
index ad6925bf..8549ecbd 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
@@ -1295,6 +1295,24 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
     }
 
     /**
+     * Builds a diagnostic string with standard JNDI environment credentials 
omitted.
+     *
+     * <p>
+     * The JNDI environment omits the following exact, case-sensitive keys 
using {@link Utils#cloneWithoutCredentials(Properties)}:
+     * </p>
+     * <ul>
+     * <li>{@code user}</li>
+     * <li>{@code password}</li>
+     * <li>{@link Context#SECURITY_PRINCIPAL 
java.naming.security.principal}</li>
+     * <li>{@link Context#SECURITY_CREDENTIALS 
java.naming.security.credentials}</li>
+     * </ul>
+     *
+     * <p>
+     * The configured environment is unchanged. This does not provide general 
redaction of other environment entries, including provider-specific credential
+     * keys, or other datasource fields.
+     * </p>
+     *
+     * @return a diagnostic string for this datasource.
      * @since 2.6.0
      */
     @Override
@@ -1321,7 +1339,7 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
         builder.append(", description=");
         builder.append(description);
         builder.append(", jndiEnvironment=");
-        builder.append(jndiEnvironment);
+        builder.append(Utils.cloneWithoutCredentials(jndiEnvironment));
         builder.append(", loginTimeoutDuration=");
         builder.append(loginTimeoutDuration);
         builder.append(", logWriter=");
diff --git 
a/src/test/java/org/apache/commons/dbcp2/TestCredentialRedaction.java 
b/src/test/java/org/apache/commons/dbcp2/TestCredentialRedaction.java
new file mode 100644
index 00000000..ff27d210
--- /dev/null
+++ b/src/test/java/org/apache/commons/dbcp2/TestCredentialRedaction.java
@@ -0,0 +1,366 @@
+/*
+ * 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;
+
+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.assertTrue;
+
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.function.Supplier;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import javax.naming.Context;
+import javax.sql.PooledConnection;
+
+import org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS;
+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.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests the shared credential filter and JDBC callers that use it for 
diagnostic output.
+ */
+class TestCredentialRedaction {
+
+    private enum Caller {
+        DRIVER_ADAPTER,
+        DRIVER_CONNECTION_FACTORY;
+
+        Supplier<String> renderer(final Properties properties) {
+            if (this == DRIVER_ADAPTER) {
+                final DriverAdapterCPDS dataSource = new DriverAdapterCPDS();
+                dataSource.setConnectionProperties(properties);
+                return dataSource::toString;
+            }
+            final DriverConnectionFactory factory = new 
DriverConnectionFactory(new TesterDriver(), "jdbc:apache:commons:testdriver", 
properties);
+            return factory::toString;
+        }
+
+        String segment(final String properties) {
+            return this == DRIVER_ADAPTER ? ", connectionProperties=" + 
properties + "," : ";" + properties + "]";
+        }
+    }
+
+    private enum CredentialValue {
+        EMPTY_STRING,
+        STRING,
+        CHAR_ARRAY,
+        BYTE_ARRAY,
+        OBJECT;
+
+        Object create(final String key) {
+            final String value = "secret-for-" + key + "-=,{}[]\n\u00e9";
+            switch (this) {
+            case EMPTY_STRING:
+                return "";
+            case STRING:
+                return value;
+            case CHAR_ARRAY:
+                return value.toCharArray();
+            case BYTE_ARRAY:
+                return value.getBytes(StandardCharsets.UTF_8);
+            default:
+                return new Object() {
+                    @Override
+                    public String toString() {
+                        throw new AssertionError("Credential values must not 
be stringified.");
+                    }
+                };
+            }
+        }
+    }
+
+    private static final class RecordingDriver extends TesterDriver implements 
AutoCloseable {
+
+        private final String url = "jdbc:apache:commons:credential-redaction:" 
+ UUID.randomUUID();
+        private final TesterDriver delegate = new TesterDriver();
+        private Properties received;
+
+        RecordingDriver() throws SQLException {
+            DriverManager.registerDriver(this);
+        }
+
+        @Override
+        public boolean acceptsURL(final String connectionUrl) {
+            return url.equals(connectionUrl);
+        }
+
+        @Override
+        public void close() throws SQLException {
+            DriverManager.deregisterDriver(this);
+        }
+
+        @Override
+        public Connection connect(final String connectionUrl, final Properties 
properties) throws SQLException {
+            if (!acceptsURL(connectionUrl)) {
+                return null;
+            }
+            received = (Properties) properties.clone();
+            return delegate.connect("jdbc:apache:commons:testdriver", 
properties);
+        }
+    }
+
+    private static final List<String> CREDENTIAL_KEYS = Arrays.asList("user", 
"password", Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS);
+    private static final int ALL_CREDENTIALS = (1 << CREDENTIAL_KEYS.size()) - 
1;
+
+    private static void assertDiagnostics(final Supplier<String> renderer, 
final Properties properties) {
+        final Properties original = (Properties) properties.clone();
+        for (int repeat = 0; repeat < 2; repeat++) {
+            final String text = renderer.get();
+            for (final String key : CREDENTIAL_KEYS) {
+                assertFalse(text.contains("{" + key + "=") || text.contains(", 
" + key + "="), key);
+                final String value = properties.getProperty(key);
+                if (value != null && !value.isEmpty()) {
+                    assertFalse(text.contains(value), key);
+                }
+            }
+            for (final String key : properties.stringPropertyNames()) {
+                if (properties.containsKey(key) && 
!CREDENTIAL_KEYS.contains(key)) {
+                    assertTrue(text.contains(key + "=" + 
properties.getProperty(key)), key);
+                }
+            }
+            assertEquals(original, properties);
+            original.forEach((key, value) -> assertSame(value, 
properties.get(key), key.toString()));
+        }
+    }
+
+    private static Properties credentialProperties(final CredentialValue 
value, final int mask) {
+        final Properties properties = visibleProperties();
+        for (int index = 0; index < CREDENTIAL_KEYS.size(); index++) {
+            if ((mask & 1 << index) != 0) {
+                final String key = CREDENTIAL_KEYS.get(index);
+                properties.put(key, value.create(key));
+            }
+        }
+        return properties;
+    }
+
+    static Stream<Arguments> utilityCases() {
+        // With no credential keys, the value type does not affect the input.
+        return Stream.concat(Stream.of(Arguments.of(CredentialValue.STRING, 
0)), Arrays.stream(CredentialValue.values())
+                .flatMap(value -> IntStream.rangeClosed(1, 
ALL_CREDENTIALS).mapToObj(mask -> Arguments.of(value, mask))));
+    }
+
+    private static Properties visibleProperties() {
+        final Properties properties = new Properties();
+        properties.setProperty("ApplicationName", "diagnostic-app");
+        properties.setProperty("socketTimeout", "123");
+        return properties;
+    }
+
+    @ParameterizedTest
+    @EnumSource(Caller.class)
+    void testCallerConnectionAfterDiagnostics(final Caller caller) throws 
Exception {
+        try (final RecordingDriver driver = new RecordingDriver()) {
+            final Properties properties = 
credentialProperties(CredentialValue.STRING, ALL_CREDENTIALS);
+            properties.setProperty("user", "foo");
+            properties.setProperty("password", "bar");
+            final Properties original = (Properties) properties.clone();
+            if (caller == Caller.DRIVER_ADAPTER) {
+                final DriverAdapterCPDS dataSource = new DriverAdapterCPDS();
+                dataSource.setUrl(driver.url);
+                dataSource.setConnectionProperties(properties);
+                assertDiagnostics(dataSource::toString, properties);
+                final PooledConnection pooled = 
dataSource.getPooledConnection();
+                try (final Connection connection = pooled.getConnection()) {
+                    assertFalse(connection.isClosed());
+                } finally {
+                    pooled.close();
+                }
+                assertDiagnostics(dataSource::toString, properties);
+                assertSame(properties, dataSource.getConnectionProperties());
+            } else {
+                final DriverConnectionFactory factory = new 
DriverConnectionFactory(driver, driver.url, properties);
+                assertDiagnostics(factory::toString, properties);
+                try (final Connection connection = factory.createConnection()) 
{
+                    assertNotNull(connection);
+                    assertFalse(connection.isClosed());
+                }
+                assertDiagnostics(factory::toString, properties);
+                assertSame(properties, factory.getProperties());
+            }
+            assertEquals(original, driver.received);
+            assertEquals(original, properties);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Caller.class)
+    void testCallerInheritedDefaults(final Caller caller) {
+        final Properties defaults = 
credentialProperties(CredentialValue.STRING, ALL_CREDENTIALS);
+        final Properties originalDefaults = (Properties) defaults.clone();
+        final Properties properties = new Properties(defaults);
+        properties.setProperty("ApplicationName", "explicit-app");
+        final Supplier<String> renderer = caller.renderer(properties);
+        assertDiagnostics(renderer, properties);
+        assertFalse(renderer.get().contains("socketTimeout="));
+        for (final String key : CREDENTIAL_KEYS) {
+            assertEquals(defaults.getProperty(key), 
properties.getProperty(key), key);
+        }
+        assertEquals(originalDefaults, defaults);
+    }
+
+    @ParameterizedTest
+    @EnumSource(Caller.class)
+    void testCallerNonStringCredentials(final Caller caller) {
+        final Properties properties = 
credentialProperties(CredentialValue.OBJECT, ALL_CREDENTIALS);
+        assertDiagnostics(caller.renderer(properties), properties);
+    }
+
+    @ParameterizedTest
+    @EnumSource(Caller.class)
+    void testCallerNullAndEmptyProperties(final Caller caller) {
+        
assertTrue(caller.renderer(null).get().contains(caller.segment("null")));
+        final Properties properties = new Properties();
+        final Supplier<String> renderer = caller.renderer(properties);
+        assertTrue(renderer.get().contains(caller.segment("{}")));
+        assertDiagnostics(renderer, properties);
+    }
+
+    @ParameterizedTest
+    @EnumSource(Caller.class)
+    void testCallerReflectsPropertyUpdates(final Caller caller) {
+        final Properties properties = 
credentialProperties(CredentialValue.STRING, ALL_CREDENTIALS);
+        final Supplier<String> renderer = caller.renderer(properties);
+        assertDiagnostics(renderer, properties);
+        CREDENTIAL_KEYS.forEach(key -> properties.setProperty(key, 
"updated-secret-" + key));
+        properties.setProperty("ApplicationName", "updated-app");
+        assertDiagnostics(renderer, properties);
+        properties.clear();
+        assertTrue(renderer.get().contains(caller.segment("{}")));
+        assertDiagnostics(renderer, properties);
+    }
+
+    @ParameterizedTest
+    @EnumSource(Caller.class)
+    void testCallerWithoutCredentials(final Caller caller) {
+        final Properties properties = visibleProperties();
+        properties.setProperty("provider.password", "retained-option");
+        assertDiagnostics(caller.renderer(properties), properties);
+    }
+
+    @Test
+    void testCloneContainersAreIndependent() {
+        final Properties properties = 
credentialProperties(CredentialValue.STRING, ALL_CREDENTIALS);
+        final Properties first = Utils.cloneWithoutCredentials(properties);
+        final Properties second = Utils.cloneWithoutCredentials(properties);
+        assertNotSame(first, second);
+        first.setProperty("ApplicationName", "first-clone");
+        properties.setProperty("socketTimeout", "456");
+        assertEquals("diagnostic-app", 
properties.getProperty("ApplicationName"));
+        assertEquals("diagnostic-app", second.getProperty("ApplicationName"));
+        assertEquals("123", first.getProperty("socketTimeout"));
+        assertEquals("123", second.getProperty("socketTimeout"));
+        assertEquals(visibleProperties(), second);
+    }
+
+    @ParameterizedTest(name = "value={0}, credentialMask={1}")
+    @MethodSource("utilityCases")
+    void testCloneEveryCredentialCombination(final CredentialValue value, 
final int mask) {
+        final Properties properties = credentialProperties(value, mask);
+        final Properties original = (Properties) properties.clone();
+        final Properties filtered = Utils.cloneWithoutCredentials(properties);
+        assertNotSame(properties, filtered);
+        for (final String key : CREDENTIAL_KEYS) {
+            assertFalse(filtered.containsKey(key), key);
+        }
+        assertEquals(visibleProperties(), filtered);
+        assertEquals(original, properties);
+        original.forEach((key, item) -> assertSame(item, properties.get(key), 
key.toString()));
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testCloneInheritedDefaultsRemainShared(final boolean 
overrideCredentials) {
+        final Properties defaults = 
credentialProperties(CredentialValue.STRING, ALL_CREDENTIALS);
+        final Properties originalDefaults = (Properties) defaults.clone();
+        final Properties properties = new Properties(defaults);
+        if (overrideCredentials) {
+            CREDENTIAL_KEYS.forEach(key -> properties.setProperty(key, 
"direct-secret-" + key));
+        }
+        properties.setProperty("ApplicationName", "explicit-app");
+        final Properties original = (Properties) properties.clone();
+        final Properties filtered = Utils.cloneWithoutCredentials(properties);
+        assertEquals(1, filtered.size());
+        assertEquals("explicit-app", filtered.getProperty("ApplicationName"));
+        for (final String key : CREDENTIAL_KEYS) {
+            assertFalse(filtered.containsKey(key), key);
+            assertEquals(defaults.getProperty(key), filtered.getProperty(key), 
key);
+            
assertFalse(filtered.toString().contains(defaults.getProperty(key)), key);
+        }
+        assertEquals(original, properties);
+        assertEquals(originalDefaults, defaults);
+        defaults.setProperty("socketTimeout", "789");
+        assertEquals("789", properties.getProperty("socketTimeout"));
+        assertEquals("789", filtered.getProperty("socketTimeout"));
+    }
+
+    @Test
+    void testCloneNullAndEmptyProperties() {
+        assertNull(Utils.cloneWithoutCredentials(null));
+        final Properties properties = new Properties();
+        final Properties filtered = Utils.cloneWithoutCredentials(properties);
+        assertNotSame(properties, filtered);
+        assertTrue(filtered.isEmpty());
+        filtered.setProperty("option", "value");
+        assertTrue(properties.isEmpty());
+    }
+
+    @Test
+    void testCloneRetainsOtherObjectEntries() {
+        final Properties properties = 
credentialProperties(CredentialValue.OBJECT, ALL_CREDENTIALS);
+        final Object key = new Object();
+        final Object value = new Object();
+        properties.put(key, value);
+        properties.put("opaque-option", value);
+        final Properties filtered = Utils.cloneWithoutCredentials(properties);
+        assertSame(value, filtered.get(key));
+        assertSame(value, filtered.get("opaque-option"));
+        assertSame(value, properties.get(key));
+        assertEquals(4, filtered.size());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"user", "password", Context.SECURITY_PRINCIPAL, 
Context.SECURITY_CREDENTIALS})
+    void testExactKeyMatching(final String credentialKey) {
+        final Properties properties = 
credentialProperties(CredentialValue.STRING, ALL_CREDENTIALS);
+        final Properties expected = visibleProperties();
+        for (final String key : 
Arrays.asList(credentialKey.toUpperCase(Locale.ROOT), "provider." + 
credentialKey, credentialKey + ".extra")) {
+            properties.setProperty(key, "retained-option");
+            expected.setProperty(key, "retained-option");
+        }
+        assertEquals(expected, Utils.cloneWithoutCredentials(properties));
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/dbcp2/datasources/TestInstanceKeyDataSourceToString.java
 
b/src/test/java/org/apache/commons/dbcp2/datasources/TestInstanceKeyDataSourceToString.java
new file mode 100644
index 00000000..46dd9f48
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/dbcp2/datasources/TestInstanceKeyDataSourceToString.java
@@ -0,0 +1,287 @@
+/*
+ * 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.datasources;
+
+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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Properties;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.naming.spi.InitialContextFactory;
+
+import org.apache.commons.dbcp2.TesterDriver;
+import org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Tests JNDI credential redaction in datasource diagnostic strings and 
exception messages.
+ */
+public class TestInstanceKeyDataSourceToString {
+
+    /**
+     * Checks that diagnostic rendering preserves the credentials supplied to 
JNDI.
+     */
+    public static final class CredentialCheckingContextFactory implements 
InitialContextFactory {
+
+        /**
+         * Constructs a factory for JNDI to instantiate reflectively.
+         */
+        public CredentialCheckingContextFactory() {
+        }
+
+        @Override
+        public Context getInitialContext(final Hashtable<?, ?> environment) 
throws NamingException {
+            for (final String key : CREDENTIAL_KEYS) {
+                assertEquals(credentialValue(key), environment.get(key), key);
+            }
+            final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
+            try {
+                cpds.setDriver(TesterDriver.class.getName());
+            } catch (final ClassNotFoundException e) {
+                final NamingException exception = new NamingException("Cannot 
load the test JDBC driver.");
+                exception.initCause(e);
+                throw exception;
+            }
+            cpds.setUrl("jdbc:apache:commons:testdriver");
+            cpds.setUser("foo");
+            cpds.setPassword("bar");
+            return new InitialContext(true) {
+                @Override
+                public Object lookup(final String name) {
+                    assertEquals("testCPDS", name);
+                    return cpds;
+                }
+            };
+        }
+    }
+
+    private enum DataSourceType {
+        PER_USER(PerUserPoolDataSource::new),
+        SHARED(SharedPoolDataSource::new);
+
+        private final Supplier<InstanceKeyDataSource> factory;
+
+        DataSourceType(final Supplier<InstanceKeyDataSource> factory) {
+            this.factory = factory;
+        }
+
+        InstanceKeyDataSource create() {
+            return factory.get();
+        }
+    }
+
+    private static final List<String> CREDENTIAL_KEYS = Arrays.asList("user", 
"password", Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS);
+
+    private static void assertDiagnostics(final InstanceKeyDataSource 
dataSource, final Properties environment) {
+        for (int repeat = 0; repeat < 2; repeat++) {
+            assertRedacted(dataSource.toString(), environment);
+            assertEnvironmentUnchanged(dataSource, environment);
+        }
+        final SQLException exception = assertThrows(SQLException.class, () -> 
dataSource.unwrap(Runnable.class));
+        assertTrue(exception.getMessage().contains("is not a wrapper for"));
+        assertRedacted(exception.getMessage(), environment);
+        assertEnvironmentUnchanged(dataSource, environment);
+    }
+
+    private static void assertEnvironmentUnchanged(final InstanceKeyDataSource 
dataSource, final Properties environment) {
+        for (final String key : CREDENTIAL_KEYS) {
+            assertEquals(environment.getProperty(key), 
dataSource.getJndiEnvironment(key), key);
+        }
+        for (final String key : environment.stringPropertyNames()) {
+            assertEquals(environment.getProperty(key), 
dataSource.getJndiEnvironment(key), key);
+        }
+    }
+
+    private static void assertRedacted(final String text, final Properties 
environment) {
+        assertTrue(text.contains(", jndiEnvironment="));
+        for (final String key : CREDENTIAL_KEYS) {
+            assertFalse(text.contains(key + "="), key);
+            final String value = environment.getProperty(key);
+            if (value != null && !value.isEmpty()) {
+                assertFalse(text.contains(value), key);
+            }
+        }
+        for (final String key : environment.stringPropertyNames()) {
+            if (!CREDENTIAL_KEYS.contains(key)) {
+                assertTrue(text.contains(key + "=" + 
environment.getProperty(key)), key);
+            }
+        }
+    }
+
+    private static String credentialValue(final String key) {
+        return "secret-for-" + key + "-with-=,{}[]\n\u00e9";
+    }
+
+    private static Properties environment() {
+        final Properties properties = new Properties();
+        properties.setProperty(Context.PROVIDER_URL, 
"ldap://directory.invalid:389";);
+        properties.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
+        properties.setProperty(Context.SECURITY_PROTOCOL, "ssl");
+        for (final String key : CREDENTIAL_KEYS) {
+            properties.setProperty(key, credentialValue(key));
+        }
+        return properties;
+    }
+
+    static Stream<Arguments> environmentSetters() {
+        return Arrays.stream(DataSourceType.values()).flatMap(type -> 
Stream.of(false, true).map(bulk -> Arguments.of(type, bulk)));
+    }
+
+    private static void setEnvironment(final InstanceKeyDataSource dataSource, 
final Properties environment, final boolean bulk) {
+        if (bulk) {
+            dataSource.setJndiEnvironment(environment);
+        } else {
+            for (final String key : environment.stringPropertyNames()) {
+                dataSource.setJndiEnvironment(key, 
environment.getProperty(key));
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("environmentSetters")
+    void testDiagnosticsPreserveJndiLookup(final DataSourceType type, final 
boolean bulk) throws Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            final Properties properties = environment();
+            properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, 
CredentialCheckingContextFactory.class.getName());
+            final Properties original = (Properties) properties.clone();
+            setEnvironment(dataSource, properties, bulk);
+            dataSource.setDataSourceName("testCPDS");
+            assertDiagnostics(dataSource, original);
+            assertNotNull(dataSource.testCPDS(null, null));
+            assertDiagnostics(dataSource, original);
+            assertEquals(original, properties);
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("environmentSetters")
+    void testToStringEmptyCredentials(final DataSourceType type, final boolean 
bulk) throws Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            final Properties properties = new Properties();
+            CREDENTIAL_KEYS.forEach(key -> properties.setProperty(key, ""));
+            setEnvironment(dataSource, properties, bulk);
+            assertDiagnostics(dataSource, properties);
+            assertTrue(dataSource.toString().contains(", 
jndiEnvironment={},"));
+            assertEquals(CREDENTIAL_KEYS.size(), properties.size());
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(DataSourceType.class)
+    void testToStringNonStringCredentials(final DataSourceType type) throws 
Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            final Object secret = new Object() {
+                @Override
+                public String toString() {
+                    throw new AssertionError("Credential values must not be 
stringified.");
+                }
+            };
+            final Properties properties = new Properties();
+            CREDENTIAL_KEYS.forEach(key -> properties.put(key, secret));
+            dataSource.setJndiEnvironment(properties);
+            assertTrue(dataSource.toString().contains(", 
jndiEnvironment={},"));
+            final SQLException exception = assertThrows(SQLException.class, () 
-> dataSource.unwrap(Runnable.class));
+            assertTrue(exception.getMessage().contains(", 
jndiEnvironment={},"));
+            for (final String key : CREDENTIAL_KEYS) {
+                assertSame(secret, properties.get(key));
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(DataSourceType.class)
+    void testToStringNullAndEmptyEnvironment(final DataSourceType type) throws 
Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            assertTrue(dataSource.toString().contains(", 
jndiEnvironment=null,"));
+            assertDiagnostics(dataSource, new Properties());
+            dataSource.setJndiEnvironment(new Properties());
+            assertTrue(dataSource.toString().contains(", 
jndiEnvironment={},"));
+            assertDiagnostics(dataSource, new Properties());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("environmentSetters")
+    void testToStringReflectsEnvironmentUpdates(final DataSourceType type, 
final boolean bulk) throws Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            final Properties properties = environment();
+            setEnvironment(dataSource, properties, bulk);
+            assertDiagnostics(dataSource, properties);
+            CREDENTIAL_KEYS.forEach(key -> properties.setProperty(key, 
"updated-" + credentialValue(key)));
+            properties.setProperty(Context.PROVIDER_URL, 
"ldap://updated.invalid:389";);
+            setEnvironment(dataSource, properties, bulk);
+            assertDiagnostics(dataSource, properties);
+            dataSource.setJndiEnvironment(new Properties());
+            assertTrue(dataSource.toString().contains(", 
jndiEnvironment={},"));
+            assertDiagnostics(dataSource, new Properties());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("environmentSetters")
+    void testToStringRetainsOtherKeys(final DataSourceType type, final boolean 
bulk) throws Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            final Properties properties = new Properties();
+            for (final String key : Arrays.asList("provider.password", 
"credentials", "User", "Password", "JAVA.NAMING.SECURITY.CREDENTIALS",
+                    "java.naming.security.credentials.extra", 
Context.SECURITY_AUTHENTICATION, Context.SECURITY_PROTOCOL)) {
+                properties.setProperty(key, "retained-value");
+            }
+            setEnvironment(dataSource, properties, bulk);
+            final String text = dataSource.toString();
+            final SQLException exception = assertThrows(SQLException.class, () 
-> dataSource.unwrap(Runnable.class));
+            for (final String key : properties.stringPropertyNames()) {
+                assertTrue(text.contains(key + "=retained-value"), key);
+                assertTrue(exception.getMessage().contains(key + 
"=retained-value"), key);
+            }
+            assertEnvironmentUnchanged(dataSource, properties);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(DataSourceType.class)
+    void testToStringWithConnectionPoolDataSource(final DataSourceType type) 
throws Exception {
+        try (final InstanceKeyDataSource dataSource = type.create()) {
+            final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
+            cpds.setDriver(TesterDriver.class.getName());
+            cpds.setUrl("jdbc:apache:commons:testdriver");
+            cpds.setUser("foo");
+            cpds.setPassword("bar");
+            cpds.setPoolPreparedStatements(false);
+            dataSource.setConnectionPoolDataSource(cpds);
+            final Properties properties = environment();
+            setEnvironment(dataSource, properties, false);
+            assertDiagnostics(dataSource, properties);
+        }
+    }
+}

Reply via email to