From f1ebbc57751369f03709a54d208c4869fa82160b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Kyjovsk=C3=BD?= <1867605+tkyjovsk@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:20:38 +0100 Subject: [PATCH] Restore LDAP connection URL failover for user authentication Closes #55322 * Since the forced password change support for LDAP users, LDAPOperationManager.authenticate() created the LDAP context without credentials and bound later via reconnect(). JNDI only iterates over multiple space-separated connection URLs during context creation, so a primary server accepting TCP but failing or hanging on bind no longer failed over to the next URL. When StartTLS is not used, bind during context creation again, passing the password policy request control as connection control. * Change server socket address to use '127.0.0.1' * Add LDAP and LDAPS bind failover integration tests Signed-off-by: Peter Heiles <72147026+pheiles@users.noreply.github.com> Signed-off-by: NedimPopovac Signed-off-by: NedimPopovac <115164896+NedimPopovac@users.noreply.github.com> Signed-off-by: Tomas Kyjovsky Co-authored-by: Peter Heiles <72147026+pheiles@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: NedimPopovac <115164896+NedimPopovac@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../idm/store/ldap/LDAPOperationManager.java | 36 ++- .../LDAPOperationManagerFailoverTest.java | 301 ++++++++++++++++++ .../federation/ldap/LDAPFailoverServer.java | 199 ++++++++++++ .../federation/ldap/LDAPFailoverTest.java | 295 +++++++++++++++++ 4 files changed, 818 insertions(+), 13 deletions(-) create mode 100644 federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManagerFailoverTest.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverServer.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverTest.java diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManager.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManager.java index 5b609a4ea2a2..00eaca7a6ccb 100644 --- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManager.java +++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManager.java @@ -550,12 +550,13 @@ public void authenticate(LdapName dn, String password) throws AuthenticationExce // Prepare to receive password policy response control. env.put(LdapContext.CONTROL_FACTORIES, PasswordPolicyControlFactory.class.getName()); - // Create connection but avoid triggering automatic bind request by not setting security principal and credentials yet. - // That allows us to send optional StartTLS request before binding. - authCtx = new InitialLdapContext(env, null); - - // Send StartTLS request and setup SSL context if needed. if (config.isStartTls()) { + // Create connection but avoid triggering automatic bind request by not setting security principal and credentials yet. + // That allows us to send StartTLS request before binding. + // Note: failover between multiple connection URLs only happens during context creation, so a bind failure + // after StartTLS will not fail over to the next URL. + authCtx = new InitialLdapContext(env, null); + SSLSocketFactory sslSocketFactory = null; if (LDAPUtil.shouldUseTruststoreSpi(config)) { TruststoreProvider provider = session.getProvider(TruststoreProvider.class); @@ -568,15 +569,24 @@ public void authenticate(LdapName dn, String password) throws AuthenticationExce if (tlsResponse == null) { throw new AuthenticationException("Null TLS Response returned from the authentication"); } - } - // Configure given credentials. - authCtx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); - authCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn.toString()); - authCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); - - // Send bind request. Throws AuthenticationException when authentication fails. - authCtx.reconnect(getControls()); + // Configure given credentials. + authCtx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); + authCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn.toString()); + authCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); + + // Send bind request. Throws AuthenticationException when authentication fails. + authCtx.reconnect(getControls()); + } else { + // Bind during context creation so that JNDI can fail over to the next URL of a multi-URL connection URL + // when a server accepts the connection but fails to answer the bind (e.g. read timeout). Failover is + // only performed during context creation, not by reconnect(). Request controls are sent with the bind + // and response controls (e.g. password policy) are available via getResponseControls(). + env.put(Context.SECURITY_AUTHENTICATION, "simple"); + env.put(Context.SECURITY_PRINCIPAL, dn.toString()); + env.put(Context.SECURITY_CREDENTIALS, password); + authCtx = new InitialLdapContext(env, getControls()); + } // Check for password policy response control in the response. // If present and forced password change is required, throw an exception. diff --git a/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManagerFailoverTest.java b/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManagerFailoverTest.java new file mode 100644 index 000000000000..b280e94c1fb4 --- /dev/null +++ b/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManagerFailoverTest.java @@ -0,0 +1,301 @@ +/* + * 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.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Proxy; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import javax.naming.AuthenticationException; +import javax.naming.ldap.LdapName; + +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.LDAPConstants; +import org.keycloak.storage.ldap.LDAPConfig; +import org.keycloak.storage.ldap.idm.store.ldap.control.PasswordPolicyControl; +import org.keycloak.storage.ldap.idm.store.ldap.control.PasswordPolicyPasswordChangeException; +import org.keycloak.tracing.NoopTracingProvider; +import org.keycloak.tracing.TracingProvider; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests that user authentication fails over to the next LDAP server of a multi-URL connection URL when the first + * server accepts the TCP connection but never answers the bind request. + */ +public class LDAPOperationManagerFailoverTest { + + private static final String USER_DN = "uid=john,dc=example,dc=org"; + + // SEQUENCE { error changeAfterReset(2) } + private static final byte[] CHANGE_AFTER_RESET = { 0x30, 0x03, (byte) 0x81, 0x01, 0x02 }; + + private BlackHoleServer unresponsiveServer; + private FakeLdapServer workingServer; + + @Before + public void before() throws IOException { + unresponsiveServer = new BlackHoleServer(); + workingServer = new FakeLdapServer(); + } + + @After + public void after() { + unresponsiveServer.close(); + workingServer.close(); + } + + @Test + public void authenticateFailsOverToNextUrlWhenBindTimesOut() throws Exception { + newOperationManager(false).authenticate(new LdapName(USER_DN), "secret"); + + Assert.assertTrue("Unresponsive server should have been contacted first", unresponsiveServer.accepted > 0); + Assert.assertEquals(List.of(USER_DN), workingServer.bindDNs); + } + + @Test + public void authenticateWithInvalidCredentialsOnNextUrl() throws Exception { + workingServer.resultCode = 49; // invalidCredentials + + Assert.assertThrows(AuthenticationException.class, + () -> newOperationManager(false).authenticate(new LdapName(USER_DN), "wrong")); + Assert.assertEquals(List.of(USER_DN), workingServer.bindDNs); + } + + @Test + public void authenticateReceivesPasswordPolicyControlAfterFailover() throws Exception { + workingServer.passwordPolicyResponse = CHANGE_AFTER_RESET; + + Assert.assertThrows(PasswordPolicyPasswordChangeException.class, + () -> newOperationManager(true).authenticate(new LdapName(USER_DN), "secret")); + Assert.assertEquals(List.of(USER_DN), workingServer.bindDNs); + Assert.assertTrue("Password policy request control should be sent with the bind", workingServer.passwordPolicyRequested); + } + + private LDAPOperationManager newOperationManager(boolean passwordPolicy) { + MultivaluedHashMap cfg = new MultivaluedHashMap<>(); + cfg.add(LDAPConstants.CONNECTION_URL, "ldap://127.0.0.1:" + unresponsiveServer.getPort() + " ldap://127.0.0.1:" + workingServer.getPort()); + cfg.add(LDAPConstants.AUTH_TYPE, LDAPConstants.AUTH_TYPE_NONE); + cfg.add(LDAPConstants.CONNECTION_TIMEOUT, "500"); + cfg.add(LDAPConstants.READ_TIMEOUT, "500"); + cfg.add(LDAPConstants.ENABLE_LDAP_PASSWORD_POLICY, String.valueOf(passwordPolicy)); + + TracingProvider tracing = new NoopTracingProvider(); + KeycloakSession session = (KeycloakSession) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { KeycloakSession.class }, + (proxy, method, args) -> { + if (method.getName().equals("getProvider") && args.length == 1 && args[0] == TracingProvider.class) { + return tracing; + } + throw new UnsupportedOperationException(method.toString()); + }); + + return new LDAPOperationManager(session, new LDAPConfig(cfg), null); + } + + private abstract static class AbstractServer implements Runnable { + + protected final ServerSocket serverSocket; + protected final List sockets = new CopyOnWriteArrayList<>(); + + AbstractServer() throws IOException { + serverSocket = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")); + Thread thread = new Thread(this, getClass().getSimpleName()); + thread.setDaemon(true); + thread.start(); + } + + int getPort() { + return serverSocket.getLocalPort(); + } + + @Override + public void run() { + while (!serverSocket.isClosed()) { + try { + Socket socket = serverSocket.accept(); + sockets.add(socket); + handle(socket); + } catch (IOException e) { + // closed + } + } + } + + abstract void handle(Socket socket); + + void close() { + try { + serverSocket.close(); + } catch (IOException ignore) { + } + for (Socket socket : sockets) { + try { + socket.close(); + } catch (IOException ignore) { + } + } + } + } + + /** + * Accepts TCP connections but never answers, simulating a degraded or paused LDAP server. + */ + private static class BlackHoleServer extends AbstractServer { + + volatile int accepted; + + BlackHoleServer() throws IOException { + super(); + } + + @Override + void handle(Socket socket) { + accepted++; + } + } + + /** + * Minimal LDAP server answering simple bind requests. + */ + private static class FakeLdapServer extends AbstractServer { + + final List bindDNs = new CopyOnWriteArrayList<>(); + volatile int resultCode = 0; + volatile byte[] passwordPolicyResponse; + volatile boolean passwordPolicyRequested; + + FakeLdapServer() throws IOException { + super(); + } + + @Override + void handle(Socket socket) { + Thread thread = new Thread(() -> serve(socket), "FakeLdapServer-connection"); + thread.setDaemon(true); + thread.start(); + } + + private void serve(Socket socket) { + try (socket) { + DataInputStream in = new DataInputStream(socket.getInputStream()); + OutputStream out = socket.getOutputStream(); + while (true) { + // LDAPMessage ::= SEQUENCE { messageID, protocolOp, controls [0] OPTIONAL } + if (in.read() != 0x30) { + return; + } + byte[] message = readBytes(in, readLength(in)); + Tlv messageId = Tlv.parse(message, 0); + Tlv op = Tlv.parse(message, messageId.end); + + if (op.tag == 0x60) { // BindRequest ::= [APPLICATION 0] SEQUENCE { version, name, authentication } + Tlv version = Tlv.parse(message, op.valueStart); + Tlv name = Tlv.parse(message, version.end); + bindDNs.add(new String(message, name.valueStart, name.length, StandardCharsets.UTF_8)); + if (op.end < message.length) { + passwordPolicyRequested = new String(message, op.end, message.length - op.end, StandardCharsets.US_ASCII) + .contains(PasswordPolicyControl.OID); + } + out.write(bindResponse(message, messageId)); + out.flush(); + } else if (op.tag == 0x42) { // UnbindRequest + return; + } + } + } catch (IOException e) { + // connection closed + } + } + + private byte[] bindResponse(byte[] message, Tlv messageId) { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.write(message, messageId.start, messageId.end - messageId.start); + // BindResponse ::= [APPLICATION 1] SEQUENCE { resultCode, matchedDN, diagnosticMessage } + body.writeBytes(tlv(0x61, new byte[] { 0x0A, 0x01, (byte) resultCode, 0x04, 0x00, 0x04, 0x00 })); + byte[] ppolicy = passwordPolicyResponse; + if (ppolicy != null) { + ByteArrayOutputStream control = new ByteArrayOutputStream(); + control.writeBytes(tlv(0x04, PasswordPolicyControl.OID.getBytes(StandardCharsets.US_ASCII))); + control.writeBytes(tlv(0x04, ppolicy)); + body.writeBytes(tlv(0xA0, tlv(0x30, control.toByteArray()))); + } + return tlv(0x30, body.toByteArray()); + } + + private static byte[] tlv(int tag, byte[] value) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(tag); + if (value.length < 0x80) { + out.write(value.length); + } else { + out.write(0x82); + out.write(value.length >> 8); + out.write(value.length & 0xFF); + } + out.writeBytes(value); + return out.toByteArray(); + } + + private static int readLength(InputStream in) throws IOException { + int first = in.read(); + if (first < 0x80) { + return first; + } + int length = 0; + for (int i = 0; i < (first & 0x7F); i++) { + length = (length << 8) | in.read(); + } + return length; + } + + private static byte[] readBytes(DataInputStream in, int length) throws IOException { + byte[] bytes = new byte[length]; + in.readFully(bytes); + return bytes; + } + } + + private record Tlv(int tag, int start, int valueStart, int length, int end) { + + static Tlv parse(byte[] data, int offset) { + int tag = data[offset] & 0xFF; + int pos = offset + 1; + int first = data[pos++] & 0xFF; + int length = first; + if (first >= 0x80) { + length = 0; + for (int i = 0; i < (first & 0x7F); i++) { + length = (length << 8) | (data[pos++] & 0xFF); + } + } + return new Tlv(tag, offset, pos, length, pos + length); + } + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverServer.java b/tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverServer.java new file mode 100644 index 000000000000..f93bbe4d53ce --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverServer.java @@ -0,0 +1,199 @@ +/* + * 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.tests.federation.ldap; + +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.keycloak.common.util.PemUtils; +import org.keycloak.testframework.https.CertificatesConfigBuilder; +import org.keycloak.testframework.https.ManagedCertificates; +import org.keycloak.util.ldap.LDAPEmbeddedServer; + +import org.apache.directory.api.ldap.model.entry.DefaultEntry; +import org.apache.directory.api.ldap.model.entry.DefaultModification; +import org.apache.directory.api.ldap.model.entry.ModificationOperation; +import org.apache.directory.api.ldap.model.message.BindRequest; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.server.ldap.LdapServer; +import org.apache.directory.server.ldap.LdapSession; +import org.apache.directory.server.ldap.handlers.request.BindRequestHandler; +import org.apache.directory.server.ldap.handlers.response.BindResponseHandler; +import org.apache.directory.server.protocol.shared.transport.Transport; + +/** + * Two real LDAP frontends share one directory, including entry UUIDs and password-policy state. + * Faults suppress bind responses after decoding LDAP, so LDAPS faults happen after the TLS handshake. + */ +final class LDAPFailoverServer extends LDAPEmbeddedServer implements AutoCloseable { + + static final String USERNAME = "failover-user"; + static final String USER_DN = "uid=" + USERNAME + ",ou=People,dc=keycloak,dc=org"; + static final String SERVICE_DN = "uid=failover-service,dc=keycloak,dc=org"; + static final String PASSWORD = "Password1"; + static final String PASSWORD_POLICY_OID = "1.3.6.1.4.1.42.2.27.8.5.1"; + + enum Fault { + NONE, USER_BIND_TIMEOUT, ALL_BINDS_TIMEOUT + } + + enum ConnectionType { + LDAP, LDAPS + } + + record BindAttempt(String dn, boolean passwordPolicyRequested) { + } + + private final List primaryBinds = new CopyOnWriteArrayList<>(); + private final List secondaryBinds = new CopyOnWriteArrayList<>(); + private volatile Fault fault = Fault.NONE; + private LdapServer primary; + + LDAPFailoverServer() { + super(properties()); + } + + private static Properties properties() { + Properties properties = new Properties(); + properties.setProperty(PROPERTY_DSF, DSF_INMEMORY); + properties.setProperty(PROPERTY_BIND_HOST, "localhost"); + properties.setProperty(PROPERTY_BIND_PORT, "0"); + properties.setProperty(PROPERTY_BIND_LDAPS_PORT, "0"); + properties.setProperty(PROPERTY_ENABLE_SSL, "true"); + properties.setProperty("keystoreFile", TlsMaterial.CERTIFICATES.getServerKeyStorePath()); + properties.setProperty("certificatePassword", TlsMaterial.CERTIFICATES.getServerKeyStorePassword()); + properties.setProperty(PROPERTY_PPOLICY_ENABLED, "true"); + properties.setProperty(PROPERTY_PPOLICY_MUST_CHANGE, "true"); + // Like LDAPRule's mustChange fixture, use a non-admin service account so a user's password + // update does not immediately mark the new password as another administrative reset. + properties.setProperty(PROPERTY_ENABLE_ACCESS_CONTROL, "false"); + return properties; + } + + @Override + protected LdapServer createLdapServer() { + return endpoint(false); + } + + private LdapServer endpoint(boolean isPrimary) { + LdapServer server = super.createLdapServer(); + server.setBindHandlers(new BindRequestHandler() { + @Override + public void handle(LdapSession session, BindRequest request) throws Exception { + String dn = request.getName(); + (isPrimary ? primaryBinds : secondaryBinds).add(new BindAttempt(dn, request.hasControl(PASSWORD_POLICY_OID))); + if (isPrimary && (fault == Fault.ALL_BINDS_TIMEOUT || fault == Fault.USER_BIND_TIMEOUT && new Dn(dn).equals(new Dn(USER_DN)))) { + // Do not block an ApacheDS worker. The client times out and closes the session. + return; + } + super.handle(session, request); + } + }, new BindResponseHandler()); + return server; + } + + @Override + public void start() throws Exception { + super.start(); + primary = endpoint(true); + primary.start(); + addUser(SERVICE_DN, "failover-service"); + addUser(USER_DN, USERNAME); + clearBinds(); + } + + private void addUser(String dn, String username) throws Exception { + directoryService.getAdminSession().add(new DefaultEntry(directoryService.getSchemaManager(), dn, + "objectClass: inetOrgPerson", "uid: " + username, "cn: Failover User", "givenName: Failover", + "sn: User", "mail: " + username + "@example.org", "userPassword: " + PASSWORD)); + if (directoryService.getAdminSession().lookup(new Dn(dn), "pwdReset").containsAttribute("pwdReset")) { + directoryService.getAdminSession().modify(new Dn(dn), new DefaultModification(ModificationOperation.REMOVE_ATTRIBUTE, "pwdReset")); + } + } + + void fault(Fault fault) { + this.fault = fault; + } + + String url(boolean isPrimary, ConnectionType connectionType) { + LdapServer server = isPrimary ? primary : ldapServer; + Transport transport = List.of(server.getTransports()).stream() + .filter(t -> t.isSSLEnabled() == (connectionType == ConnectionType.LDAPS)).findFirst().orElseThrow(); + int port = ((InetSocketAddress) transport.getAcceptor().getLocalAddress()).getPort(); + return (connectionType == ConnectionType.LDAPS ? "ldaps" : "ldap") + "://localhost:" + port; + } + + void refusePrimaryConnections() { + primary.stop(); + } + + List binds(boolean isPrimary, String dn) { + return (isPrimary ? primaryBinds : secondaryBinds).stream().filter(b -> b.dn().equalsIgnoreCase(dn)).toList(); + } + + void clearBinds() { + primaryBinds.clear(); + secondaryBinds.clear(); + } + + @Override + public void close() throws Exception { + try { + if (primary != null && primary.isStarted()) { + primary.stop(); + } + } finally { + if (ldapServer != null) { + stop(); + } else if (directoryService != null) { + shutdownDirectoryService(); + } + } + } + + static Path trustedCertificate() { + return TlsMaterial.CERTIFICATE; + } + + private static class TlsMaterial { + private static final ManagedCertificates CERTIFICATES = new ManagedCertificates(new CertificatesConfigBuilder().tlsEnabled(true)); + private static final Path CERTIFICATE = exportCertificate(); + + private static Path exportCertificate() { + try { + KeyStore store = KeyStore.getInstance(CERTIFICATES.getKeystoreFormat().name()); + try (InputStream input = Files.newInputStream(Path.of(CERTIFICATES.getServerKeyStorePath()))) { + store.load(input, CERTIFICATES.getServerKeyStorePassword().toCharArray()); + } + Certificate certificate = store.getCertificate("server-key"); + Path path = Files.createTempFile("ldap-failover-certificate-", ".pem"); + Files.writeString(path, PemUtils.BEGIN_CERT + "\n" + PemUtils.encodeCertificate(certificate) + "\n" + PemUtils.END_CERT + "\n"); + path.toFile().deleteOnExit(); + return path; + } catch (Exception e) { + throw new IllegalStateException("Could not prepare the LDAP server certificate", e); + } + } + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverTest.java b/tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverTest.java new file mode 100644 index 000000000000..ca434820f358 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/federation/ldap/LDAPFailoverTest.java @@ -0,0 +1,295 @@ +/* + * 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.tests.federation.ldap; + + +import jakarta.ws.rs.core.Response; + +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.models.LDAPConstants; +import org.keycloak.representations.idm.ComponentRepresentation; +import org.keycloak.storage.UserStorageProvider; +import org.keycloak.storage.UserStorageProviderModel; +import org.keycloak.testframework.annotations.InjectRealm; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.injection.LifeCycle; +import org.keycloak.testframework.oauth.OAuthClient; +import org.keycloak.testframework.oauth.annotations.InjectOAuthClient; +import org.keycloak.testframework.realm.ClientBuilder; +import org.keycloak.testframework.realm.ClientConfig; +import org.keycloak.testframework.realm.ManagedRealm; +import org.keycloak.testframework.server.KeycloakServerConfig; +import org.keycloak.testframework.server.KeycloakServerConfigBuilder; +import org.keycloak.testframework.ui.annotations.InjectPage; +import org.keycloak.testframework.ui.page.LoginPage; +import org.keycloak.testframework.ui.page.LoginPasswordUpdatePage; +import org.keycloak.testframework.util.ApiUtil; +import org.keycloak.tests.federation.ldap.LDAPFailoverServer.ConnectionType; +import org.keycloak.tests.federation.ldap.LDAPFailoverServer.Fault; +import org.keycloak.testsuite.util.oauth.AccessTokenResponse; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import static org.keycloak.tests.federation.ldap.LDAPFailoverServer.PASSWORD; +import static org.keycloak.tests.federation.ldap.LDAPFailoverServer.SERVICE_DN; +import static org.keycloak.tests.federation.ldap.LDAPFailoverServer.USERNAME; +import static org.keycloak.tests.federation.ldap.LDAPFailoverServer.USER_DN; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; + +@KeycloakIntegrationTest(config = LDAPFailoverTest.ServerConfig.class) +public class LDAPFailoverTest { + + @InjectRealm(lifecycle = LifeCycle.METHOD) + ManagedRealm realm; + + @InjectOAuthClient(config = ClientConfiguration.class, lifecycle = LifeCycle.METHOD) + OAuthClient oauth; + + @InjectPage + LoginPage loginPage; + + @InjectPage + LoginPasswordUpdatePage passwordUpdatePage; + + private LDAPFailoverServer ldap; + private ComponentRepresentation provider; + + @BeforeEach + void startDirectory() throws Exception { + ldap = new LDAPFailoverServer(); + ldap.init(); + ldap.start(); + oauth.getDriver().manage().deleteAllCookies(); + } + + @AfterEach + void stopDirectory() throws Exception { + if (ldap != null) { + ldap.close(); + } + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void healthyPrimary(ConnectionType connectionType) { + configure(connectionType); + assertLogin(PASSWORD); + assertThat(ldap.binds(true, USER_DN), hasSize(1)); + assertThat(ldap.binds(false, USER_DN), empty()); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void invalidPasswordDoesNotTryNextServer(ConnectionType connectionType) { + configure(connectionType); + assertInvalidPassword(); + assertThat(ldap.binds(true, USER_DN), hasSize(1)); + assertThat(ldap.binds(false, USER_DN), empty()); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void userBindTimeoutFailsOver(ConnectionType connectionType) { + configure(connectionType); + ldap.fault(Fault.USER_BIND_TIMEOUT); + assertLookup(); + assertThat(ldap.binds(false, SERVICE_DN), empty()); + ldap.clearBinds(); + assertLogin(PASSWORD); + assertUserBindFailover(); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void serviceAccountAndUserBindFailOver(ConnectionType connectionType) { + configure(connectionType); + ldap.fault(Fault.ALL_BINDS_TIMEOUT); + assertLookup(); + assertThat(ldap.binds(false, SERVICE_DN), not(empty())); + ldap.clearBinds(); + assertLogin(PASSWORD); + assertUserBindFailover(); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void invalidPasswordIsRejectedAfterFailover(ConnectionType connectionType) { + configure(connectionType); + ldap.fault(Fault.USER_BIND_TIMEOUT); + assertInvalidPassword(); + assertUserBindFailover(); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void passwordPolicyControlSurvivesFailover(ConnectionType connectionType) { + configure(connectionType); + enablePasswordPolicy(); + ldap.fault(Fault.USER_BIND_TIMEOUT); + assertLogin(PASSWORD); + assertUserBindFailover(); + assertThat(ldap.binds(false, USER_DN).stream().map(LDAPFailoverServer.BindAttempt::passwordPolicyRequested).toList(), everyItem(is(true))); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void healthyServerFirst(ConnectionType connectionType) { + configure(connectionType); + provider.getConfig().putSingle(LDAPConstants.CONNECTION_URL, ldap.url(false, connectionType) + " " + ldap.url(true, connectionType)); + updateProvider(); + ldap.fault(Fault.USER_BIND_TIMEOUT); + assertLogin(PASSWORD); + assertThat(ldap.binds(true, USER_DN), empty()); + assertThat(ldap.binds(false, USER_DN), hasSize(1)); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void refusedConnectionFailsOver(ConnectionType connectionType) { + configure(connectionType); + ldap.refusePrimaryConnections(); + assertLogin(PASSWORD); + assertThat(ldap.binds(true, USER_DN), empty()); + assertThat(ldap.binds(false, USER_DN), hasSize(1)); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void recoveredPrimaryIsUsedForNextLogin(ConnectionType connectionType) { + configure(connectionType); + ldap.fault(Fault.USER_BIND_TIMEOUT); + assertLogin(PASSWORD); + assertUserBindFailover(); + ldap.fault(Fault.NONE); + ldap.clearBinds(); + assertLogin(PASSWORD); + assertThat(ldap.binds(true, USER_DN), hasSize(1)); + assertThat(ldap.binds(false, USER_DN), empty()); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void forcedPasswordChangeAfterFailover(ConnectionType connectionType) { + configure(connectionType); + enablePasswordPolicy(); + ldap.setPwdReset(USER_DN, true); + ldap.fault(Fault.USER_BIND_TIMEOUT); + + AccessTokenResponse grant = oauth.doPasswordGrantRequest(USERNAME, PASSWORD); + assertThat(grant.getError(), is("invalid_grant")); + assertThat(grant.getErrorDescription(), is("Account is not fully set up")); + assertThat(grant.getAccessToken(), is((String) null)); + assertUserBindFailover(); + + oauth.openLoginForm(); + loginPage.fillLogin(USERNAME, PASSWORD); + loginPage.submit(); + passwordUpdatePage.assertCurrent(); + passwordUpdatePage.changePassword("Changed-password1", "Changed-password1"); + assertThat(oauth.parseLoginResponse().getCode(), notNullValue()); + assertLogin("Changed-password1"); + AccessTokenResponse oldPassword = oauth.doPasswordGrantRequest(USERNAME, PASSWORD); + assertThat(oldPassword.getError(), is("invalid_grant")); + assertThat(oldPassword.getAccessToken(), is((String) null)); + } + + private void configure(ConnectionType connectionType) { + MultivaluedHashMap config = new MultivaluedHashMap<>(); + config.putSingle(LDAPConstants.CONNECTION_URL, ldap.url(true, connectionType) + " " + ldap.url(false, connectionType)); + config.putSingle(LDAPConstants.USERS_DN, "ou=People,dc=keycloak,dc=org"); + config.putSingle(LDAPConstants.BIND_DN, SERVICE_DN); + config.putSingle(LDAPConstants.BIND_CREDENTIAL, PASSWORD); + config.putSingle(LDAPConstants.AUTH_TYPE, LDAPConstants.AUTH_TYPE_SIMPLE); + config.putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.name()); + config.putSingle(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, "uid"); + config.putSingle(LDAPConstants.RDN_LDAP_ATTRIBUTE, "uid"); + config.putSingle(LDAPConstants.UUID_LDAP_ATTRIBUTE, "entryUUID"); + config.putSingle(LDAPConstants.USER_OBJECT_CLASSES, "inetOrgPerson"); + config.putSingle(LDAPConstants.CONNECTION_POOLING, "false"); + config.putSingle(LDAPConstants.CONNECTION_TIMEOUT, "2000"); + config.putSingle(LDAPConstants.READ_TIMEOUT, "2000"); + config.putSingle(LDAPConstants.START_TLS, "false"); + config.putSingle(LDAPConstants.ENABLE_LDAP_PASSWORD_POLICY, "false"); + config.putSingle(UserStorageProviderModel.CACHE_POLICY, UserStorageProviderModel.CachePolicy.NO_CACHE.name()); + provider = new ComponentRepresentation(); + provider.setName("failover-ldap"); + provider.setProviderId("ldap"); + provider.setProviderType(UserStorageProvider.class.getName()); + provider.setConfig(config); + try (Response response = realm.admin().components().add(provider)) { + assertThat(response.getStatus(), is(201)); + provider.setId(ApiUtil.getCreatedId(response)); + } + ldap.clearBinds(); + } + + private void enablePasswordPolicy() { + provider.getConfig().putSingle(LDAPConstants.ENABLE_LDAP_PASSWORD_POLICY, "true"); + updateProvider(); + } + + private void updateProvider() { + realm.admin().components().component(provider.getId()).update(provider); + ldap.clearBinds(); + } + + private void assertLookup() { + assertThat(realm.admin().users().searchByUsername(USERNAME, true), hasSize(1)); + } + + private void assertLogin(String password) { + AccessTokenResponse grant = oauth.doPasswordGrantRequest(USERNAME, password); + assertThat(grant.getErrorDescription(), grant.getStatusCode(), is(200)); + assertThat(grant.getAccessToken(), notNullValue()); + } + + private void assertInvalidPassword() { + AccessTokenResponse grant = oauth.doPasswordGrantRequest(USERNAME, "wrong-password"); + assertThat(grant.getError(), is("invalid_grant")); + assertThat(grant.getErrorDescription(), is("Invalid user credentials")); + assertThat(grant.getAccessToken(), is((String) null)); + } + + private void assertUserBindFailover() { + assertThat(ldap.binds(true, USER_DN), hasSize(1)); + assertThat(ldap.binds(false, USER_DN), hasSize(1)); + } + + public static class ClientConfiguration implements ClientConfig { + @Override + public ClientBuilder configure(ClientBuilder client) { + return client.clientId("ldap-failover").secret("secret").directAccessGrantsEnabled(true); + } + } + + public static class ServerConfig implements KeycloakServerConfig { + @Override + public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) { + return config.option("truststore-paths", LDAPFailoverServer.trustedCertificate().toString()); + } + } +}