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
2 changes: 2 additions & 0 deletions conf/openmetadata-h2-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,8 @@ cacheMemory:
logging:
level: ${LOG_LEVEL:-INFO}
loggers:
org.eclipse.jetty:
level: ${JETTY_LOG_LEVEL:-INFO}
org.openmetadata.service.util.jdbi.OMSqlLogger:
level: ${SQL_LOG_LEVEL:-INFO}
additive: false
Expand Down
6 changes: 6 additions & 0 deletions conf/openmetadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,12 @@ cacheMemory:
logging:
level: ${LOG_LEVEL:-INFO}
loggers:
# LOG_LEVEL sets the ROOT logger, and at DEBUG Jetty's HttpParser prints every request header
# verbatim — including `Authorization: Bearer <jwt>` and `Cookie: OM_SESSION=<id>`. DEBUG is
# exactly what support asks customers to enable and those logs get attached to tickets, so pin
# the framework logger independently of LOG_LEVEL.
org.eclipse.jetty:
level: ${JETTY_LOG_LEVEL:-INFO}
org.openmetadata.service.util.jdbi.OMSqlLogger:
level: ${SQL_LOG_LEVEL:-INFO}
additive: false
Expand Down
5 changes: 5 additions & 0 deletions docker/development/distributed-test/local/server1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ server:
# Set LOG_FORMAT=json for structured logs. The default text format preserves legacy output.
logging:
level: ${LOG_LEVEL:-INFO}
loggers:
# ROOT at DEBUG makes Jetty's HttpParser log every header verbatim, including Authorization
# bearer tokens and OM_SESSION cookies. Pin it so LOG_LEVEL=DEBUG stays safe to share.
org.eclipse.jetty:
level: ${JETTY_LOG_LEVEL:-INFO}
appenders:
- type: console
threshold: INFO
Expand Down
5 changes: 5 additions & 0 deletions docker/development/distributed-test/local/server2.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ server:
# Set LOG_FORMAT=json for structured logs. The default text format preserves legacy output.
logging:
level: ${LOG_LEVEL:-INFO}
loggers:
# ROOT at DEBUG makes Jetty's HttpParser log every header verbatim, including Authorization
# bearer tokens and OM_SESSION cookies. Pin it so LOG_LEVEL=DEBUG stays safe to share.
org.eclipse.jetty:
level: ${JETTY_LOG_LEVEL:-INFO}
appenders:
- type: console
threshold: INFO
Expand Down
5 changes: 5 additions & 0 deletions docker/development/distributed-test/local/server3.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ server:
# Set LOG_FORMAT=json for structured logs. The default text format preserves legacy output.
logging:
level: ${LOG_LEVEL:-INFO}
loggers:
# ROOT at DEBUG makes Jetty's HttpParser log every header verbatim, including Authorization
# bearer tokens and OM_SESSION cookies. Pin it so LOG_LEVEL=DEBUG stays safe to share.
org.eclipse.jetty:
level: ${JETTY_LOG_LEVEL:-INFO}
appenders:
- type: console
threshold: INFO
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,14 @@
import org.openmetadata.service.search.InheritedFieldEntitySearch.InheritedFieldResult;
import org.openmetadata.service.secrets.SecretsManager;
import org.openmetadata.service.secrets.SecretsManagerFactory;
import org.openmetadata.service.security.AuthServeletHandlerRegistry;
import org.openmetadata.service.security.SecurityUtil;
import org.openmetadata.service.security.auth.BotTokenCache;
import org.openmetadata.service.security.auth.SecurityConfigurationManager;
import org.openmetadata.service.security.auth.UserActivityTracker;
import org.openmetadata.service.security.policyevaluator.SubjectCache;
import org.openmetadata.service.security.policyevaluator.SubjectContext;
import org.openmetadata.service.security.session.SessionService;
import org.openmetadata.service.util.AsyncService;
import org.openmetadata.service.util.EntityUtil;
import org.openmetadata.service.util.EntityUtil.Fields;
Expand Down Expand Up @@ -1327,6 +1329,7 @@ protected void postDelete(User entity, boolean hardDelete) {
if (Boolean.TRUE.equals(entity.getIsBot())) {
BotTokenCache.invalidateToken(entity.getName());
}
revokeLiveSessions(entity);
// Lightweight app-managed table, no FK - clean up explicitly rather than via cascade.
userPreferencesRepository.delete(entity.getId());
deleteSuggestionTasksForUser(entity);
Expand All @@ -1342,6 +1345,27 @@ protected void postDelete(User entity, boolean hardDelete) {
});
}

/**
* Soft delete is the normal off-boarding action in the UI, so it has to cut live access too — the
* user's existing session-bound tokens keep working until natural expiry (7 days by default)
* otherwise. Revocation notifies the WebSocket/cross-pod listeners, so peer pods drop the user's
* sockets as well.
*/
private void revokeLiveSessions(User entity) {
SessionService sessionService = AuthServeletHandlerRegistry.getSessionService();
if (sessionService == null || entity.getId() == null) {
return;
}
try {
int revoked = sessionService.revokeSessionsForUser(entity.getId().toString());
if (revoked > 0) {
LOG.info("Revoked {} session(s) for deleted user {}", revoked, entity.getName());
}
} catch (Exception e) {
LOG.error("Failed to revoke sessions for deleted user {}", entity.getName(), e);
}
}

