8000 Reuse the pooled LDAP admin connection instead of re-binding per operation by R-Owino · Pull Request #50218 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<Object, Object> 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);
}
Expand All @@ -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);
Expand All @@ -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()).
}
Expand Down Expand Up @@ -116,25 +121,53 @@ 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<Object, Object> 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);
}
Comment thread
R-Owino marked this conversation as resolved.
Resolved
}

logConnectionProperties(connProp);
}

// Fill in the connection properties to authenticate as admin.
private void setAdminConnectionAuthProperties(LdapContext ldapContext) throws NamingException {
String authType = ldapConfig.getAuthType();
if (authType != null) {
ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, authType);
}

String bindPassword = getBindPassword();
if (bindPassword != null) {
ldapContext.addToEnvironment(SECURITY_CREDENTIALS, bindPassword);
}
if (!LDAPConstants.AUTH_TYPE_NONE.equals(authType)) {
Comment thread
pedroigor marked this conversation as resolved.
Resolved
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<Object, Object> copyEnv = new Hashtable<>(ldapContext.getEnvironment());
Map<Object, Object> copyEnv = new Hashtable<>(env);
if (copyEnv.containsKey(Context.SECURITY_CREDENTIALS)) {
copyEnv.put(Context.SECURITY_CREDENTIALS, "**************************************");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, String> 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<Object, Object> 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<Object, Object> 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<Object, Object> 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));
}
}
Loading
0