Repository navigation
Restore LDAP connection URL failover for user authentication - #55323
NedimPopovac wants to merge 2 commits into
Conversation
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. Closes keycloak#55322 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Peter Heiles <72147026+pheiles@users.noreply.github.com> Signed-off-by: NedimPopovac <nedim.popovac@dedalus.com>
There was a problem hiding this comment.
🟡 Changes recommended
The failover tests bind to ::1 on IPv6-preferred hosts while their LDAP URLs target 127.0.0.1, causing connection refusals instead of exercising bind failover.
1 open issue
What changed in this PR
Restores multi-URL failover for LDAP user authentication when a server accepts connections but does not answer bind requests, addressing the regression described in #55322.
Changes:
- Performs non-StartTLS authentication during context creation so JNDI can try subsequent URLs.
- Preserves password-policy controls and the existing StartTLS authentication flow.
- Adds regression tests for successful failover, invalid credentials, and forced password changes.
| File | Description |
|---|---|
federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManagerFailoverTest.java |
Adds failover tests using unresponsive and fake LDAP servers. |
federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPOperationManager.java |
Moves non-StartTLS binding into context creation to restore failover. |
Review effort: Balanced
There was a problem hiding this comment.
Correctness assessment
This PR fixes the reported bind-time failover problem when StartTLS is disabled.
- Initial bind failover: Credentials are now supplied during context creation for connections without StartTLS, placing bind errors back inside JNDI’s existing URL iteration.
This covers the reported plaintext LDAP case and selects the same branch for LDAPS without StartTLS. - Invalid credentials: JNDI immediately propagates
AuthenticationException.
A separate probe confirmed that the second server is not contacted when the first rejects credentials. - Password policy: Constructor connection controls reach the bind, and the bind response controls remain available through
getResponseControls().
Validation confirmed that the password-policy request is sent and that Keycloak raisesPasswordPolicyPasswordChangeExceptionafter successful failover when the response requires a password change. - StartTLS: The existing sequence remains: create the context, negotiate TLS, then bind.
Bind-time failover still does not work on that path. (Existing limitation, not a regression.) - Existing safeguards: User authentication still disables connection pooling and rejects null or empty passwords.
Existing metrics, tracing, exception handling, and cleanup remain in place.
Testing
In addition to the added JUnit test, which now passes, I ran the same battery of tests for the PR, as for the original issue reproduction (StartTLS disabled, 3000 ms connect/read timeouts, and two OpenLDAP servers populated through syncrepl with matching user UUIDs):
| Scenario | User lookup | Login outcome |
|---|---|---|
| Healthy primary | HTTP 200 | HTTP 200, token issued |
| Healthy primary, wrong password | HTTP 200 | HTTP 400 invalid_grant, no token; no user bind to replica |
| Primary paused, attempt 1 | HTTP 200 through replica | HTTP 200, token issued through replica, 6.043 s |
| Primary paused, attempt 2 | HTTP 200 through replica | HTTP 200, token issued through replica, 6.048 s |
| Primary paused, wrong password | HTTP 200 through replica | Replica returns LDAP 49; HTTP 400 invalid_grant, no token |
| Primary paused, LDAP password policy enabled | HTTP 200 through replica | HTTP 200, token issued through replica, 6.082 s |
| Primary paused, replica URL first | HTTP 200 | HTTP 200, token issued through replica |
| Replica URL first, wrong password | HTTP 200 | HTTP 400 invalid_grant, no token |
| Primary TCP endpoint refuses connections | HTTP 200 through replica | HTTP 200, token issued through replica |
| Primary recovered, original URL order | HTTP 200 | HTTP 200, token issued through primary |
| Primary paused, replicated reset flag and LDAP policy enabled | HTTP 200 through replica | Replica returns changeAfterReset; Keycloak requires UPDATE_PASSWORD and issues no token |
-
The two ordinary stalled-primary logins show the user bind sent first to the primary and then to the replica, which returns LDAP bind success. This directly differs from the recorded 26.8.2 behavior, where the user bind never reaches the replica and login fails. The 3000 ms timeout applies to individual LDAP operations; total request duration includes service-account lookup and the subsequent user bind.
-
For the wrong-password failover case, the user bind reaches the replica and receives LDAP result code 49 (invalidCredentials), which Keycloak rejects. For the healthy-primary wrong-password case, no user bind is sent to the replica after the primary rejects the password.
-
For forced password change, the LDAP provider uses WRITABLE mode with enableLdapPasswordPolicy=true. The trace records password-policy request OID
1.3.6.1.4.1.42.2.27.8.5.1on the user bind and a successful replica bind response carrying password-policy error 2 (changeAfterReset). Keycloak logs Adding requiredActionUPDATE_PASSWORDto the authenticationSession of user resetuser and the password grant returns HTTP 400 invalid_grant with Account is not fully set up. This is the expected required-action outcome for the noninteractive password grant, rather than an ordinary invalid-password rejection. No browser password-change submission or completion was tested.
I would consider this a pass.
Testing scope
Based on the code changes there should be no problem for LDAPS, however the above tests only cover plain LDAP (no TLS config).
IPv6 portability
The three added JUnit tests pass normally, but fail with -Djava.net.preferIPv6Addresses=true. The copilod comment is valid.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: NedimPopovac <115164896+NedimPopovac@users.noreply.github.com>
There was a problem hiding this comment.
LGTM.
Could you please add these additional integration tests: DedalusDIIT#4 ?
|
@tkyjovsk I think your intention was to ask @NedimPopovac to incorporate the PRs you've added to enhance the tests, correct? https://github.com/keycloak/keycloak/pull/55665/commits |
@sguilhen Yes, just the commit with the integration tests. But it's not strictly necessary. The issue is fixed even without them. |
|
+1, would be good to have them in place to cover possible future regressions there. |
|
@NedimPopovac Thanks for the fix. Since this is a regression I went ahead with a new PR so that we can merge asap, so I'm closing this one. I included your commits, and added the integration tests on top. |

