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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -947,9 +948,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();
SessionService sessionService =
AuthServeletHandlerRegistry.getSessionService(contextHandler.getServletContext());
if (sessionService == null) {
Expand Down Expand Up @@ -993,6 +997,41 @@ public void reinitializeAuthSystem(
// 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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand All @@ -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).");
Expand Down Expand Up @@ -739,6 +743,8 @@ public ValidationResponse validateSystem(
validation.setLogStorage(logStorageValidation);
}

addLdapValidation(validation, SecurityConfigurationManager.getCurrentAuthConfig());

if (Entity.getSearchRepository().isVectorEmbeddingEnabled()) {
validation.setAdditionalProperty(
"Semantic Search", getEmbeddingsValidation(applicationConfig));
Expand Down Expand Up @@ -878,6 +884,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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -85,6 +87,12 @@
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 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";
Expand All @@ -101,7 +109,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.");
Expand All @@ -115,38 +123,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
Expand Down Expand Up @@ -516,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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}
Loading
Loading