From c10e9f7f03fe2e3cc1e5252f851b2bc1438d8a9e Mon Sep 17 00:00:00 2001 From: Rehema Owino Date: Mon, 22 Jun 2026 14:22:12 +0300 Subject: [PATCH] Reuse the pooled LDAP admin connection instead of re-binding per operation Closes #50201 Signed-off-by: Rehema Owino --- .../idm/store/ldap/LDAPContextManager.java | 57 +++++++++--- .../store/ldap/LDAPContextManagerTest.java | 86 +++++++++++++++++++ 2 files changed, 131 insertions(+), 12 deletions(-) create mode 100644 federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManagerTest.java diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManager.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManager.java index d71f97f66f8..47b2e1db4ca 100644 --- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManager.java +++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManager.java @@ -50,10 +50,14 @@ private void createLdapContext() throws NamingException { var tracing = session.getProvider(TracingProvider.class); tracing.startSpan(LDAPContextManager.class, "createLdapContext"); try { - // Create the LDAP context without setting the security principal and credentials yet. - // This avoids triggering an automatic bind request, allowing us to send an optional StartTLS request before binding. Hashtable connProp = getNonAuthConnectionProperties(ldapConfig); + // Without StartTLS, bind via the initial env so the pooled connection is reused, not re-bound per operation + // With StartTLS the bind is deferred until after the negotiation + if (!ldapConfig.isStartTls()) { + setAuthConnectionProperties(connProp, ldapConfig, getBindPassword()); + } + if (ldapConfig.isConnectionTrace()) { connProp.put(LDAPConstants.CONNECTION_TRACE_BER, System.err); } @@ -74,6 +78,9 @@ private void createLdapContext() throws NamingException { if (tlsResponse == null) { throw new NamingException("Wasn't able to establish LDAP connection through StartTLS"); } + + // StartTLS must complete before authenticating, so bind only now. + setAdminConnectionAuthProperties(ldapContext); } } catch (NamingException e) { tracing.error(e); @@ -82,8 +89,6 @@ private void createLdapContext() throws NamingException { tracing.endSpan(); } - setAdminConnectionAuthProperties(ldapContext); - // Bind will be automatically called when operations are executed on the context, // or it can be explicitly called by invoking the reconnect() method (e.g., authentication test in LDAPServerCapabilitiesManager.testLDAP()). } @@ -116,6 +121,27 @@ public static StartTlsResponse startTLS(LdapContext ldapContext, SSLSocketFactor return tls; } + // Fill auth properties into the initial connection env so the bound connection can be pooled and reused. + static void setAuthConnectionProperties(Hashtable connProp, LDAPConfig ldapConfig, String bindPassword) { + String authType = ldapConfig.getAuthType(); + if (authType != null) { + connProp.put(Context.SECURITY_AUTHENTICATION, authType); + } + + if (!LDAPConstants.AUTH_TYPE_NONE.equals(authType)) { + String bindDN = ldapConfig.getBindDN(); + if (bindDN != null) { + connProp.put(Context.SECURITY_PRINCIPAL, bindDN); + } + + if (bindPassword != null) { + connProp.put(SECURITY_CREDENTIALS, bindPassword); + } + } + + logConnectionProperties(connProp); + } + // Fill in the connection properties to authenticate as admin. private void setAdminConnectionAuthProperties(LdapContext ldapContext) throws NamingException { String authType = ldapConfig.getAuthType(); @@ -123,18 +149,25 @@ private void setAdminConnectionAuthProperties(LdapContext ldapContext) throws Na ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, authType); } - String bindPassword = getBindPassword(); - if (bindPassword != null) { - ldapContext.addToEnvironment(SECURITY_CREDENTIALS, bindPassword); - } + if (!LDAPConstants.AUTH_TYPE_NONE.equals(authType)) { + String bindDN = ldapConfig.getBindDN(); + if (bindDN != null) { + ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, bindDN); + } - String bindDN = ldapConfig.getBindDN(); - if (bindDN != null) { - ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, bindDN); + String bindPassword = getBindPassword(); + if (bindPassword != null) { + ldapContext.addToEnvironment(SECURITY_CREDENTIALS, bindPassword); + } } + logConnectionProperties(ldapContext.getEnvironment()); + } + + // Log the connection environment with the bind credentials masked. + private static void logConnectionProperties(Map env) { if (logger.isDebugEnabled()) { - Map copyEnv = new Hashtable<>(ldapContext.getEnvironment()); + Map copyEnv = new Hashtable<>(env); if (copyEnv.containsKey(Context.SECURITY_CREDENTIALS)) { copyEnv.put(Context.SECURITY_CREDENTIALS, "**************************************"); } diff --git a/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManagerTest.java b/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManagerTest.java new file mode 100644 index 00000000000..5f6e59c4e84 --- /dev/null +++ b/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPContextManagerTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed 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 + * + * http://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.keycloak.storage.ldap.idm.store.ldap; + +import java.util.Hashtable; +import javax.naming.Context; + +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.models.LDAPConstants; +import org.keycloak.storage.ldap.LDAPConfig; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests the admin connection environment built by {@link LDAPContextManager}. + */ +public class LDAPContextManagerTest { + + private static LDAPConfig ldapConfig(String authType, String bindDN, String connectionUrl) { + MultivaluedHashMap cfg = new MultivaluedHashMap<>(); + if (authType != null) { + cfg.add(LDAPConstants.AUTH_TYPE, authType); + } + if (bindDN != null) { + cfg.add(LDAPConstants.BIND_DN, bindDN); + } + if (connectionUrl != null) { + cfg.add(LDAPConstants.CONNECTION_URL, connectionUrl); + } + return new LDAPConfig(cfg); + } + + @Test + public void getNonAuthConnectionPropertiesHasNoBindCredentials() { + LDAPConfig config = ldapConfig(LDAPConstants.AUTH_TYPE_SIMPLE, "uid=admin,dc=example,dc=org", "ldap://localhost:389"); + + Hashtable env = LDAPContextManager.getNonAuthConnectionProperties(config); + + // The base connection stays anonymous; credentials are added separately by the caller. + Assert.assertFalse(env.containsKey(Context.SECURITY_AUTHENTICATION)); + Assert.assertFalse(env.containsKey(Context.SECURITY_PRINCIPAL)); + Assert.assertFalse(env.containsKey(Context.SECURITY_CREDENTIALS)); + } + + @Test + public void setAuthConnectionPropertiesPutsBindCredentialsIntoInitialEnv() { + LDAPConfig config = ldapConfig(LDAPConstants.AUTH_TYPE_SIMPLE, "uid=admin,dc=example,dc=org", "ldap://localhost:389"); + + Hashtable env = LDAPContextManager.getNonAuthConnectionProperties(config); + LDAPContextManager.setAuthConnectionProperties(env, config, "theBindPassword"); + + // Credentials present in the *initial* environment is what lets the JNDI pool reuse the bound + // connection instead of re-binding the service account on every operation. + Assert.assertEquals(LDAPConstants.AUTH_TYPE_SIMPLE, env.get(Context.SECURITY_AUTHENTICATION)); + Assert.assertEquals("uid=admin,dc=example,dc=org", env.get(Context.SECURITY_PRINCIPAL)); + Assert.assertEquals("theBindPassword", env.get(Context.SECURITY_CREDENTIALS)); + } + + @Test + public void setAuthConnectionPropertiesDoesNotBindForAnonymousAuth() { + LDAPConfig config = ldapConfig(LDAPConstants.AUTH_TYPE_NONE, null, "ldap://localhost:389"); + + Hashtable env = LDAPContextManager.getNonAuthConnectionProperties(config); + LDAPContextManager.setAuthConnectionProperties(env, config, null); + + // Anonymous bind: no principal/credentials must be added. + Assert.assertFalse(env.containsKey(Context.SECURITY_PRINCIPAL)); + Assert.assertFalse(env.containsKey(Context.SECURITY_CREDENTIALS)); + } +}