From e76c77ebe458e01dc0a8759204e42e99dcd477b1 Mon Sep 17 00:00:00 2001 From: mohitdeuex Date: Mon, 5 Oct 2026 15:21:15 +0530 Subject: [PATCH 1/3] Fixes #14601: Health-check pooled LDAP connections so a dropped one cannot stall login The LDAP lookup pool used the SDK's default health check, which never probes a connection. When a firewall or load balancer silently drops an idle pooled connection, the next login's user search waits out the SDK's five-minute search response timeout, and the login retry can repeat that on another dead connection. - Probe each pooled connection with a root DSE read before checkout, every 60 s in the background, and after a connection error; a connection that stays silent for 5 s is replaced. The background probe also keeps idle connections alive through load balancer and firewall idle timeouts. - Retry a search once on a fresh connection when its connection turns out dead. - Open pool connections through the same openConnection path as the password check and Test Login, and close the socket when the lookup bind is rejected. - Close the handlers a security reload replaces, so their LDAP pools stop probing the directory once the provider is no longer LDAP. Co-Authored-By: Claude Opus 5.5 --- .../service/OpenMetadataApplication.java | 8 + .../service/security/AuthServeletHandler.java | 3 + .../security/auth/AuthenticatorHandler.java | 3 + .../security/auth/LdapAuthServletHandler.java | 5 + .../security/auth/LdapAuthenticator.java | 85 ++++-- .../auth/LdapAuthServletHandlerTest.java | 7 + .../auth/LdapLookupConnectionPoolTest.java | 274 ++++++++++++++++++ 7 files changed, 357 insertions(+), 28 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapLookupConnectionPoolTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java index f92a95cb00db..ac236b9940ee 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java @@ -947,6 +947,9 @@ public void reinitializeAuthSystem( try { LOG.info("Starting authentication system reinitialization"); MutableServletContextHandler contextHandler = environment.getApplicationContext(); + AuthServeletHandler previousHandler = + AuthServeletHandlerRegistry.getHandler(contextHandler.getServletContext()); + AuthenticatorHandler previousAuthenticator = authenticatorHandler; SessionService sessionService = AuthServeletHandlerRegistry.getSessionService(contextHandler.getServletContext()); if (sessionService == null) { @@ -984,6 +987,11 @@ public void reinitializeAuthSystem( registerSamlServlets(config, environment); } + // An LDAP handler left open would keep its pool connected to, and probing, the directory + // it was built for, even after the provider moved away from LDAP. + previousHandler.close(); + previousAuthenticator.close(); + LOG.info("Successfully reinitialized authentication system"); } catch (Exception e) { LOG.error("Failed to reinitialize authentication system", e); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandler.java index 28f643ec1d31..6fdf49bc7ed2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandler.java @@ -11,4 +11,7 @@ public interface AuthServeletHandler { void handleCallback(HttpServletRequest req, HttpServletResponse resp); void handleRefresh(HttpServletRequest req, HttpServletResponse resp); + + /** Releases what this handler holds, once a security reload has replaced it. */ + default void close() {} } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/AuthenticatorHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/AuthenticatorHandler.java index 0886f770922f..ceb499c20f16 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/AuthenticatorHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/AuthenticatorHandler.java @@ -38,6 +38,9 @@ default void reload(OpenMetadataApplicationConfig config) { init(config); } + /** Releases what {@link #init} acquired, once a security reload has replaced this handler. */ + default void close() {} + JwtResponse loginUser(LoginRequest loginRequest) throws IOException, TemplateException; void checkIfLoginBlocked(String userName); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthServletHandler.java index 48854989bedd..dd74af64314e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthServletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthServletHandler.java @@ -237,6 +237,11 @@ public void handleLogout(HttpServletRequest req, HttpServletResponse resp) { } } + @Override + public void close() { + authenticator.close(); + } + private LoginRequest parseLoginRequest(HttpServletRequest req) throws IOException { if ("POST".equalsIgnoreCase(req.getMethod())) { StringBuilder sb = new StringBuilder(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java index ffe0eb9fc583..734b154f7707 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java @@ -20,9 +20,11 @@ import com.unboundid.ldap.sdk.Attribute; import com.unboundid.ldap.sdk.BindResult; import com.unboundid.ldap.sdk.Filter; +import com.unboundid.ldap.sdk.GetEntryLDAPConnectionPoolHealthCheck; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionOptions; import com.unboundid.ldap.sdk.LDAPConnectionPool; +import com.unboundid.ldap.sdk.LDAPConnectionPoolHealthCheck; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.ResultCode; import com.unboundid.ldap.sdk.SearchRequest; @@ -85,6 +87,11 @@ public class LdapAuthenticator implements AuthenticatorHandler { static final String AD_RECURSIVE_GROUP_MATCHING_RULE = "1.2.840.113556.1.4.1941"; static final String LDAP_ERR_MSG = "[LDAP] Issue in creating a LookUp Connection "; + private static final String ROOT_DSE = ""; + // Below the idle timeout of common load balancers and firewalls, so the background probe also + // keeps them from silently dropping pooled connections that sit idle between logins. + private static final long POOL_HEALTH_CHECK_INTERVAL_MILLIS = 60_000L; + private static final long POOL_HEALTH_CHECK_TIMEOUT_MILLIS = 5_000L; private static final int MAX_RETRIES = 3; private static final int BASE_DELAY_MS = 500; private static final String DEFAULT_EMAIL_ATTRIBUTE = "mail"; @@ -101,7 +108,7 @@ public void init(OpenMetadataApplicationConfig config) { if (SecurityConfigurationManager.getCurrentAuthConfig().getProvider().equals(AuthProvider.LDAP) && SecurityConfigurationManager.getCurrentAuthConfig().getLdapConfiguration() != null) { ldapLookupConnectionPool = - getLdapConnectionPool( + createLookupConnectionPool( SecurityConfigurationManager.getCurrentAuthConfig().getLdapConfiguration()); } else { throw new IllegalStateException("Invalid or Missing Ldap Configuration."); @@ -115,38 +122,60 @@ public void init(OpenMetadataApplicationConfig config) { SecurityConfigurationManager.getCurrentAuthConfig().getEnableSelfSignup(); } - private LDAPConnectionPool getLdapConnectionPool(LdapConfiguration ldapConfiguration) { - LDAPConnectionPool connectionPool; + static LDAPConnectionPool createLookupConnectionPool(LdapConfiguration ldapConfiguration) { try { - if (Boolean.TRUE.equals(ldapConfiguration.getSslEnabled())) { - LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions(); - LdapUtil ldapUtil = new LdapUtil(); - SSLUtil sslUtil = - new SSLUtil(ldapUtil.getLdapSSLConnection(ldapConfiguration, connectionOptions)); - LDAPConnection connection = - new LDAPConnection( - sslUtil.createSSLSocketFactory(), - connectionOptions, - ldapConfiguration.getHost(), - ldapConfiguration.getPort(), - ldapConfiguration.getDnAdminPrincipal(), - ldapConfiguration.getDnAdminPassword()); - // Use the connection here. - connectionPool = new LDAPConnectionPool(connection, ldapConfiguration.getMaxPoolSize()); - } else { - LDAPConnection conn = - new LDAPConnection( - ldapConfiguration.getHost(), - ldapConfiguration.getPort(), - ldapConfiguration.getDnAdminPrincipal(), - ldapConfiguration.getDnAdminPassword()); - connectionPool = new LDAPConnectionPool(conn, ldapConfiguration.getMaxPoolSize()); - } + LDAPConnectionPool connectionPool = + new LDAPConnectionPool( + openLookupConnection(ldapConfiguration), ldapConfiguration.getMaxPoolSize()); + connectionPool.setHealthCheck(rootDseHealthCheck()); + connectionPool.setHealthCheckIntervalMillis(POOL_HEALTH_CHECK_INTERVAL_MILLIS); + connectionPool.setRetryFailedOperationsDueToInvalidConnections(true); + return connectionPool; } catch (LDAPException | GeneralSecurityException e) { LOG.error("[LDAP] Issue in creating a LookUp Connection", e); throw new IllegalStateException(LDAP_ERR_MSG, e); } - return connectionPool; + } + + private static LDAPConnection openLookupConnection(LdapConfiguration ldapConfiguration) + throws LDAPException, GeneralSecurityException { + LDAPConnection connection = openConnection(ldapConfiguration, new LDAPConnectionOptions()); + try { + connection.bind( + ldapConfiguration.getDnAdminPrincipal(), ldapConfiguration.getDnAdminPassword()); + } catch (LDAPException e) { + connection.close(); + throw e; + } + return connection; + } + + /** + * Reads the root DSE to prove a pooled connection still gets answers: before each checkout, on + * every background pass, and after an error that may have broken it. A connection that stays + * silent past the timeout is replaced instead of stalling the login that drew it. + */ + private static LDAPConnectionPoolHealthCheck rootDseHealthCheck() { + boolean invokeOnCreate = false; + boolean invokeOnCheckout = true; + boolean invokeOnRelease = false; + boolean invokeForBackgroundChecks = true; + boolean invokeOnException = true; + return new GetEntryLDAPConnectionPoolHealthCheck( + ROOT_DSE, + POOL_HEALTH_CHECK_TIMEOUT_MILLIS, + invokeOnCreate, + invokeOnCheckout, + invokeOnRelease, + invokeForBackgroundChecks, + invokeOnException); + } + + @Override + public void close() { + if (ldapLookupConnectionPool != null) { + ldapLookupConnectionPool.close(); + } } @Override diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapAuthServletHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapAuthServletHandlerTest.java index 4ad4dda17568..66381f204b32 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapAuthServletHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapAuthServletHandlerTest.java @@ -171,4 +171,11 @@ void handleRefresh_revokedSessionDeletesRotatedRefreshToken() { verify(sessionService).revokeSession(request, response); verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } + + @Test + void close_releasesTheAuthenticatorConnectionPool() { + handler.close(); + + verify(authenticator).close(); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapLookupConnectionPoolTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapLookupConnectionPoolTest.java new file mode 100644 index 000000000000..f8a77953bda8 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapLookupConnectionPoolTest.java @@ -0,0 +1,274 @@ +/* + * Copyright 2026 Collate. + * 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.openmetadata.service.security.auth; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import com.unboundid.ldap.listener.InMemoryDirectoryServer; +import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; +import com.unboundid.ldap.listener.InMemoryListenerConfig; +import com.unboundid.ldap.sdk.Filter; +import com.unboundid.ldap.sdk.LDAPConnectionPool; +import com.unboundid.ldap.sdk.LDAPException; +import com.unboundid.ldap.sdk.LDAPSearchException; +import com.unboundid.ldap.sdk.SearchScope; +import com.unboundid.ldif.LDIFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.auth.LdapConfiguration; + +/** + * Runs the LDAP lookup pool against a real, in-process directory reached through a relay that can + * go silent on the connections it holds, the way a firewall or load balancer does when it drops an + * idle connection without closing it (#14601). + */ +class LdapLookupConnectionPoolTest { + private static final String BASE_DN = "dc=example,dc=com"; + private static final String USERS_DN = "ou=users," + BASE_DN; + private static final String LOOKUP_DN = "cn=Directory Manager"; + private static final String LOOKUP_PASSWORD = "lookup-password"; + private static final String ALICE_DN = "uid=alice," + USERS_DN; + private static final String ALICE_EMAIL = "alice@example.com"; + + private static InMemoryDirectoryServer directory; + private SilenceableRelay relay; + + @BeforeAll + static void startDirectory() throws LDAPException, LDIFException { + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(BASE_DN); + config.addAdditionalBindCredentials(LOOKUP_DN, LOOKUP_PASSWORD); + config.setListenerConfigs( + InMemoryListenerConfig.createLDAPConfig( + "default", InetAddress.getLoopbackAddress(), 0, null)); + config.setSchema(null); + directory = new InMemoryDirectoryServer(config); + directory.add("dn: " + BASE_DN, "objectClass: domain", "dc: example"); + directory.add("dn: " + USERS_DN, "objectClass: organizationalUnit", "ou: users"); + directory.add( + "dn: " + ALICE_DN, + "objectClass: inetOrgPerson", + "uid: alice", + "cn: Alice", + "sn: Liddell", + "mail: " + ALICE_EMAIL); + directory.startListening(); + } + + @AfterAll + static void stopDirectory() { + directory.shutDown(true); + } + + @BeforeEach + void startRelay() throws IOException { + relay = new SilenceableRelay(directory.getListenPort()); + } + + @AfterEach + void stopRelay() { + relay.close(); + } + + @Test + void aLookupIsNotStalledByAPooledConnectionThatStoppedAnswering() throws LDAPSearchException { + LDAPConnectionPool pool = LdapAuthenticator.createLookupConnectionPool(lookupThroughRelay()); + try { + assertEquals(ALICE_DN, findAlice(pool)); + relay.silenceOpenConnections(); + + // Unchecked, the search would wait out the SDK's five-minute search response timeout. + String foundDn = assertTimeoutPreemptively(Duration.ofSeconds(30), () -> findAlice(pool)); + + assertEquals(ALICE_DN, foundDn); + } finally { + pool.close(); + } + } + + @Test + void aRejectedLookupBindDoesNotLeaveItsConnectionOpen() { + LdapConfiguration wrongPassword = + lookupThroughRelay().withDnAdminPassword("not-the-lookup-password"); + + assertThrows( + IllegalStateException.class, + () -> LdapAuthenticator.createLookupConnectionPool(wrongPassword)); + + assertEquals(1, relay.acceptedConnections()); + await().atMost(Duration.ofSeconds(10)).until(() -> relay.openConnections() == 0); + } + + @Test + void closingTheAuthenticatorReleasesItsDirectoryConnections() throws Exception { + LdapAuthenticator authenticator = new LdapAuthenticator(); + setField( + authenticator, + "ldapLookupConnectionPool", + LdapAuthenticator.createLookupConnectionPool(lookupThroughRelay())); + assertEquals(1, relay.openConnections()); + + authenticator.close(); + + await().atMost(Duration.ofSeconds(10)).until(() -> relay.openConnections() == 0); + } + + private LdapConfiguration lookupThroughRelay() { + return new LdapConfiguration() + .withHost(InetAddress.getLoopbackAddress().getHostAddress()) + .withPort(relay.port()) + .withMaxPoolSize(1) + .withDnAdminPrincipal(LOOKUP_DN) + .withDnAdminPassword(LOOKUP_PASSWORD) + .withUserBaseDN(USERS_DN) + .withMailAttributeName("mail"); + } + + private static String findAlice(LDAPConnectionPool pool) throws LDAPSearchException { + return pool.search( + USERS_DN, SearchScope.SUB, Filter.createEqualityFilter("mail", ALICE_EMAIL), "mail") + .getSearchEntries() + .getFirst() + .getDN(); + } + + private static void setField(Object target, String fieldName, Object value) throws Exception { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(target, value); + } + + /** Relays TCP to the directory; {@link #silenceOpenConnections} drops their traffic for good. */ + private static final class SilenceableRelay implements AutoCloseable { + private final ServerSocket listener; + private final int directoryPort; + private final List connections = new CopyOnWriteArrayList<>(); + private final ExecutorService threads = + Executors.newCachedThreadPool( + task -> { + Thread thread = new Thread(task, "ldap-test-relay"); + thread.setDaemon(true); + return thread; + }); + + SilenceableRelay(int directoryPort) throws IOException { + this.directoryPort = directoryPort; + this.listener = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + threads.execute(this::acceptConnections); + } + + int port() { + return listener.getLocalPort(); + } + + void silenceOpenConnections() { + connections.forEach(RelayedConnection::silence); + } + + long openConnections() { + return connections.stream().filter(RelayedConnection::isOpen).count(); + } + + int acceptedConnections() { + return connections.size(); + } + + private void acceptConnections() { + while (!listener.isClosed()) { + try { + Socket client = listener.accept(); + Socket upstream = new Socket(InetAddress.getLoopbackAddress(), directoryPort); + RelayedConnection connection = new RelayedConnection(client, upstream); + connections.add(connection); + threads.execute(() -> connection.relay(client, upstream)); + threads.execute(() -> connection.relay(upstream, client)); + } catch (IOException e) { + // The listener was closed by close(); the loop condition ends accepting. + } + } + } + + @Override + public void close() { + closeQuietly(listener); + connections.forEach(RelayedConnection::close); + threads.shutdownNow(); + } + } + + private static final class RelayedConnection { + private final Socket client; + private final Socket upstream; + private volatile boolean silenced; + + RelayedConnection(Socket client, Socket upstream) { + this.client = client; + this.upstream = upstream; + } + + void silence() { + silenced = true; + } + + boolean isOpen() { + return !client.isClosed(); + } + + void relay(Socket from, Socket to) { + byte[] buffer = new byte[8192]; + try { + InputStream in = from.getInputStream(); + OutputStream out = to.getOutputStream(); + for (int read = in.read(buffer); read != -1; read = in.read(buffer)) { + if (!silenced) { + out.write(buffer, 0, read); + } + } + } catch (IOException e) { + // One side went away; closing both below propagates that to the other side. + } finally { + close(); + } + } + + void close() { + closeQuietly(client); + closeQuietly(upstream); + } + } + + private static void closeQuietly(AutoCloseable closeable) { + try { + closeable.close(); + } catch (Exception e) { + // Teardown of a test relay; there is nothing useful to do with a failed close. + } + } +} From e95aab56371c7efcd296f5ece51ff1eef435e9d8 Mon Sep 17 00:00:00 2001 From: mohitdeuex Date: Mon, 5 Oct 2026 17:38:20 +0530 Subject: [PATCH 2/3] Report the LDAP directory on the Health Check page when LDAP is the provider (#14601) /v1/system/status, which the Health Check page renders, gets an LDAP entry when the login provider is LDAP. It connects the way login does with 5 s timeouts, binds as the lookup account and reads the user base DN, and names the step that failed with the root reason rather than the SDK's nested wrapper text. No entry appears under any other provider, even when LDAP settings are still saved. Test Login's fail-fast connection options move to LdapAuthenticator so both share them. Co-Authored-By: Claude Opus 5.5 --- .../it/tests/SystemResourceIT.java | 3 + .../service/jdbi3/SystemRepository.java | 20 +++ .../security/auth/LdapAuthenticator.java | 9 ++ .../auth/LdapDirectoryValidation.java | 89 ++++++++++++ .../auth/TestLoginCredentialHandler.java | 16 +-- .../jdbi3/SystemRepositoryLdapStatusTest.java | 75 ++++++++++ .../auth/LdapDirectoryValidationTest.java | 131 ++++++++++++++++++ 7 files changed, 331 insertions(+), 12 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapDirectoryValidation.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryLdapStatusTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapDirectoryValidationTest.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java index d52caef43059..dec123e61e61 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java @@ -203,6 +203,9 @@ void test_getSystemStatus() throws Exception { Boolean migrationsPassed = migrations.get("passed").asBoolean(); assertTrue(migrationsPassed, "Database migrations should have passed"); + assertFalse( + statusNode.has("LDAP"), + "The status reports on an LDAP directory only when LDAP is the login provider"); } @Test diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java index 5b12469d49fa..529a78be543f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java @@ -116,7 +116,9 @@ import org.openmetadata.service.security.JwtFilter; import org.openmetadata.service.security.SecurityUtil; import org.openmetadata.service.security.TokenValidityResolver; +import org.openmetadata.service.security.auth.LdapDirectoryValidation; import org.openmetadata.service.security.auth.LoginAttemptCache; +import org.openmetadata.service.security.auth.SecurityConfigurationManager; import org.openmetadata.service.security.auth.validator.Auth0Validator; import org.openmetadata.service.security.auth.validator.AzureAuthValidator; import org.openmetadata.service.security.auth.validator.CognitoAuthValidator; @@ -147,6 +149,7 @@ public class SystemRepository { public static final String INTERNAL_SERVER_ERROR_WITH_REASON = "Internal Server Error. Reason :"; private static final String VECTOR_EMBEDDING_INDEX_KEY = "vectorEmbedding"; private static final String REINDEX_STATUS_VALIDATION_KEY = "Search Reindex Status"; + private static final String LDAP_VALIDATION_KEY = "LDAP"; private final SystemDAO dao; private final MigrationValidationClient migrationValidationClient; @@ -156,6 +159,7 @@ private enum ValidationStepDescription { PIPELINE_SERVICE_CLIENT("Validate that the pipeline service client is available."), JWT_TOKEN("Validate that the ingestion-bot JWT token can be properly decoded."), MIGRATION("Validate that all the necessary migrations have been properly executed."), + LDAP("Validate that the login LDAP directory is reachable and accepts the lookup account."), SEARCH_REINDEX( "Validate that every deployed search index was built from the current index mapping " + "(i.e. no reindex is pending)."); @@ -735,6 +739,8 @@ public ValidationResponse validateSystem( validation.setLogStorage(logStorageValidation); } + addLdapValidation(validation, SecurityConfigurationManager.getCurrentAuthConfig()); + if (Entity.getSearchRepository().isVectorEmbeddingEnabled()) { validation.setAdditionalProperty( "Semantic Search", getEmbeddingsValidation(applicationConfig)); @@ -874,6 +880,20 @@ private void deleteProbeQuietly(AssetService assetService, Asset probe) { public void addExtraValidations( OpenMetadataApplicationConfig applicationConfig, ValidationResponse validation) {} + /** Only an LDAP login depends on the directory, so only then does the status report on it. */ + @VisibleForTesting + static void addLdapValidation( + ValidationResponse validation, AuthenticationConfiguration authConfig) { + if (authConfig != null + && authConfig.getProvider() == AuthProvider.LDAP + && authConfig.getLdapConfiguration() != null) { + validation.setAdditionalProperty( + LDAP_VALIDATION_KEY, + LdapDirectoryValidation.validate(authConfig.getLdapConfiguration()) + .withDescription(ValidationStepDescription.LDAP.key)); + } + } + @VisibleForTesting StepValidation getEmbeddingsValidation(OpenMetadataApplicationConfig applicationConfig) { StepValidation embeddingsValidation = new StepValidation(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java index 734b154f7707..af1766c9b0cb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapAuthenticator.java @@ -92,6 +92,7 @@ public class LdapAuthenticator implements AuthenticatorHandler { // keeps them from silently dropping pooled connections that sit idle between logins. private static final long POOL_HEALTH_CHECK_INTERVAL_MILLIS = 60_000L; private static final long POOL_HEALTH_CHECK_TIMEOUT_MILLIS = 5_000L; + private static final int DIRECTORY_TIMEOUT_MILLIS = 5_000; private static final int MAX_RETRIES = 3; private static final int BASE_DELAY_MS = 500; private static final String DEFAULT_EMAIL_ATTRIBUTE = "mail"; @@ -545,6 +546,14 @@ static LDAPConnection openConnection( connectionOptions, ldapConfiguration.getHost(), ldapConfiguration.getPort()); } + /** For a connection opened on a request thread: an unreachable directory must fail in seconds. */ + static LDAPConnectionOptions boundedConnectionOptions() { + LDAPConnectionOptions options = new LDAPConnectionOptions(); + options.setConnectTimeoutMillis(DIRECTORY_TIMEOUT_MILLIS); + options.setResponseTimeoutMillis(DIRECTORY_TIMEOUT_MILLIS); + return options; + } + /** The attribute login matches the entered email against: emailClaim, else mailAttributeName. */ static String emailAttributeFor( AuthenticationConfiguration authConfig, LdapConfiguration ldapConfiguration) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapDirectoryValidation.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapDirectoryValidation.java new file mode 100644 index 000000000000..9ef2341a3b42 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/LdapDirectoryValidation.java @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Collate. + * 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.openmetadata.service.security.auth; + +import com.unboundid.ldap.sdk.LDAPConnection; +import com.unboundid.ldap.sdk.LDAPException; +import java.security.GeneralSecurityException; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.openmetadata.schema.auth.LdapConfiguration; +import org.openmetadata.schema.system.StepValidation; + +/** + * The LDAP entry of the system status, shown on the Health Check page. It reaches the directory the + * way login does, binds as the lookup account and reads the user base DN, and names the step that + * failed. + */ +public final class LdapDirectoryValidation { + private static final String NO_ATTRIBUTES = "1.1"; + + private LdapDirectoryValidation() {} + + public static StepValidation validate(LdapConfiguration ldap) { + try (LDAPConnection connection = + LdapAuthenticator.openConnection(ldap, LdapAuthenticator.boundedConnectionOptions())) { + return validateLookupAccount(connection, ldap); + } catch (LDAPException | GeneralSecurityException e) { + return failed( + String.format( + "Could not connect to %s:%s: %s", ldap.getHost(), ldap.getPort(), reasonOf(e))); + } + } + + private static StepValidation validateLookupAccount( + LDAPConnection connection, LdapConfiguration ldap) { + try { + connection.bind(ldap.getDnAdminPrincipal(), ldap.getDnAdminPassword()); + } catch (LDAPException e) { + return failed( + String.format( + "The directory rejected the lookup account '%s': %s", + ldap.getDnAdminPrincipal(), reasonOf(e))); + } + return validateUserBaseDn(connection, ldap); + } + + private static StepValidation validateUserBaseDn( + LDAPConnection connection, LdapConfiguration ldap) { + try { + return connection.getEntry(ldap.getUserBaseDN(), NO_ATTRIBUTES) == null + ? failed( + String.format( + "The user base DN '%s' does not exist or the lookup account cannot read it", + ldap.getUserBaseDN())) + : passed(ldap); + } catch (LDAPException e) { + return failed( + String.format( + "Could not read the user base DN '%s': %s", ldap.getUserBaseDN(), reasonOf(e))); + } + } + + private static StepValidation passed(LdapConfiguration ldap) { + return new StepValidation() + .withPassed(Boolean.TRUE) + .withMessage( + String.format( + "Connected to %s:%s, bound as the lookup account and read the user base DN '%s'", + ldap.getHost(), ldap.getPort(), ldap.getUserBaseDN())); + } + + private static StepValidation failed(String message) { + return new StepValidation().withPassed(Boolean.FALSE).withMessage(message); + } + + /** The SDK wraps the useful reason, such as "Connection refused", in layers of its own text. */ + private static String reasonOf(Exception e) { + return TestLoginService.rootMessage(ExceptionUtils.getRootCause(e)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/TestLoginCredentialHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/TestLoginCredentialHandler.java index 35995a7e9c59..c564938694b2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/TestLoginCredentialHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/TestLoginCredentialHandler.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.unboundid.ldap.sdk.Filter; import com.unboundid.ldap.sdk.LDAPConnection; -import com.unboundid.ldap.sdk.LDAPConnectionOptions; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.ResultCode; import com.unboundid.ldap.sdk.SearchRequest; @@ -53,7 +52,6 @@ */ @Slf4j final class TestLoginCredentialHandler { - private static final int DIRECTORY_TIMEOUT_MILLIS = 5_000; private static final Set BASIC_USER_FIELDS = Set.of(USER_PROTECTED_FIELDS, "roles", "teams"); @@ -111,7 +109,8 @@ private static TestLoginResult verifyAgainstDirectory( private static LDAPConnection connectAsLookupAccount(LdapConfiguration ldap) { LDAPConnection connection = null; try { - connection = LdapAuthenticator.openConnection(ldap, boundedTimeouts()); + connection = + LdapAuthenticator.openConnection(ldap, LdapAuthenticator.boundedConnectionOptions()); connection.bind(ldap.getDnAdminPrincipal(), ldap.getDnAdminPassword()); return connection; } catch (Exception e) { @@ -172,7 +171,8 @@ private static DirectoryUser requireSingleMatch( } private static void bindAsUser(LdapConfiguration ldap, DirectoryUser user, String password) { - try (LDAPConnection connection = LdapAuthenticator.openConnection(ldap, boundedTimeouts())) { + try (LDAPConnection connection = + LdapAuthenticator.openConnection(ldap, LdapAuthenticator.boundedConnectionOptions())) { connection.bind(user.dn(), password); } catch (LDAPException e) { throw credentialFailure( @@ -283,14 +283,6 @@ private static List namesOf(List references) { return listOrEmpty(references).stream().map(EntityReference::getName).toList(); } - private static LDAPConnectionOptions boundedTimeouts() { - // An unreachable candidate directory must fail the test quickly, not hold the request thread. - LDAPConnectionOptions options = new LDAPConnectionOptions(); - options.setConnectTimeoutMillis(DIRECTORY_TIMEOUT_MILLIS); - options.setResponseTimeoutMillis(DIRECTORY_TIMEOUT_MILLIS); - return options; - } - private static String localPartOf(String email) { return email.contains("@") ? email.substring(0, email.indexOf('@')) : email; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryLdapStatusTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryLdapStatusTest.java new file mode 100644 index 000000000000..15b1bac56405 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/SystemRepositoryLdapStatusTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Collate. + * 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.openmetadata.service.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.security.AuthenticationConfiguration; +import org.openmetadata.schema.auth.LdapConfiguration; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.schema.system.StepValidation; +import org.openmetadata.schema.system.ValidationResponse; + +/** The Health Check page reports on the LDAP directory only when LDAP is the login provider. */ +class SystemRepositoryLdapStatusTest { + private static final String LDAP_KEY = "LDAP"; + + @Test + void theStatusReportsOnTheDirectoryWhenLdapIsTheProvider() throws IOException { + ValidationResponse validation = new ValidationResponse(); + + SystemRepository.addLdapValidation(validation, withProvider(AuthProvider.LDAP)); + + StepValidation ldapEntry = + assertInstanceOf(StepValidation.class, validation.getAdditionalProperties().get(LDAP_KEY)); + assertFalse(ldapEntry.getPassed(), "nothing listens on the configured port"); + assertNotNull(ldapEntry.getDescription()); + } + + @Test + void theStatusSaysNothingAboutLdapUnderAnotherProvider() throws IOException { + ValidationResponse validation = new ValidationResponse(); + + // Switching away from LDAP can leave its settings saved; they must not bring the entry back. + SystemRepository.addLdapValidation(validation, withProvider(AuthProvider.BASIC)); + SystemRepository.addLdapValidation(validation, null); + + assertFalse(validation.getAdditionalProperties().containsKey(LDAP_KEY)); + } + + private static AuthenticationConfiguration withProvider(AuthProvider provider) + throws IOException { + return new AuthenticationConfiguration() + .withProvider(provider) + .withLdapConfiguration( + new LdapConfiguration() + .withHost(InetAddress.getLoopbackAddress().getHostAddress()) + .withPort(closedLoopbackPort()) + .withDnAdminPrincipal("cn=lookup") + .withDnAdminPassword("lookup-password") + .withUserBaseDN("ou=users,dc=example,dc=com") + .withMailAttributeName("mail")); + } + + private static int closedLoopbackPort() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + return socket.getLocalPort(); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapDirectoryValidationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapDirectoryValidationTest.java new file mode 100644 index 000000000000..c5892b747fe5 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/auth/LdapDirectoryValidationTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2026 Collate. + * 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.openmetadata.service.security.auth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.unboundid.ldap.listener.InMemoryDirectoryServer; +import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; +import com.unboundid.ldap.listener.InMemoryListenerConfig; +import com.unboundid.ldap.sdk.LDAPException; +import com.unboundid.ldif.LDIFException; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.auth.LdapConfiguration; +import org.openmetadata.schema.system.StepValidation; + +/** Runs the Health Check page's LDAP entry against a real, in-process directory. */ +class LdapDirectoryValidationTest { + private static final String BASE_DN = "dc=example,dc=com"; + private static final String USERS_DN = "ou=users," + BASE_DN; + private static final String LOOKUP_DN = "cn=Directory Manager"; + private static final String LOOKUP_PASSWORD = "lookup-password"; + private static final String LOOPBACK = InetAddress.getLoopbackAddress().getHostAddress(); + + private static InMemoryDirectoryServer directory; + + @BeforeAll + static void startDirectory() throws LDAPException, LDIFException { + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(BASE_DN); + config.addAdditionalBindCredentials(LOOKUP_DN, LOOKUP_PASSWORD); + config.setListenerConfigs( + InMemoryListenerConfig.createLDAPConfig( + "default", InetAddress.getLoopbackAddress(), 0, null)); + config.setSchema(null); + directory = new InMemoryDirectoryServer(config); + directory.add("dn: " + BASE_DN, "objectClass: domain", "dc: example"); + directory.add("dn: " + USERS_DN, "objectClass: organizationalUnit", "ou: users"); + directory.startListening(); + } + + @AfterAll + static void stopDirectory() { + directory.shutDown(true); + } + + @Test + void aReachableDirectoryThatAcceptsTheLookupAccountPasses() { + StepValidation result = LdapDirectoryValidation.validate(ldap(LOOKUP_PASSWORD, USERS_DN)); + + assertTrue(result.getPassed(), result.getMessage()); + assertTrue(result.getMessage().contains(LOOPBACK + ":" + directory.getListenPort())); + assertTrue(result.getMessage().contains(USERS_DN)); + } + + @Test + void aRejectedLookupAccountFailsAndNamesTheAccount() { + StepValidation result = + LdapDirectoryValidation.validate(ldap("not-the-lookup-password", USERS_DN)); + + assertFalse(result.getPassed()); + assertTrue( + result.getMessage().contains("rejected the lookup account '" + LOOKUP_DN + "'"), + result.getMessage()); + } + + @Test + void aMissingUserBaseDnFailsAndNamesTheDn() { + String missingDn = "ou=nobody," + BASE_DN; + + StepValidation result = LdapDirectoryValidation.validate(ldap(LOOKUP_PASSWORD, missingDn)); + + assertFalse(result.getPassed()); + assertTrue( + result.getMessage().contains("user base DN '" + missingDn + "' does not exist"), + result.getMessage()); + } + + @Test + void aMalformedUserBaseDnFailsWithTheDirectorysReason() { + String malformedDn = "not a dn"; + + StepValidation result = LdapDirectoryValidation.validate(ldap(LOOKUP_PASSWORD, malformedDn)); + + assertFalse(result.getPassed()); + assertTrue( + result.getMessage().startsWith("Could not read the user base DN '" + malformedDn + "': "), + result.getMessage()); + } + + @Test + void anUnreachableDirectoryFailsAndNamesTheAddress() throws IOException { + int closedPort; + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + closedPort = socket.getLocalPort(); + } + + StepValidation result = + LdapDirectoryValidation.validate(ldap(LOOKUP_PASSWORD, USERS_DN).withPort(closedPort)); + + assertFalse(result.getPassed()); + assertEquals( + "Could not connect to " + LOOPBACK + ":" + closedPort + ": Connection refused", + result.getMessage()); + } + + private static LdapConfiguration ldap(String lookupPassword, String userBaseDn) { + return new LdapConfiguration() + .withHost(LOOPBACK) + .withPort(directory.getListenPort()) + .withDnAdminPrincipal(LOOKUP_DN) + .withDnAdminPassword(lookupPassword) + .withUserBaseDN(userBaseDn) + .withMailAttributeName("mail"); + } +} From a51c3e7d2bdf7fecbc5f10d8379c4c7f4960f52f Mon Sep 17 00:00:00 2001 From: mohitdeuex Date: Mon, 5 Oct 2026 21:06:51 +0530 Subject: [PATCH 3/3] Close the auth handlers a failed security reload already replaced (#14601) A reload swaps in the new handlers before it initializes the authenticator, so one that fails afterwards (an unreachable directory, a wrong lookup password) left the replaced handlers open with nothing routing to them, and an LDAP one kept probing the old directory. Close whatever the reload replaced in a finally. A handler it never replaced is still serving logins and stays open, and a failing close is logged rather than thrown. Co-Authored-By: Claude Opus 5.5 --- .../service/OpenMetadataApplication.java | 49 +++++++++++--- ...OpenMetadataApplicationAuthReloadTest.java | 64 +++++++++++++++++++ 2 files changed, 104 insertions(+), 9 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java index ac236b9940ee..702153292cb5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java @@ -16,6 +16,7 @@ import static org.openmetadata.service.util.jdbi.JdbiUtils.createAndSetupJDBI; import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.common.annotations.VisibleForTesting; import io.dropwizard.configuration.EnvironmentVariableSubstitutor; import io.dropwizard.configuration.SubstitutingSourceProvider; import io.dropwizard.core.Application; @@ -944,12 +945,12 @@ private void validateConfiguration(OpenMetadataApplicationConfig catalogConfig) public void reinitializeAuthSystem( OpenMetadataApplicationConfig config, Environment environment) { + MutableServletContextHandler contextHandler = environment.getApplicationContext(); + AuthServeletHandler previousHandler = + AuthServeletHandlerRegistry.getHandler(contextHandler.getServletContext()); + AuthenticatorHandler previousAuthenticator = authenticatorHandler; try { LOG.info("Starting authentication system reinitialization"); - MutableServletContextHandler contextHandler = environment.getApplicationContext(); - AuthServeletHandler previousHandler = - AuthServeletHandlerRegistry.getHandler(contextHandler.getServletContext()); - AuthenticatorHandler previousAuthenticator = authenticatorHandler; SessionService sessionService = AuthServeletHandlerRegistry.getSessionService(contextHandler.getServletContext()); if (sessionService == null) { @@ -987,17 +988,47 @@ public void reinitializeAuthSystem( registerSamlServlets(config, environment); } - // An LDAP handler left open would keep its pool connected to, and probing, the directory - // it was built for, even after the provider moved away from LDAP. - previousHandler.close(); - previousAuthenticator.close(); - LOG.info("Successfully reinitialized authentication system"); } catch (Exception e) { LOG.error("Failed to reinitialize authentication system", e); // Trigger rollback in AuthenticationConfigurationManager // Rollback is handled internally by SecurityConfigurationManager throw new RuntimeException("Authentication system reinitialization failed", e); + } finally { + closeReplacedAuthHandlers( + previousHandler, + AuthServeletHandlerRegistry.getHandler(contextHandler.getServletContext()), + previousAuthenticator, + authenticatorHandler); + } + } + + /** + * Closes the handlers a security reload swapped out, including when the reload failed after the + * swap: nothing routes to them any more, and an LDAP one would otherwise keep its pool probing + * the directory it was built for. A handler the reload never replaced is still serving logins + * and stays open. Every reload builds new instances, so identity tells the two apart. + */ + @VisibleForTesting + static void closeReplacedAuthHandlers( + AuthServeletHandler previousHandler, + AuthServeletHandler currentHandler, + AuthenticatorHandler previousAuthenticator, + AuthenticatorHandler currentAuthenticator) { + if (previousHandler != currentHandler) { + closeQuietly(previousHandler::close); + } + if (previousAuthenticator != currentAuthenticator) { + closeQuietly(previousAuthenticator::close); + } + } + + /** A failed close must neither hide the reload's own error nor fail a reload that worked. */ + private static void closeQuietly(Runnable close) { + try { + close.run(); + } catch (RuntimeException e) { + LOG.warn("Could not close an auth handler replaced by a security reload", e); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java new file mode 100644 index 000000000000..ff02aebb1a17 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2026 Collate. + * 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.openmetadata.service; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.Test; +import org.openmetadata.service.security.AuthServeletHandler; +import org.openmetadata.service.security.auth.AuthenticatorHandler; + +/** Which auth handlers a security reload closes, whether or not the reload itself succeeded. */ +class OpenMetadataApplicationAuthReloadTest { + private final AuthServeletHandler previousHandler = mock(AuthServeletHandler.class); + private final AuthServeletHandler currentHandler = mock(AuthServeletHandler.class); + private final AuthenticatorHandler previousAuthenticator = mock(AuthenticatorHandler.class); + private final AuthenticatorHandler currentAuthenticator = mock(AuthenticatorHandler.class); + + @Test + void closesTheHandlersAReloadReplacedEvenIfItFailedAfterTheSwap() { + OpenMetadataApplication.closeReplacedAuthHandlers( + previousHandler, currentHandler, previousAuthenticator, currentAuthenticator); + + verify(previousHandler).close(); + verify(previousAuthenticator).close(); + verify(currentHandler, never()).close(); + verify(currentAuthenticator, never()).close(); + } + + @Test + void leavesOpenTheHandlersAReloadNeverReplaced() { + // A reload that failed before reaching the swap leaves the old handlers serving logins. + OpenMetadataApplication.closeReplacedAuthHandlers( + previousHandler, previousHandler, previousAuthenticator, previousAuthenticator); + + verify(previousHandler, never()).close(); + verify(previousAuthenticator, never()).close(); + } + + @Test + void aFailingCloseNeitherEscapesNorSkipsTheOtherHandler() { + doThrow(new IllegalStateException("pool already gone")).when(previousHandler).close(); + + assertDoesNotThrow( + () -> + OpenMetadataApplication.closeReplacedAuthHandlers( + previousHandler, currentHandler, previousAuthenticator, currentAuthenticator)); + + verify(previousAuthenticator).close(); + } +}