Problem
Since Keycloak 26.6.0 (#15253, forced password change for LDAP federated users), LDAP user login no longer fails over to the next server of a multi-URL Connection URL (e.g. ldap://ldap1:389 ldap://ldap2:389) when the primary accepts TCP but hangs or fails on the bind (degraded AD, docker pause, …). Login fails with LDAP response read timed out instead of using the replica. 26.5 failed over correctly.
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.
Root cause
LDAPOperationManager.authenticate() creates the InitialLdapContext without credentials and binds afterwards via addToEnvironment(SECURITY_*) + reconnect(getControls()).
JDK JNDI (LdapCtxFactory.getUsingURLs) only iterates over the URL list during initial context creation: it tries the next URL for any NamingException (incl. read timeouts) and only rethrows AuthenticationException immediately. With LDAPv3 and no credentials no bind is sent during creation, so the first host that accepts TCP is selected; reconnect() then re-binds on that already-selected host and never tries other URLs.
The admin/bind-account connection (LDAPContextManager) already binds via the initial environment when StartTLS is off, so only the user-authentication path is affected. No configuration option works around it (Enable LDAP password policy only toggles the request control).
Fix
When StartTLS is not used, put SECURITY_AUTHENTICATION=simple, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS into the initial environment and create the context with new InitialLdapContext(env, getControls()), so the bind happens during context creation and JNDI fails over as before.
Password policy still works: connection controls passed to InitialLdapContext are sent as bind request controls, and LdapCtx stores the bind response controls, so authCtx.getResponseControls() still returns the PasswordPolicyControl and changeAfterReset still raises PasswordPolicyPasswordChangeException.
StartTLS: unchanged. StartTLS must be negotiated on an established connection before the bind, so the bind cannot be part of context creation and therefore cannot fail over on bind errors (connection-level failover still applies). This is a JNDI limitation and was already the case before #15253.
Connection pooling stays disabled, metrics/tracing/exception handling unchanged.
Tests
New unit test LDAPOperationManagerFailoverTest (no new dependencies) with a "black hole" server that accepts TCP but never answers, followed by a minimal fake LDAP server:
login succeeds via the second URL,
invalid credentials on the second URL raise AuthenticationException,
password policy request control is sent and a changeAfterReset response control raises PasswordPolicyPasswordChangeException after failover.
All three fail without the fix (read timeout) and pass with it. ./mvnw -pl federation/ldap test: 36 tests, 0 failures.
Closes #55322