diff --git a/conf/openmetadata-h2-test.yaml b/conf/openmetadata-h2-test.yaml index 30f3382f2b2c..555268cf2b17 100644 --- a/conf/openmetadata-h2-test.yaml +++ b/conf/openmetadata-h2-test.yaml @@ -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 diff --git a/conf/openmetadata.yaml b/conf/openmetadata.yaml index c23edd0379d7..fc28e5c5a7b9 100644 --- a/conf/openmetadata.yaml +++ b/conf/openmetadata.yaml @@ -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 ` and `Cookie: OM_SESSION=`. 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 diff --git a/docker/development/distributed-test/local/server1.yaml b/docker/development/distributed-test/local/server1.yaml index 5fbcbcc1d536..8d169533b175 100644 --- a/docker/development/distributed-test/local/server1.yaml +++ b/docker/development/distributed-test/local/server1.yaml @@ -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 diff --git a/docker/development/distributed-test/local/server2.yaml b/docker/development/distributed-test/local/server2.yaml index e80c1436e258..b25d2943fa39 100644 --- a/docker/development/distributed-test/local/server2.yaml +++ b/docker/development/distributed-test/local/server2.yaml @@ -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 diff --git a/docker/development/distributed-test/local/server3.yaml b/docker/development/distributed-test/local/server3.yaml index 463386e9d734..6c8c1185fc77 100644 --- a/docker/development/distributed-test/local/server3.yaml +++ b/docker/development/distributed-test/local/server3.yaml @@ -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 diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java index fc484f1c6678..e20207a7fa93 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java @@ -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; @@ -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); @@ -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 diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java index 98afa6e59384..5b0efad95a15 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java @@ -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; @@ -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 NATIVE_PASSWORD_PROVIDER_VALUES = + Set.of(AuthProvider.BASIC.value(), AuthProvider.OPENMETADATA.value()); @Getter private List jwtPrincipalClaims; @Getter private Map jwtPrincipalClaimsMapping; @Getter private String jwtTeamClaimMapping; @@ -148,10 +151,21 @@ public JwtFilter( List jwtPrincipalClaims, String principalDomain, boolean enforcePrincipalDomain) { + this(jwkProvider, jwtPrincipalClaims, principalDomain, enforcePrincipalDomain, null); + } + + @VisibleForTesting + JwtFilter( + JwkProvider jwkProvider, + List 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; } @@ -418,6 +432,7 @@ private void validateSessionBoundToken(Map claims, String userNam || !session.getUsername().equalsIgnoreCase(userName)) { throw AuthenticationException.getInvalidTokenException("Invalid session."); } + validateSessionProviderIsCurrent(session); try { sessionService.recordSessionAccess(session); } catch (Exception e) { @@ -425,6 +440,45 @@ private void validateSessionBoundToken(Map claims, String userNam } } + /** + * 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 claims = validateJwtAndGetClaims(token); String userName = findUserNameFromClaims(jwtPrincipalClaimsMapping, jwtPrincipalClaims, claims); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java index 1d87b1004ccb..44678d679e17 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java @@ -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; @@ -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; @@ -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); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/BasicAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/BasicAuthServletHandler.java index f818a8f1efc2..99461ac97713 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/BasicAuthServletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/auth/BasicAuthServletHandler.java @@ -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; @@ -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); } } @@ -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); } } 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 b30db6aef166..264e6b46619f 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 @@ -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; @@ -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); } } @@ -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); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/session/SessionService.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/session/SessionService.java index 4e11b42a9bed..539186e586f4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/session/SessionService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/session/SessionService.java @@ -32,6 +32,8 @@ public class SessionService implements Managed { private static final int SESSION_LIMIT_MAX_ITERATIONS = 20; private static final int SESSION_LIMIT_LOOKUP_MULTIPLIER = 4; private static final long SESSION_ACCESS_UPDATE_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(5); + private static final List REVOCABLE_STATUSES = + List.of(SessionStatus.ACTIVE, SessionStatus.REFRESHING); private volatile AuthenticationConfiguration authConfig; private final SessionStore repository; @@ -606,6 +608,65 @@ private int getMaxActiveSessionsPerUser() { : DEFAULT_MAX_ACTIVE_SESSIONS_PER_USER; } + /** + * Revokes every revocable session for a user. Called when the user is deleted (soft or hard) or + * otherwise off-boarded — without it a soft-deleted user keeps API access until their token + * expires. Bounded: each pass reads at most {@link #CLEANUP_BATCH_SIZE} sessions per status and the + * loop is capped, so a user with a pathological session count degrades rather than spinning. + */ + public int revokeSessionsForUser(String userId) { + int revoked = 0; + if (!nullOrEmpty(userId)) { + java.util.Set previousBatchIds = java.util.Collections.emptySet(); + for (int attempt = 0; attempt < SESSION_LIMIT_MAX_ITERATIONS; attempt++) { + List sessions = findRevocableSessions(userId); + if (sessions.isEmpty()) { + break; + } + java.util.Set currentBatchIds = + sessions.stream().map(UserSession::getId).collect(java.util.stream.Collectors.toSet()); + // A revoke that loses every compare-and-set leaves the session where it was, so the next + // pass + // reads the same batch back. Stop instead of burning every remaining pass on rows that will + // not move; the cleanup sweep expires them at their timeout. + if (currentBatchIds.equals(previousBatchIds)) { + LOG.warn( + "Unable to revoke {} session(s) for user {}; leaving them to session cleanup", + currentBatchIds.size(), + userId); + break; + } + for (UserSession session : sessions) { + if (revokeSession(session.getId()).filter(SessionService::isTerminal).isPresent()) { + revoked++; + } + } + previousBatchIds = currentBatchIds; + } + } + return revoked; + } + + /** + * {@code REFRESHING} has to be included, not just {@code ACTIVE}: a session mid-refresh holds a + * lease and is invisible to an ACTIVE-only lookup, and {@code completeRefresh} / + * {@link #releaseRefreshLease} put it back to {@code ACTIVE} afterwards — so a user deleted inside + * that window would keep a live session. {@code PENDING} is not revocable by user because a login + * in flight has no user attached yet ({@code createPendingSession} sets no {@code userId}). + */ + private List findRevocableSessions(String userId) { + List sessions = new ArrayList<>(); + for (SessionStatus status : REVOCABLE_STATUSES) { + sessions.addAll(repository.findByUserIdAndStatus(userId, status, CLEANUP_BATCH_SIZE)); + } + return sessions; + } + + private static boolean isTerminal(UserSession session) { + return session.getStatus() == SessionStatus.REVOKED + || session.getStatus() == SessionStatus.EXPIRED; + } + private int sessionLookupLimit(int maxActiveSessionsPerUser) { long lookupLimit = (long) maxActiveSessionsPerUser * SESSION_LIMIT_LOOKUP_MULTIPLIER; return lookupLimit > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) lookupLimit; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java index 46e7fbeee442..7b3cd56547d1 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java @@ -51,6 +51,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.openmetadata.schema.auth.ServiceTokenType; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; import org.openmetadata.service.Entity; import org.openmetadata.service.security.auth.CatalogSecurityContext; import org.openmetadata.service.security.auth.UserTokenCache; @@ -494,4 +495,71 @@ private static ContainerRequestContext createRequestContextWithJwt(String jwt) { return context; } + + private static SessionService sessionServiceReturning(UserSession session) { + SessionService sessionService = mock(SessionService.class); + when(sessionService.getFreshSessionById(session.getId())).thenReturn(Optional.of(session)); + return sessionService; + } + + private static UserSession activeSession(String id, String username, String provider) { + return UserSession.builder() + .id(id) + .username(username) + .provider(provider) + .status(SessionStatus.ACTIVE) + .expiresAt(System.currentTimeMillis() + 60_000) + .idleExpiresAt(System.currentTimeMillis() + 60_000) + .build(); + } + + private static String sessionBoundJwt(String userName, String sessionId) { + return JWT.create() + .withExpiresAt(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) + .withClaim("sub", userName) + .withClaim(TOKEN_TYPE, ServiceTokenType.OM_USER.value()) + .withClaim(JWTTokenGenerator.SESSION_ID_CLAIM, sessionId) + .sign(algorithm); + } + + @Test + void sessionIssuedUnderTheOtherNativePasswordProviderNameIsAccepted() { + // basic and openmetadata are two names for the same native-password authenticator. Renaming one + // to the other is not a provider swap, so it must not invalidate every live session. + UserSession openMetadataSession = activeSession("session-1", "sam", "openmetadata"); + AuthServeletHandlerRegistry.setSessionService( + null, sessionServiceReturning(openMetadataSession)); + JwtFilter basicProviderFilter = + new JwtFilter( + jwkProvider, List.of("sub", "email"), "openmetadata.org", false, AuthProvider.BASIC); + + try { + ContainerRequestContext context = + createRequestContextWithJwt(sessionBoundJwt("sam", "session-1")); + basicProviderFilter.filter(context); + verify(context, times(1)) + .setSecurityContext(org.mockito.ArgumentMatchers.any(SecurityContext.class)); + } finally { + AuthServeletHandlerRegistry.setSessionService(null, null); + } + } + + @Test + void sessionIssuedByDecommissionedProviderIsRejected() { + UserSession googleSession = activeSession("session-1", "sam", "google"); + AuthServeletHandlerRegistry.setSessionService(null, sessionServiceReturning(googleSession)); + JwtFilter basicProviderFilter = + new JwtFilter( + jwkProvider, List.of("sub", "email"), "openmetadata.org", false, AuthProvider.BASIC); + + try { + ContainerRequestContext context = + createRequestContextWithJwt(sessionBoundJwt("sam", "session-1")); + Exception exception = + assertThrows(AuthenticationException.class, () -> basicProviderFilter.filter(context)); + assertTrue(exception.getMessage().toLowerCase(Locale.ROOT).contains("no longer configured")); + } finally { + AuthServeletHandlerRegistry.setSessionService(null, null); + } + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java index 7ca190b5c14f..5ec2c0ce67a4 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java @@ -19,6 +19,7 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.client.Invocation; import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -33,6 +34,8 @@ import org.openmetadata.schema.api.configuration.LoginConfiguration; import org.openmetadata.schema.api.security.AuthorizerConfiguration; import org.openmetadata.service.OpenMetadataApplicationConfig; +import org.openmetadata.service.exception.CustomExceptionMessage; +import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.resources.settings.SettingsCache; import org.openmetadata.service.security.auth.CatalogSecurityContext; @@ -515,6 +518,65 @@ void testWriteJsonResponseSetsBodyHeadersAndStatus() throws IOException { assertEquals("{\"ok\":true}", outputStream.content()); } + @Test + void testWriteFailureResponseMapsMissingUserToUnauthorized() throws IOException { + HttpServletResponse response = mock(HttpServletResponse.class); + RecordingServletOutputStream outputStream = new RecordingServletOutputStream(); + when(response.getOutputStream()).thenReturn(outputStream); + + SecurityUtil.writeFailureResponse(response, new EntityNotFoundException("user not found")); + + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + assertTrue(outputStream.content().contains("Invalid credentials")); + } + + @Test + void testWriteFailureResponseKeepsStatusOfRejectedCredentials() throws IOException { + HttpServletResponse response = mock(HttpServletResponse.class); + RecordingServletOutputStream outputStream = new RecordingServletOutputStream(); + when(response.getOutputStream()).thenReturn(outputStream); + + // What BasicAuthenticator throws for a bad password: carries a 401 Response but is not a + // WebApplicationException, so it used to fall through to a 500. + SecurityUtil.writeFailureResponse( + response, new AuthenticationException("You have entered an invalid username or password.")); + + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + void testWriteFailureResponseKeepsStatusOfCustomExceptionMessage() throws IOException { + HttpServletResponse response = mock(HttpServletResponse.class); + RecordingServletOutputStream outputStream = new RecordingServletOutputStream(); + when(response.getOutputStream()).thenReturn(outputStream); + + // What a login for a soft-deleted user actually reaches this method as: CustomExceptionMessage + // extends the SDK's WebServiceException, which is a plain RuntimeException — so without an + // explicit branch its 4xx was reported as a 500. + SecurityUtil.writeFailureResponse( + response, + new CustomExceptionMessage( + Response.Status.BAD_REQUEST, + "INVALID_USER_OR_PASSWORD", + "You have entered an invalid username or password.")); + + verify(response).setStatus(HttpServletResponse.SC_BAD_REQUEST); + assertTrue(outputStream.content().contains("invalid username or password")); + } + + @Test + void testWriteFailureResponseFallsBackToServerError() throws IOException { + HttpServletResponse response = mock(HttpServletResponse.class); + RecordingServletOutputStream outputStream = new RecordingServletOutputStream(); + when(response.getOutputStream()).thenReturn(outputStream); + + SecurityUtil.writeFailureResponse(response, new IllegalStateException("boom")); + + verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + // The exception text is an internal detail: callers log it, the client gets a generic message. + assertFalse(outputStream.content().contains("boom")); + } + @Test void testIsBotHelpersReadBooleanClaimValues() { assertTrue(SecurityUtil.isBot(Map.of("isBot", booleanClaim(true)))); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/session/SessionServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/session/SessionServiceTest.java index e994c1438e70..07ca259e9adb 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/session/SessionServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/session/SessionServiceTest.java @@ -889,6 +889,97 @@ private UserSession pendingSession(String id, long expiresAt) { .build(); } + @Test + void revokeSessionsForUser_revokesEveryActiveSession() { + User user = + new User() + .withId(UUID.randomUUID()) + .withName("offboarded-user") + .withEmail("offboarded-user@example.com"); + UserSession first = activeSession(validSessionId('a'), user, 1L, 1L); + UserSession second = activeSession(validSessionId('b'), user, 2L, 2L); + when(repository.findByUserIdAndStatus( + eq(user.getId().toString()), eq(SessionStatus.ACTIVE), anyInt())) + .thenReturn(List.of(first, second), List.of()); + when(repository.findByUserIdAndStatus( + eq(user.getId().toString()), eq(SessionStatus.REFRESHING), anyInt())) + .thenReturn(List.of()); + when(repository.findById(first.getId())).thenReturn(Optional.of(first)); + when(repository.findById(second.getId())).thenReturn(Optional.of(second)); + when(repository.updateIfVersion(any(UserSession.class), anyLong())).thenReturn(true); + + assertEquals(2, sessionService.revokeSessionsForUser(user.getId().toString())); + + ArgumentCaptor revoked = ArgumentCaptor.forClass(UserSession.class); + verify(repository, times(2)).updateIfVersion(revoked.capture(), anyLong()); + assertTrue( + revoked.getAllValues().stream() + .allMatch(session -> session.getStatus() == SessionStatus.REVOKED)); + } + + @Test + void revokeSessionsForUser_stopsAndCountsNothingWhenSessionsCannotBeRevoked() { + User user = + new User() + .withId(UUID.randomUUID()) + .withName("stuck-user") + .withEmail("stuck-user@example.com"); + UserSession stuck = activeSession(validSessionId('z'), user, 1L, 1L); + // Every compare-and-set loses, so the session stays ACTIVE and is read back each pass. + when(repository.findByUserIdAndStatus( + eq(user.getId().toString()), eq(SessionStatus.ACTIVE), anyInt())) + .thenReturn(List.of(stuck)); + when(repository.findByUserIdAndStatus( + eq(user.getId().toString()), eq(SessionStatus.REFRESHING), anyInt())) + .thenReturn(List.of()); + when(repository.findById(stuck.getId())).thenReturn(Optional.of(stuck)); + when(repository.updateIfVersion(any(UserSession.class), anyLong())).thenReturn(false); + + assertEquals(0, sessionService.revokeSessionsForUser(user.getId().toString())); + + // Two passes: the first attempts the revoke, the second sees the same batch and gives up + // instead of burning every remaining iteration on a row that will not move. + verify(repository, times(2)) + .findByUserIdAndStatus(eq(user.getId().toString()), eq(SessionStatus.ACTIVE), anyInt()); + } + + @Test + void revokeSessionsForUser_alsoRevokesASessionThatIsMidRefresh() { + User user = + new User() + .withId(UUID.randomUUID()) + .withName("refreshing-user") + .withEmail("refreshing-user@example.com"); + // A session mid-refresh holds a lease and is invisible to an ACTIVE-only lookup, and + // completeRefresh puts it back to ACTIVE — so without this it would outlive the delete. + UserSession refreshing = + activeSession(validSessionId('r'), user, 3L, 3L).toBuilder() + .status(SessionStatus.REFRESHING) + .refreshLeaseUntil(System.currentTimeMillis() + 15_000) + .build(); + when(repository.findByUserIdAndStatus( + eq(user.getId().toString()), eq(SessionStatus.ACTIVE), anyInt())) + .thenReturn(List.of()); + when(repository.findByUserIdAndStatus( + eq(user.getId().toString()), eq(SessionStatus.REFRESHING), anyInt())) + .thenReturn(List.of(refreshing), List.of()); + when(repository.findById(refreshing.getId())).thenReturn(Optional.of(refreshing)); + when(repository.updateIfVersion(any(UserSession.class), anyLong())).thenReturn(true); + + assertEquals(1, sessionService.revokeSessionsForUser(user.getId().toString())); + + ArgumentCaptor revoked = ArgumentCaptor.forClass(UserSession.class); + verify(repository).updateIfVersion(revoked.capture(), anyLong()); + assertEquals(SessionStatus.REVOKED, revoked.getValue().getStatus()); + assertNull(revoked.getValue().getRefreshLeaseUntil()); + } + + @Test + void revokeSessionsForUser_isANoOpWithoutAUserId() { + assertEquals(0, sessionService.revokeSessionsForUser(null)); + verify(repository, never()).findByUserIdAndStatus(any(), any(SessionStatus.class), anyInt()); + } + private UserSession activeSession(String id, User user, long version, long lastAccessedAt) { return UserSession.builder() .id(id)