private void deleteSuggestionTasksForUser(User entity) {
Retry retry = Retry.of("user-task-cleanup", TASK_CLEANUP_RETRY_CONFIG);
retry
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
Expand Down Expand Up @@ -85,6 +86,8 @@ public class JwtFilter implements ContainerRequestFilter {
public static final String IMPERSONATED_USER_CLAIM = "impersonatedUser";
public static final String IMPERSONATE_USER_HEADER = "X-Impersonate-User";
public static final String ACTIVE_PERSONA_HEADER = "X-OpenMetadata-Persona";
private static final Set<String> NATIVE_PASSWORD_PROVIDER_VALUES =
Set.of(AuthProvider.BASIC.value(), AuthProvider.OPENMETADATA.value());
@Getter private List<String> jwtPrincipalClaims;
@Getter private Map<String, String> jwtPrincipalClaimsMapping;
@Getter private String jwtTeamClaimMapping;
Expand Down Expand Up @@ -148,10 +151,21 @@ public JwtFilter(
List<String> jwtPrincipalClaims,
String principalDomain,
boolean enforcePrincipalDomain) {
this(jwkProvider, jwtPrincipalClaims, principalDomain, enforcePrincipalDomain, null);
}

@VisibleForTesting
JwtFilter(
JwkProvider jwkProvider,
List<String> jwtPrincipalClaims,
String principalDomain,
boolean enforcePrincipalDomain,
AuthProvider providerType) {
this.jwkProvider = jwkProvider;
this.jwtPrincipalClaims = jwtPrincipalClaims;
this.principalDomain = principalDomain;
this.enforcePrincipalDomain = enforcePrincipalDomain;
this.providerType = providerType;
this.tokenValidationAlgorithm = AuthenticationConfiguration.TokenValidationAlgorithm.RS_256;
}

Expand Down Expand Up @@ -418,13 +432,53 @@ private void validateSessionBoundToken(Map<String, Claim> claims, String userNam
|| !session.getUsername().equalsIgnoreCase(userName)) {
throw AuthenticationException.getInvalidTokenException("Invalid session.");
}
validateSessionProviderIsCurrent(session);
try {
sessionService.recordSessionAccess(session);
} catch (Exception e) {
LOG.warn("Failed to record session access for session {}", session.getId(), e);
}
}

/**
* Sessions record the provider that authenticated them. Swapping {@code AUTHENTICATION_PROVIDER}
* decommissions that provider, so sessions minted under it must stop working immediately instead of
* living on until natural expiry — otherwise off-boarding a user by moving IdPs leaves their old
* token valid for up to a week. Checked per request against this pod's current config, so it holds
* on every pod without a session sweep.
*/
private void validateSessionProviderIsCurrent(UserSession session) {
String sessionProvider = session.getProvider();
if (nullOrEmpty(sessionProvider) || providerType == null) {
return;
}
if (!isSameProvider(sessionProvider, providerType.value())) {
LOG.warn(
"Rejecting session {} issued by provider {} — the configured provider is now {}",
SessionService.truncateId(session.getId()),
sessionProvider,
providerType.value());
throw AuthenticationException.getInvalidTokenException(
"Session was issued by a provider that is no longer configured.");
}
}

/**
* {@code basic} and {@code openmetadata} are two historical names for the same native-password
* authenticator — {@code SecurityConfigurationManager.isNativePasswordProvider} treats them
* interchangeably and one servlet handler serves both. Renaming one to the other is not a provider
* swap and must not log the whole deployment out.
*/
private static boolean isSameProvider(String sessionProvider, String configuredProvider) {
return sessionProvider.equalsIgnoreCase(configuredProvider)
|| (isNativePasswordProviderValue(sessionProvider)
&& isNativePasswordProviderValue(configuredProvider));
}

private static boolean isNativePasswordProviderValue(String provider) {
return NATIVE_PASSWORD_PROVIDER_VALUES.contains(provider.toLowerCase(Locale.ROOT));
}

public CatalogSecurityContext getCatalogSecurityContext(String token) {
Map<String, Claim> claims = validateJwtAndGetClaims(token);
String userName = findUserNameFromClaims(jwtPrincipalClaimsMapping, jwtPrincipalClaims, claims);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MultivaluedHashMap;
Expand All @@ -47,7 +48,9 @@
import org.openmetadata.schema.api.configuration.LoginConfiguration;
import org.openmetadata.schema.settings.SettingsType;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.sdk.exception.WebServiceException;
import org.openmetadata.service.OpenMetadataApplicationConfig;
import org.openmetadata.service.exception.EntityNotFoundException;
import org.openmetadata.service.resources.settings.SettingsCache;
import org.openmetadata.service.security.auth.CatalogSecurityContext;

Expand Down Expand Up @@ -410,6 +413,60 @@ public static void writeErrorResponse(HttpServletResponse response, int status,
JsonUtils.pojoToJson(Map.of("error", message == null ? StringUtils.EMPTY : message)));
}

/**
* Writes a failure on a servlet auth path with the status the failure actually deserves. These
* paths have no JAX-RS exception mapper, so a bare {@code 500 + e.getMessage()} catch-all reports a
* rejected credential as a server bug — which is how a login by a deleted user came back as a 500 —
* and puts the exception text on the wire while doing it. A rejected credential is the caller's
* 4xx; only the rest is a 500, and that one carries a generic message because an unclassified
* exception's text is an internal detail. Callers log the failure before delegating here, so
* nothing is lost.
*/
public static void writeFailureResponse(HttpServletResponse response, Throwable failure) {
// Default generic: an unclassified failure is a server fault whose message is an internal
// detail. It stays in the log, not on the wire.
int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
String message = "Authentication service error";
// EntityNotFoundException is checked first on purpose: it extends the SDK's WebServiceException
// with NOT_FOUND, and answering 404 on a login endpoint tells an unauthenticated caller which
// accounts exist. A user that no longer resolves is a rejected credential, not a lookup miss.
if (failure instanceof EntityNotFoundException) {
status = HttpServletResponse.SC_UNAUTHORIZED;
message = "Invalid credentials";
} else if (carriesResponseStatus(failure)) {
status = responseStatusOf(failure);
message = failure.getMessage();
}
try {
writeErrorResponse(response, status, message);
} catch (IOException e) {
LOG.error("Error writing error response", e);
}
}

/**
* Three unrelated hierarchies carry an intended HTTP status and none of them share a supertype:
* JAX-RS {@link WebApplicationException}, {@link AuthenticationException}, and the SDK's {@link
* WebServiceException} (the parent of {@code CustomExceptionMessage}, which is what the basic and
* LDAP authenticators throw for a rejected credential). Missing any one of them reports a 4xx as a
* 500.
*/
private static boolean carriesResponseStatus(Throwable failure) {
return failure instanceof WebApplicationException
|| failure instanceof AuthenticationException
|| failure instanceof WebServiceException;
}

private static int responseStatusOf(Throwable failure) {
if (failure instanceof WebApplicationException webApplicationException) {
return webApplicationException.getResponse().getStatus();
}
if (failure instanceof AuthenticationException authenticationException) {
return authenticationException.getResponse().getStatus();
}
return ((WebServiceException) failure).getResponse().getStatus();
}

public static void writeMessageResponse(HttpServletResponse response, int status, String message)
throws IOException {
response.setStatus(status);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.openmetadata.service.security.auth;

import static org.openmetadata.service.security.SecurityUtil.writeErrorResponse;
import static org.openmetadata.service.security.SecurityUtil.writeFailureResponse;
import static org.openmetadata.service.security.SecurityUtil.writeJsonResponse;
import static org.openmetadata.service.security.SecurityUtil.writeMessageResponse;
import static org.openmetadata.service.util.UserUtil.getRoleListFromUser;
Expand Down Expand Up @@ -110,7 +111,7 @@ public void handleLogin(HttpServletRequest req, HttpServletResponse resp) {

} catch (Exception e) {
LOG.error("Error handling login", e);
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
writeFailureResponse(resp, e);
}
}

Expand Down Expand Up @@ -178,7 +179,7 @@ public void handleRefresh(HttpServletRequest req, HttpServletResponse resp) {
} catch (Exception e) {
sessionService.releaseRefreshLease(leasedSession);
LOG.error("Error handling refresh", e);
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
writeFailureResponse(resp, e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static jakarta.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE;
import static jakarta.ws.rs.core.Response.Status.UNAUTHORIZED;
import static org.openmetadata.service.security.SecurityUtil.writeErrorResponse;
import static org.openmetadata.service.security.SecurityUtil.writeFailureResponse;
import static org.openmetadata.service.security.SecurityUtil.writeJsonResponse;
import static org.openmetadata.service.security.SecurityUtil.writeMessageResponse;
import static org.openmetadata.service.util.UserUtil.getRoleListFromUser;
Expand Down Expand Up @@ -126,7 +127,7 @@ public void handleLogin(HttpServletRequest req, HttpServletResponse resp) {
sendError(resp, statusCode, e.getMessage());
} catch (Exception e) {
LOG.error("Unexpected error handling LDAP login", e);
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Authentication service error");
writeFailureResponse(resp, e);
}
}

Expand Down Expand Up @@ -197,7 +198,7 @@ public void handleRefresh(HttpServletRequest req, HttpServletResponse resp) {
} catch (Exception e) {
sessionService.releaseRefreshLease(leasedSession);
LOG.error("Error handling refresh", e);
sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
writeFailureResponse(resp, e);
}
}

Expand Down
Loading
Loading