From fc06ca33120fc44bbcbd7c1e989fc523fd21c674 Mon Sep 17 00:00:00 2001 From: deepinsight coder Date: Thu, 26 Nov 2026 09:34:23 +0100 Subject: [PATCH 1/4] Add tests for push feed sockets that outlive their token or their user These tests fail on main. A socket opened with a token that carries no session is never closed when that token expires or when its user is deleted, the handshake never stamps the token expiry, and the UI never retries a server close. --- .../it/sso/browser/PushFeedSocket.java | 95 ++++++++++ .../it/sso/oidc/MockOidcProvider.java | 6 + .../it/sso/oidc/MockOidcTokens.java | 4 + .../it/tests/SessionMultiNodeIT.java | 51 +++++ .../it/tests/SsoPushFeedSocketIT.java | 176 ++++++++++++++++++ ...OpenMetadataApplicationAuthReloadTest.java | 38 ++++ .../socket/Jetty12WebSocketHandlerTest.java | 18 ++ .../socket/SocketAddressFilterTest.java | 159 ++++++++++++++++ .../service/socket/WebSocketManagerTest.java | 79 ++++++++ .../WebSocketProvider.test.tsx | 35 ++++ 10 files changed, 661 insertions(+) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/browser/PushFeedSocket.java create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoPushFeedSocketIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/browser/PushFeedSocket.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/browser/PushFeedSocket.java new file mode 100644 index 000000000000..45d743234596 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/browser/PushFeedSocket.java @@ -0,0 +1,95 @@ +package org.openmetadata.it.sso.browser; + +import io.socket.client.IO; +import io.socket.client.Socket; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.awaitility.Awaitility; + +/** + * A push-feed socket opened the way the single-page app opens one: socket.io over the websocket + * transport only, with the bearer token in the handshake query and no automatic reconnection, so a + * close the server makes stays visible to the test. + */ +public final class PushFeedSocket implements AutoCloseable { + public static final String SERVER_DISCONNECT = "io server disconnect"; + public static final String TOKEN_EXPIRED_CHANNEL = "tokenExpiredChannel"; + private static final String DISCONNECTED_PREFIX = "disconnect: "; + private static final String PATH = "/api/v1/push/feed"; + private static final String WEBSOCKET = "websocket"; + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(20); + + private final Socket socket; + private final AtomicBoolean connected = new AtomicBoolean(); + private final AtomicReference connectError = new AtomicReference<>(); + private final List received = new CopyOnWriteArrayList<>(); + + private PushFeedSocket(Socket socket) { + this.socket = socket; + socket.on(Socket.EVENT_CONNECT, args -> connected.set(true)); + socket.on(Socket.EVENT_CONNECT_ERROR, args -> connectError.set(firstOf(args))); + socket.on(TOKEN_EXPIRED_CHANNEL, args -> received.add(TOKEN_EXPIRED_CHANNEL)); + socket.on(Socket.EVENT_DISCONNECT, args -> onDisconnect(firstOf(args))); + } + + /** Opens a socket on {@code baseUrl} and waits until the server accepts its handshake. */ + public static PushFeedSocket open(String baseUrl, String token) { + PushFeedSocket feed = new PushFeedSocket(IO.socket(URI.create(baseUrl), options(token))); + feed.connect(); + return feed; + } + + public boolean isConnected() { + return connected.get(); + } + + /** What the socket received, in order: the token expired notice and the disconnect reason. */ + public List received() { + return List.copyOf(received); + } + + public static String disconnectedBy(String reason) { + return DISCONNECTED_PREFIX + reason; + } + + @Override + public void close() { + socket.off(); + socket.close(); + } + + private void connect() { + socket.connect(); + Awaitility.await("push-feed handshake") + .atMost(CONNECT_TIMEOUT) + .until(() -> connected.get() || connectError.get() != null); + if (!connected.get()) { + throw new AssertionError("The push feed refused the handshake: " + connectError.get()); + } + } + + // Recorded before the state flips, so a test that waits on isConnected sees the reason too. + private void onDisconnect(String reason) { + received.add(disconnectedBy(reason)); + connected.set(false); + } + + // Every socket gets its own connection: a shared one would reuse the first socket's token. + private static IO.Options options(String token) { + IO.Options options = new IO.Options(); + options.path = PATH; + options.query = "token=" + token; + options.transports = new String[] {WEBSOCKET}; + options.reconnection = false; + options.forceNew = true; + return options; + } + + private static String firstOf(Object[] args) { + return args.length > 0 ? String.valueOf(args[0]) : null; + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java index 7bb0d4139277..f80d55408616 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java @@ -22,6 +22,7 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import java.io.IOException; +import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -116,6 +117,11 @@ public String issueIdToken(MockOidcIdentity identity) { return tokens.idToken(identity, null); } + /** An ID token that expires {@code lifetime} after it is minted. */ + public String issueIdToken(MockOidcIdentity identity, Duration lifetime) { + return tokens.idTokenLasting(identity, lifetime); + } + /** An ID token for {@code identity} that only looks like this provider issued it. */ public String issueForgedIdToken(MockOidcIdentity identity, TokenForgery forgery) { return tokens.forgedIdToken(identity, forgery); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokens.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokens.java index 389a892b950a..7125369f967e 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokens.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokens.java @@ -79,6 +79,10 @@ String idToken(MockOidcIdentity identity, String nonce) { return idToken(identity, nonce, ID_TOKEN_LIFETIME); } + String idTokenLasting(MockOidcIdentity identity, Duration lifetime) { + return idToken(identity, null, lifetime); + } + String forgedIdToken(MockOidcIdentity identity, TokenForgery forgery) { return keys.forge(claims(identity, null, ID_TOKEN_LIFETIME, null), forgery); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SessionMultiNodeIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SessionMultiNodeIT.java index ceb53bef58c4..8f425e98b108 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SessionMultiNodeIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SessionMultiNodeIT.java @@ -13,17 +13,21 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.sql.SQLException; +import java.time.Duration; import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.awaitility.Awaitility; import org.jdbi.v3.core.Jdbi; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.auth.JwtAuthProvider; import org.openmetadata.it.bootstrap.SessionMultiNodeCluster; import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.sso.browser.PushFeedSocket; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -48,6 +52,13 @@ class SessionMultiNodeIT { private static final String USER_REFRESH_TOKENS = " WHERE userId = :userId AND tokenType = 'REFRESH_TOKEN'"; + private static final String ADMIN_EMAIL = "admin@open-metadata.org"; + private static final long ADMIN_TOKEN_TTL_SECONDS = 600; + private static final Duration PUSH_FEED_SWEEP_INTERVAL = + Duration.ofSeconds( + Long.getLong("openmetadata.websocketSessionValidationIntervalSeconds", 60)); + private static final Duration ENTITY_CACHE_TTL = Duration.ofSeconds(30); + private static final Duration PUSH_FEED_CLOSE_MARGIN = Duration.ofSeconds(15); @Test void refreshAndLogoutAreSharedAcrossNodes(TestNamespace ns) throws Exception { @@ -222,6 +233,34 @@ void pushFeedHandshakeRejectsASessionIssuedByAProviderNoLongerConfigured(TestNam assertEquals(401, handshakeAfterSwitch.statusCode(), handshakeAfterSwitch.body()); } + /** + * A personal access token carries no session, so the session revocation a delete performs never + * reaches a socket opened with one (#38245). The nodes of this in-process cluster share one + * push-feed socket registry, so this checks the close end to end across the nodes' endpoints; the + * sweep that closes such a socket on a peer without Redis has its own unit test + * (OpenMetadataApplicationAuthReloadTest). + */ + @Test + void pushFeedSocketOpenedWithAPersonalAccessTokenClosesWhenItsUserIsDeletedOnAnotherNode( + TestNamespace ns) throws Exception { + SessionMultiNodeCluster cluster = SessionMultiNodeCluster.getInstance(); + User user = createUser(ns); + String personalAccessToken = + CredentialFixtures.createPat(user, ns.prefix("push-feed")).getJwtToken(); + + try (PushFeedSocket socket = PushFeedSocket.open(cluster.nodeBBaseUrl(), personalAccessToken)) { + HttpResponse deleted = deleteUserThrough(cluster.nodeABaseUrl(), user); + assertEquals(200, deleted.statusCode(), deleted.body()); + + Awaitility.await("the deleted user's socket on the other node is closed") + .atMost(PUSH_FEED_SWEEP_INTERVAL.plus(ENTITY_CACHE_TTL).plus(PUSH_FEED_CLOSE_MARGIN)) + .until(() -> !socket.isConnected()); + assertEquals( + List.of(PushFeedSocket.disconnectedBy(PushFeedSocket.SERVER_DISCONNECT)), + socket.received()); + } + } + @Test void apiRequestsRemainAuthenticatedWhileAnotherNodeHoldsTheRefreshLease(TestNamespace ns) throws Exception { @@ -528,6 +567,18 @@ private HttpResponse getRawWithBearer(HttpClient client, String bearerTo return client.send(request, HttpResponse.BodyHandlers.ofString()); } + private HttpResponse deleteUserThrough(String baseUrl, User user) throws Exception { + String adminToken = + JwtAuthProvider.tokenFor( + ADMIN_EMAIL, ADMIN_EMAIL, new String[] {"admin"}, ADMIN_TOKEN_TTL_SECONDS); + HttpRequest request = + HttpRequest.newBuilder(URI.create(baseUrl + "/api/v1/users/" + user.getId())) + .header("Authorization", "Bearer " + adminToken) + .DELETE() + .build(); + return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + } + private HttpResponse pushFeedHandshake( HttpClient client, SessionCookies cookies, String baseUrl) throws Exception { HttpRequest request = diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoPushFeedSocketIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoPushFeedSocketIT.java new file mode 100644 index 000000000000..0df829d81b70 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SsoPushFeedSocketIT.java @@ -0,0 +1,176 @@ +package org.openmetadata.it.tests; + +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 static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.openmetadata.it.sso.browser.PushFeedSocket.SERVER_DISCONNECT; +import static org.openmetadata.it.sso.browser.PushFeedSocket.TOKEN_EXPIRED_CHANNEL; +import static org.openmetadata.it.sso.browser.PushFeedSocket.disconnectedBy; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.sso.browser.PushFeedSocket; +import org.openmetadata.it.sso.config.SecurityConfigSwap; +import org.openmetadata.it.sso.config.SsoConfigs; +import org.openmetadata.it.sso.config.SsoServer; +import org.openmetadata.it.sso.oidc.MockOidcIdentity; +import org.openmetadata.it.sso.oidc.MockOidcProvider; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.teams.User; + +/** + * Public-client OIDC push feed: the single-page app opens its socket with the provider's ID token + * and no session, so nothing but the token and the user bound it once it is open (#38245). + */ +@Isolated +@Execution(ExecutionMode.SAME_THREAD) +@ExtendWith(TestNamespaceExtension.class) +class SsoPushFeedSocketIT { + private static final String EMAIL_DOMAIN = "@open-metadata.org"; + private static final String SWEEP_INTERVAL_PROPERTY = + "openmetadata.websocketSessionValidationIntervalSeconds"; + private static final long DEFAULT_SWEEP_INTERVAL_SECONDS = 60; + private static final Duration SWEEP_MARGIN = Duration.ofSeconds(30); + private static final Duration SHORT_LIFETIME = Duration.ofSeconds(5); + private static final Duration LONG_LIFETIME = Duration.ofMinutes(10); + + /** Shorter than one sweep, so a close this quick came from the delete, not from a sweep. */ + private static final Duration DELETE_CLOSE_DEADLINE = Duration.ofSeconds(10); + + private static MockOidcProvider provider; + private static SecurityConfigSwap securityConfig; + + @BeforeAll + static void pointTheServerAtTheMockProvider() { + assumeFalse(OssTestServer.isExternalMode(), "Reconfigures the embedded server's SSO"); + provider = MockOidcProvider.start(); + securityConfig = SecurityConfigSwap.snapshotLiveConfig(); + securityConfig.applyBaseline(SsoConfigs.publicOidc(securityConfig.originalCopy(), provider)); + } + + @AfterAll + static void restoreTheLiveConfiguration() { + if (securityConfig != null) { + securityConfig.close(); + } + if (provider != null) { + provider.close(); + } + } + + @Test + @DisplayName("PF-01 a socket closes after its provider token expires, with a notice first") + void socketClosesAfterItsProviderTokenExpires(TestNamespace ns) { + SsoUser expiring = existingUser(ns, "xavier"); + SsoUser current = existingUser(ns, "yvonne"); + + try (PushFeedSocket expiringSocket = openFor(expiring, SHORT_LIFETIME); + PushFeedSocket currentSocket = openFor(current, LONG_LIFETIME)) { + Awaitility.await("the socket whose token expired is closed") + .atMost(sweepInterval().plus(SHORT_LIFETIME).plus(SWEEP_MARGIN)) + .until(() -> !expiringSocket.isConnected()); + + assertEquals( + List.of(TOKEN_EXPIRED_CHANNEL, disconnectedBy(SERVER_DISCONNECT)), + expiringSocket.received()); + assertTrue(currentSocket.isConnected(), "the sweep left the socket with a valid token open"); + assertEquals(List.of(), currentSocket.received()); + } + } + + @Test + @DisplayName("PF-02 soft deleting a user closes their socket at once and no one else's") + void softDeleteClosesTheUsersSocketAtOnce(TestNamespace ns) { + SsoUser deleted = existingUser(ns, "walter"); + SsoUser other = existingUser(ns, "zelda"); + + try (PushFeedSocket deletedSocket = openFor(deleted, LONG_LIFETIME); + PushFeedSocket otherSocket = openFor(other, LONG_LIFETIME)) { + SdkClients.adminClient().users().delete(deleted.id()); + + awaitClosedByTheDelete(deletedSocket); + assertEquals(List.of(disconnectedBy(SERVER_DISCONNECT)), deletedSocket.received()); + assertTrue(otherSocket.isConnected(), "another user's socket stays open"); + } + } + + @Test + @DisplayName("PF-03 a restored user's old socket stays closed and a new one connects") + void restoredUserConnectsANewSocket(TestNamespace ns) { + SsoUser restored = existingUser(ns, "victor"); + + try (PushFeedSocket beforeDelete = openFor(restored, LONG_LIFETIME)) { + SdkClients.adminClient().users().delete(restored.id()); + awaitClosedByTheDelete(beforeDelete); + SdkClients.adminClient().users().restore(restored.id()); + + try (PushFeedSocket afterRestore = openFor(restored, LONG_LIFETIME)) { + assertTrue(afterRestore.isConnected(), "the restored user opens a socket again"); + assertFalse(beforeDelete.isConnected(), "the socket from before the delete stays closed"); + } + } + } + + @Test + @DisplayName("PF-04 hard deleting a user closes their socket at once") + void hardDeleteClosesTheUsersSocketAtOnce(TestNamespace ns) { + SsoUser deleted = existingUser(ns, "ursula"); + + try (PushFeedSocket socket = openFor(deleted, LONG_LIFETIME)) { + SdkClients.adminClient() + .users() + .delete(deleted.id(), Map.of("hardDelete", "true", "recursive", "true")); + + awaitClosedByTheDelete(socket); + assertEquals(List.of(disconnectedBy(SERVER_DISCONNECT)), socket.received()); + } + } + + private static void awaitClosedByTheDelete(PushFeedSocket socket) { + Awaitility.await("the deleted user's socket is closed") + .atMost(DELETE_CLOSE_DEADLINE) + .until(() -> !socket.isConnected()); + } + + private static PushFeedSocket openFor(SsoUser user, Duration tokenLifetime) { + return PushFeedSocket.open( + SsoServer.root(), provider.issueIdToken(user.identity(), tokenLifetime)); + } + + /** The embedded server reads the sweep interval from this property when it boots. */ + private static Duration sweepInterval() { + return Duration.ofSeconds( + Long.getLong(SWEEP_INTERVAL_PROPERTY, DEFAULT_SWEEP_INTERVAL_SECONDS)); + } + + private static SsoUser existingUser(TestNamespace ns, String name) { + MockOidcIdentity identity = MockOidcIdentity.forEmail(ns.shortPrefix(name) + EMAIL_DOMAIN); + String userName = identity.email().substring(0, identity.email().indexOf('@')); + User user = + SdkClients.adminClient() + .users() + .create(new CreateUser().withName(userName).withEmail(identity.email())); + return new SsoUser(user, identity); + } + + private record SsoUser(User user, MockOidcIdentity identity) { + private String id() { + return user.getId().toString(); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java index 15cba41cac08..b2ddcae73122 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java @@ -21,6 +21,7 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -31,6 +32,7 @@ import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; @@ -38,8 +40,12 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.MockedStatic; import org.openmetadata.schema.api.security.AuthenticationConfiguration; import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.security.AuthServeletHandler; import org.openmetadata.service.security.auth.AuthenticatorHandler; import org.openmetadata.service.security.auth.SecurityConfigurationManager; @@ -183,6 +189,38 @@ void buildPushFeedSockets_sweepsAgainstTheProviderTheHandshakeFilterValidatesUnd assertEquals(Map.of(), sockets.getActivityFeedEndpoints()); } + /** + * A socket opened with a token that carries no session outlives the session revocation a delete + * performs, and a peer without Redis never hears of the delete, so the sweep checks whether the + * user behind such a socket still exists and closes every socket of one who does not (#38245). + */ + @Test + void buildPushFeedSockets_closesEverySocketOfAUserWhoIsGone() { + OpenMetadataApplication.buildPushFeedSockets( + EngineIoServerOptions.newFromDefault(), + PushFeedFilters.validatingUnder(AuthProvider.GOOGLE)); + WebSocketManager sockets = WebSocketManager.getInstance(); + UUID deletedUser = UUID.randomUUID(); + UUID presentUser = UUID.randomUUID(); + SocketIoSocket deletedUsersSocket = openSocket(sockets, deletedUser, "socket-deleted"); + SocketIoSocket presentUsersSocket = openSocket(sockets, presentUser, "socket-present"); + + try (MockedStatic entities = mockStatic(Entity.class)) { + entities + .when(() -> Entity.getEntityReferenceById(Entity.USER, deletedUser, Include.NON_DELETED)) + .thenThrow(EntityNotFoundException.byId(deletedUser.toString())); + entities + .when(() -> Entity.getEntityReferenceById(Entity.USER, presentUser, Include.NON_DELETED)) + .thenReturn(new EntityReference().withId(presentUser)); + + sockets.disconnectInactiveSessions(mock(SessionService.class), 0L); + } + + verify(deletedUsersSocket).disconnect(true); + verify(presentUsersSocket, never()).disconnect(anyBoolean()); + assertEquals(Set.of(presentUser), sockets.getActivityFeedEndpoints().keySet()); + } + private static UserSession googleSession(String sessionId, UUID userId) { long now = System.currentTimeMillis(); return UserSession.builder() diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java index 317ef1803ba3..532e220d8ba4 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java @@ -112,6 +112,24 @@ void clientIdentityHeadersAreDroppedBeforeStamping() { "only the validated identity may survive next to unrelated headers"); } + /** + * The sweep closes a socket opened without a session once the expiry stamped here passes, so a + * client must not be able to send its own expiry and keep the socket open past its token (#38245). + */ + @Test + void clientTokenExpiryHeaderIsDroppedBeforeStamping() { + Jetty12WebSocketHandler stamped = + new Jetty12WebSocketHandler( + mock(EngineIoServer.class), new HandshakeIdentity("user-uuid", null, null)); + Map> forged = new HashMap<>(); + forged.put("TokenExpiresAt", List.of("99999999999999")); + forged.put("tokenexpiresat", List.of("99999999999998")); + + stamped.onOpen(upgradeSession(Map.of(), forged)); + + assertEquals(List.of("UserId"), List.copyOf(stamped.getConnectionHeaders().keySet())); + } + /** The handshake query carries the bearer token, so no log line may contain it at any level. */ @Test void handshakeTokenNeverReachesTheLog() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/socket/SocketAddressFilterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/socket/SocketAddressFilterTest.java index 1ccc1fb48550..17b936e15d77 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/socket/SocketAddressFilterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/socket/SocketAddressFilterTest.java @@ -19,8 +19,10 @@ import static org.mockito.Mockito.when; import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; +import io.socket.engineio.server.EngineIoServer; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.http.Cookie; @@ -29,6 +31,9 @@ import java.lang.reflect.Field; import java.net.URISyntaxException; import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.Optional; @@ -62,6 +67,10 @@ @ExtendWith(MockitoExtension.class) class SocketAddressFilterTest { + /** The header name WebSocketManager reads the stamped expiry from; pinned as the contract. */ + private static final String TOKEN_EXPIRES_AT_HEADER = "TokenExpiresAt"; + + private static final String FAR_FUTURE_MILLIS = "99999999999999"; @Mock private AuthenticationConfiguration authConfig; @Mock private AuthorizerConfiguration authorizerConfig; @@ -662,6 +671,107 @@ void tokenOnlyHandshakeWithoutSessionStoreIsAccepted() throws Exception { HttpServletRequest wrappedRequest = (HttpServletRequest) requestCaptor.getValue(); org.junit.jupiter.api.Assertions.assertEquals( tokenUserId.toString(), wrappedRequest.getHeader("UserId")); + // The session claim keys the socket under its session, which the sweep checks once the store + // is wired, so no token expiry is stamped. + assertEquals("session-1", wrappedRequest.getHeader("SessionId")); + assertNull(wrappedRequest.getHeader(TOKEN_EXPIRES_AT_HEADER)); + } + + /** + * A provider token carries no session, so nothing re-checks the socket once it is open: the + * handshake stamps the token's verified expiry for the sweep to close the socket at (#38245). + */ + @Test + void providerTokenHandshakeWithoutSessionIsStampedWithItsExpiry() throws Exception { + UUID tokenUserId = UUID.randomUUID(); + Instant expiresAt = inTenMinutes(); + mockRequest("userId=" + tokenUserId, "Bearer token"); + mockProviderTokenClaims(providerClaims(expiresAt, null)); + + HttpServletRequest wrappedRequest = filterAs(tokenUserId); + + assertEquals( + String.valueOf(expiresAt.toEpochMilli()), + wrappedRequest.getHeader(TOKEN_EXPIRES_AT_HEADER)); + assertNull(wrappedRequest.getHeader("SessionId")); + } + + /** A session-bound socket is governed by its session; its access token is renewed under it. */ + @Test + void sessionBoundHandshakeIsNotStampedWithATokenExpiry() throws Exception { + UUID tokenUserId = UUID.randomUUID(); + mockRequest("userId=" + tokenUserId, "Bearer token"); + mockProviderTokenClaims(providerClaims(inTenMinutes(), "session-1")); + when(sessionService.getFreshSessionById("session-1")) + .thenReturn(Optional.of(activeSession("session-1", "sam"))); + + HttpServletRequest wrappedRequest = filterAs(tokenUserId); + + assertEquals("session-1", wrappedRequest.getHeader("SessionId")); + assertNull(wrappedRequest.getHeader(TOKEN_EXPIRES_AT_HEADER)); + } + + /** An Unlimited bot token or personal access token has no exp, so expiry does not bound it. */ + @Test + void tokenWithoutExpiryIsStampedWithoutAnExpiry() throws Exception { + UUID tokenUserId = UUID.randomUUID(); + mockRequest("userId=" + tokenUserId, "Bearer token"); + mockProviderTokenClaims(providerClaims(null, null)); + + HttpServletRequest wrappedRequest = filterAs(tokenUserId); + + assertEquals(tokenUserId.toString(), wrappedRequest.getHeader("UserId")); + assertNull(wrappedRequest.getHeader(TOKEN_EXPIRES_AT_HEADER)); + } + + /** The polling transport: a client cannot extend its socket by sending its own expiry. */ + @Test + void clientSentTokenExpiresAtHeaderIsDropped() throws Exception { + UUID tokenUserId = UUID.randomUUID(); + mockRequest("userId=" + tokenUserId, "Bearer token"); + mockProviderTokenClaims(providerClaims(null, null)); + lenient().when(request.getHeader(TOKEN_EXPIRES_AT_HEADER)).thenReturn(FAR_FUTURE_MILLIS); + lenient() + .when(request.getHeaders(TOKEN_EXPIRES_AT_HEADER)) + .thenReturn(java.util.Collections.enumeration(List.of(FAR_FUTURE_MILLIS))); + + HttpServletRequest wrappedRequest = filterAs(tokenUserId); + + assertNull(wrappedRequest.getHeader(TOKEN_EXPIRES_AT_HEADER)); + assertEquals( + List.of(), java.util.Collections.list(wrappedRequest.getHeaders(TOKEN_EXPIRES_AT_HEADER))); + } + + /** + * The websocket transport, the only one the UI uses: the identity the upgrade creator validates + * carries the token's expiry into the socket's connection headers, and the client's own copy of + * that header never survives, under any casing. + */ + @Test + void upgradeHandlerStampsTheValidatedExpiryAndDropsTheClientsCopy() throws Exception { + UUID tokenUserId = UUID.randomUUID(); + Instant expiresAt = inTenMinutes(); + when(request.getQueryString()).thenReturn("token=token"); + mockProviderTokenClaims(providerClaims(expiresAt, null)); + HandshakeIdentity identity; + try (MockedStatic entityMock = mockStatic(Entity.class)) { + entityMock + .when(() -> Entity.getEntityReferenceByName(Entity.USER, "sam", Include.NON_DELETED)) + .thenReturn(new EntityReference().withId(tokenUserId)); + + identity = filter.authenticate(request); + } + Jetty12WebSocketHandler handler = + new Jetty12WebSocketHandler(mock(EngineIoServer.class), identity); + + handler.onOpen(upgradeSessionWithHeader("tokenexpiresat", FAR_FUTURE_MILLIS)); + + Map> headers = handler.getConnectionHeaders(); + assertEquals( + List.of(String.valueOf(expiresAt.toEpochMilli())), headers.get(TOKEN_EXPIRES_AT_HEADER)); + assertEquals( + List.of("Cookie", TOKEN_EXPIRES_AT_HEADER, "UserId"), + headers.keySet().stream().sorted().toList()); } @Test @@ -720,6 +830,55 @@ private void mockTokenClaims(String username, String sessionId) { when(jwtFilter.resolveUserName(any(), anyString())).thenReturn(username); } + /** Real decoded claims, as the validator hands them over once the signature is checked. */ + private static Map providerClaims(Instant expiresAt, String sessionId) { + JWTCreator.Builder token = JWT.create().withSubject("sam"); + if (expiresAt != null) { + token.withExpiresAt(expiresAt); + } + if (sessionId != null) { + token.withClaim(JWTTokenGenerator.SESSION_ID_CLAIM, sessionId); + } + return JWT.decode(token.sign(Algorithm.none())).getClaims(); + } + + private void mockProviderTokenClaims(Map claims) { + when(jwtFilter.verifySignatureOnly("token")).thenReturn(claims); + when(jwtFilter.resolveUserName(any(), anyString())).thenReturn("sam"); + } + + /** Runs the polling handshake for "sam" and returns the request the servlet behind sees. */ + private HttpServletRequest filterAs(UUID tokenUserId) throws Exception { + try (MockedStatic entityMock = mockStatic(Entity.class)) { + entityMock + .when(() -> Entity.getEntityReferenceByName(Entity.USER, "sam", Include.NON_DELETED)) + .thenReturn(new EntityReference().withId(tokenUserId)); + + filter.doFilter(request, response, chain); + } + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ServletRequest.class); + verify(chain).doFilter(requestCaptor.capture(), eq(response)); + return (HttpServletRequest) requestCaptor.getValue(); + } + + /** Exp has whole-second precision, so the stamped value is too. */ + private static Instant inTenMinutes() { + return Instant.now().plus(Duration.ofMinutes(10)).truncatedTo(ChronoUnit.SECONDS); + } + + private static org.eclipse.jetty.websocket.api.Session upgradeSessionWithHeader( + String name, String value) { + org.eclipse.jetty.websocket.api.Session session = + mock(org.eclipse.jetty.websocket.api.Session.class); + org.eclipse.jetty.websocket.api.UpgradeRequest upgradeRequest = + mock(org.eclipse.jetty.websocket.api.UpgradeRequest.class); + when(session.getUpgradeRequest()).thenReturn(upgradeRequest); + when(upgradeRequest.getParameterMap()).thenReturn(Map.of("token", List.of("token"))); + when(upgradeRequest.getHeaders()) + .thenReturn(Map.of(name, List.of(value), "Cookie", List.of("theme=dark"))); + return session; + } + private UserSession activeSession(String sessionId, String username) { return activeSession(sessionId, username, null); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java index 73bf6e7b2d63..cd9d43415c7f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java @@ -21,6 +21,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -43,6 +44,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InOrder; import org.mockito.MockedStatic; import org.openmetadata.schema.api.configuration.MCPConfiguration; import org.openmetadata.schema.api.security.AuthenticationConfiguration; @@ -61,6 +63,8 @@ import org.openmetadata.service.security.session.UserSession; class WebSocketManagerTest { + /** The wire name the UI listens for; pinned here so a rename cannot silently break the UI. */ + private static final String TOKEN_EXPIRED_CHANNEL = "tokenExpiredChannel"; private WebSocketManager manager; private AuthenticationConfiguration configuredBefore; @@ -381,6 +385,64 @@ void onConnection_keepsASocketValidatedUnderTheOtherNativePasswordProviderName() assertEquals(Set.of("socket-basic"), manager.getActivityFeedEndpoints().get(userId).keySet()); } + /** + * A socket opened with a provider token has no session for the sweep to re-check, so the token's + * expiry, stamped at the handshake, is what bounds it (#38245). + */ + @Test + void disconnectInactiveSessions_closesASessionlessSocketOnceItsTokenHasExpired() { + UUID userId = UUID.randomUUID(); + SocketIoSocket expired = + connectWithTokenExpiry(userId, "socket-expired", epochMillisAgo(1_000)); + SocketIoSocket current = + connectWithTokenExpiry(userId, "socket-current", epochMillisAgo(-60_000)); + + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + verify(expired, times(1)).disconnect(true); + verify(current, never()).disconnect(anyBoolean()); + assertEquals(Set.of("socket-current"), manager.getActivityFeedEndpoints().get(userId).keySet()); + } + + /** The UI reconnects after a server close only when this notice came first. */ + @Test + void disconnectInactiveSessions_sendsTheTokenExpiredNoticeBeforeClosing() { + SocketIoSocket expired = + connectWithTokenExpiry(UUID.randomUUID(), "socket-expired", epochMillisAgo(1_000)); + + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + InOrder closing = inOrder(expired); + closing.verify(expired).send(TOKEN_EXPIRED_CHANNEL); + closing.verify(expired).disconnect(true); + } + + /** The expiry is server-stamped; a value the server cannot read fails closed. */ + @Test + void onConnection_treatsAMalformedExpiryAsExpired() { + UUID userId = UUID.randomUUID(); + SocketIoSocket socket = connectWithTokenExpiry(userId, "socket-malformed", "not-a-number"); + + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + verify(socket, times(1)).disconnect(true); + assertFalse(manager.getActivityFeedEndpoints().containsKey(userId)); + } + + @Test + void disconnectInactiveSessions_keepsASessionBoundSocketWhoseSessionIsActive() { + UUID userId = UUID.randomUUID(); + SessionService sessionService = + sessionServiceStoring( + AuthProvider.GOOGLE, sessionIssuedBy(AuthProvider.GOOGLE, "session-g", userId)); + SocketIoSocket socket = connect(userId, "socket-session", "session-g", AuthProvider.GOOGLE); + + manager.disconnectInactiveSessions(sessionService, 0L); + + verify(socket, never()).disconnect(anyBoolean()); + assertEquals(Set.of("socket-session"), manager.getActivityFeedEndpoints().get(userId).keySet()); + } + @Test void sendToOne_deliversLocallyAndPublishesToRelay() { UUID userId = UUID.randomUUID(); @@ -549,6 +611,23 @@ private SocketIoSocket connect( return socket; } + /** A sessionless socket stamped the way the handshake stamps one opened with a provider token. */ + private SocketIoSocket connectWithTokenExpiry(UUID userId, String socketId, String expiresAt) { + SocketIoSocket socket = mock(SocketIoSocket.class); + when(socket.getId()).thenReturn(socketId); + Map> headers = new HashMap<>(); + headers.put("UserId", List.of(userId.toString())); + headers.put("AuthProvider", List.of(AuthProvider.GOOGLE.value())); + headers.put("TokenExpiresAt", List.of(expiresAt)); + when(socket.getInitialHeaders()).thenReturn(headers); + manager.onConnection(socket); + return socket; + } + + private static String epochMillisAgo(long millis) { + return String.valueOf(System.currentTimeMillis() - millis); + } + private SocketIoSocket trackSocket(UUID userId, String socketId, String sessionId) throws Exception { SocketIoSocket socket = registerSocket(userId, socketId); diff --git a/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.test.tsx b/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.test.tsx index dc7229c542d9..18b9af8a64b5 100644 --- a/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.test.tsx @@ -201,6 +201,41 @@ describe('WebSocketProvider', () => { } ); + // The server closes a socket opened without a session once its token expires, and sends this + // notice first. By then the app has renewed the token, so the reconnect reads the renewed one. + it('reconnects with the current token after the server closes a socket whose token expired', async () => { + await renderProvider(); + (getOidcToken as jest.Mock).mockResolvedValue('renewed-token'); + + fake.emit('tokenExpiredChannel'); + fake.emit('disconnect', 'io server disconnect'); + act(() => { + jest.advanceTimersByTime(1000); + }); + await flushPromises(); + + expect(fake.connectTokens).toEqual(['renewed-token']); + }); + + it('retries only the server close that follows the token expired notice', async () => { + await renderProvider(); + + fake.emit('tokenExpiredChannel'); + fake.emit('disconnect', 'io server disconnect'); + act(() => { + jest.advanceTimersByTime(1000); + }); + await flushPromises(); + fake.emit('connect'); + fake.emit('disconnect', 'io server disconnect'); + act(() => { + jest.advanceTimersByTime(60_000); + }); + await flushPromises(); + + expect(fake.socket.connect).toHaveBeenCalledTimes(1); + }); + it('never publishes a socket for a setup superseded while its token read was pending', async () => { let resolveFirstToken: ((token: string) => void) | undefined; (getOidcToken as jest.Mock).mockImplementationOnce( From 10de692c2b1a2097c28661b90aa0f87903d9b63b Mon Sep 17 00:00:00 2001 From: deepinsight coder Date: Thu, 26 Nov 2026 10:23:25 +0100 Subject: [PATCH 2/4] Close push feed sockets without a session at token expiry and on user delete A socket accepted on a token that carries no session now keeps the token's exp, stamped by the handshake on both transports. The sweep closes it at its first pass after exp and sends tokenExpiredChannel first. Deleting a user closes all of that user's sockets on this server and tells the peers, and the sweep also closes the sockets of a user who no longer exists, which covers peers without Redis. --- .../service/OpenMetadataApplication.java | 37 ++- .../service/cache/CacheBundle.java | 11 +- .../cache/CacheInvalidationPubSub.java | 9 + .../service/jdbi3/UserRepository.java | 21 +- .../service/socket/HandshakeIdentity.java | 37 ++- .../socket/Jetty12WebSocketHandler.java | 39 +-- .../service/socket/PushFeedSocketPolicy.java | 44 +++ .../service/socket/PushFeedUserPresence.java | 52 ++++ .../service/socket/SocketAddressFilter.java | 80 +++-- .../service/socket/SocketTokenExpiries.java | 59 ++++ .../service/socket/WebSocketManager.java | 293 ++++++++++++------ ...OpenMetadataApplicationAuthReloadTest.java | 26 ++ .../socket/Jetty12WebSocketHandlerTest.java | 15 + .../socket/PushFeedUserPresenceTest.java | 63 ++++ .../service/socket/WebSocketManagerTest.java | 209 +++++++++++++ 15 files changed, 845 insertions(+), 150 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedSocketPolicy.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedUserPresence.java create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketTokenExpiries.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/socket/PushFeedUserPresenceTest.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 26a4f2d40f33..7fe2f3f95ef8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java @@ -53,12 +53,14 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; +import java.time.Clock; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Objects; +import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -107,6 +109,8 @@ import org.openmetadata.service.apps.bundles.searchIndex.distributed.ServerIdentityResolver; import org.openmetadata.service.apps.scheduler.AppScheduler; import org.openmetadata.service.audit.AuditLogRepository; +import org.openmetadata.service.cache.CacheBundle; +import org.openmetadata.service.cache.CacheInvalidationPubSub; import org.openmetadata.service.clients.llm.LlmConfigHolder; import org.openmetadata.service.config.CacheConfiguration; import org.openmetadata.service.config.OMWebBundle; @@ -231,6 +235,8 @@ import org.openmetadata.service.socket.HandshakeRejectedException; import org.openmetadata.service.socket.Jetty12WebSocketHandler; import org.openmetadata.service.socket.OpenMetadataAssetServlet; +import org.openmetadata.service.socket.PushFeedSocketPolicy; +import org.openmetadata.service.socket.PushFeedUserPresence; import org.openmetadata.service.socket.SocketAddressFilter; import org.openmetadata.service.socket.WebSocketManager; import org.openmetadata.service.swagger.SwaggerBundle; @@ -1229,7 +1235,11 @@ private void wireSessionRevocationToWebSockets(SessionService sessionService) { org.openmetadata.service.cache.CacheInvalidationPubSub pubSub = org.openmetadata.service.cache.CacheBundle.getCacheInvalidationPubSub(); if (pubSub != null) { - pubSub.publish("session", id, session.getId(), "revoke"); + pubSub.publish( + CacheInvalidationPubSub.TYPE_SESSION, + id, + session.getId(), + CacheInvalidationPubSub.OP_REVOKE); } } catch (IllegalArgumentException e) { LOG.debug("Skipping revocation broadcast for non-UUID userId {}", session.getUserId()); @@ -1541,11 +1551,34 @@ static ConfigurationChangeListener pushFeedReloadListener( * validates under, not the published configuration: a reload publishes before it initializes the * new authenticator and rolls back if that fails, while only a reload that succeeded rebuilds the * filter. ADR:2026-10-20-a-refresh-ends-sessions-issued-by-a-provider-no-longer-configured + * + *

The sweep also closes the sockets of a user who is gone, and a user delete tells the other + * servers to close that user's sockets. + * ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted */ @VisibleForTesting static void buildPushFeedSockets( EngineIoServerOptions options, SocketAddressFilter websocketFilter) { - WebSocketManager.WebSocketManagerBuilder.build(options, websocketFilter::validatingProvider); + WebSocketManager.WebSocketManagerBuilder.build( + options, + new PushFeedSocketPolicy( + websocketFilter::validatingProvider, + Clock.systemUTC(), + PushFeedUserPresence::isGone, + OpenMetadataApplication::publishUserAccessEnded)); + } + + /** + * A revoke without a session id: peers close every socket the deleted user holds on them. Peers + * without Redis never get it, and their sweep closes those sockets instead. + */ + @VisibleForTesting + static void publishUserAccessEnded(UUID userId) { + CacheInvalidationPubSub pubSub = CacheBundle.getCacheInvalidationPubSub(); + if (pubSub != null) { + pubSub.publish( + CacheInvalidationPubSub.TYPE_SESSION, userId, null, CacheInvalidationPubSub.OP_REVOKE); + } } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java index 114916066fbd..62f5bf3c4ddb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java @@ -112,10 +112,13 @@ public void run(OpenMetadataApplicationConfig configuration, Environment environ cacheInvalidationPubSub.setHandler( msg -> { try { - // Out-of-band signal: a session was revoked on another pod, drop any WebSocket - // connections this pod is holding for that user. Encoded as type=session, op=revoke, - // id= so it rides the existing channel without needing a second subscriber. - if ("session".equals(msg.type()) && "revoke".equals(msg.op()) && msg.id() != null) { + // Out-of-band signal: a session was revoked or a user deleted on another pod, drop + // the WebSocket connections this pod is holding for it. Encoded as type=session, + // op=revoke, id=, fqn= or none, so it rides the existing channel + // without needing a second subscriber. + if (CacheInvalidationPubSub.TYPE_SESSION.equals(msg.type()) + && CacheInvalidationPubSub.OP_REVOKE.equals(msg.op()) + && msg.id() != null) { org.openmetadata.service.socket.WebSocketManager wsManager = org.openmetadata.service.socket.WebSocketManager.getInstance(); if (wsManager != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheInvalidationPubSub.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheInvalidationPubSub.java index 9502783d28c8..11a8773a85eb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheInvalidationPubSub.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheInvalidationPubSub.java @@ -64,6 +64,15 @@ public class CacheInvalidationPubSub { */ public static final String TYPE_CREDENTIAL = "credential"; + /** + * Non-entity signal, with {@link #OP_REVOKE}: close a user's push-feed sockets, the user id in + * {@code id}. With a session id in {@code fqn} only that session's sockets close (a revoked + * session); without one, all of them (a deleted user). + */ + public static final String TYPE_SESSION = "session"; + + public static final String OP_REVOKE = "revoke"; + private final CacheConfig.Redis redisConfig; @Getter private final String instanceId; private final AtomicBoolean running = new AtomicBoolean(false); 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 a0ed40c5f9d4..d0e3fc09fd04 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 @@ -109,6 +109,7 @@ import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.openmetadata.service.security.policyevaluator.TeamHierarchyResolver; import org.openmetadata.service.security.session.SessionService; +import org.openmetadata.service.socket.WebSocketManager; import org.openmetadata.service.tasks.TaskAssigneeCleanup; import org.openmetadata.service.util.AsyncService; import org.openmetadata.service.util.AsyncService.DatabaseOperation; @@ -1761,8 +1762,8 @@ private void updateIncidentAssignee(User user) { /** * Every delete path runs this, including the bulk soft delete that removes a deleted bot's user - * without calling {@link #postDelete}, so the credential change is announced and the user's MCP - * grants end here. + * without calling {@link #postDelete}, so the credential change is announced, the user's MCP + * grants end and their push-feed sockets close here. */ @Override protected DeleteLifecycle beginDeleteLifecycle(User entity, String deletedBy) { @@ -1771,10 +1772,23 @@ protected DeleteLifecycle beginDeleteLifecycle(User entity, String deletedBy) { try (parentLifecycle) { Credentials.changed(entity.getName()); daoCollection.oauthRefreshTokenDAO().revokeAllGrantsOfUser(entity.getName()); + PostCommitActionQueue.runOrDefer(() -> endPushFeedAccess(entity)); } }; } + /** + * Closes every push-feed socket of the deleted user, on this server and on its peers, including + * those opened with a token that carries no session, which revoking sessions cannot reach. + * ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted + */ + private static void endPushFeedAccess(User user) { + WebSocketManager sockets = WebSocketManager.getInstance(); + if (sockets != null && user.getId() != null) { + sockets.endAccessForUser(user.getId()); + } + } + @Override protected void postDelete(User entity, boolean hardDelete) { super.postDelete(entity, hardDelete); @@ -1830,7 +1844,8 @@ public void endSignIns(User user, SessionService sessionService) { * 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. + * session-bound sockets as well; the delete lifecycle closes the rest ({@link + * #endPushFeedAccess}). */ private void revokeLiveSessions(User entity) { revokeLiveSessions(entity, AuthServeletHandlerRegistry.getSessionService()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/HandshakeIdentity.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/HandshakeIdentity.java index 48e1a500115a..a3224a6fbb1e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/socket/HandshakeIdentity.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/HandshakeIdentity.java @@ -13,11 +13,38 @@ package org.openmetadata.service.socket; +import java.time.Instant; +import java.util.List; + /** * The validated identity a push-feed socket may act as: the user id (UUID as a string) the socket - * is keyed under, the session id its handshake was accepted with, and the provider value of the - * configuration that validated the handshake. All come from {@link - * SocketAddressFilter#authenticate} — never from a client-supplied value. The provider is null only - * when the filter has no configuration to validate a token with. + * is keyed under, the session id its handshake was accepted with, the provider value of the + * configuration that validated the handshake, and the expiry of the token a socket without a + * session was accepted on. All come from {@link SocketAddressFilter#authenticate} — never from a + * client-supplied value. The provider is null only when the filter has no configuration to validate + * a token with. The token expiry is null for a socket with a session, which its session governs, + * and for a token without exp. */ -public record HandshakeIdentity(String userId, String sessionId, String provider) {} +public record HandshakeIdentity( + String userId, String sessionId, String provider, Instant tokenExpiresAt) { + public static final String USER_ID_HEADER = "UserId"; + public static final String SESSION_ID_HEADER = "SessionId"; + public static final String PROVIDER_HEADER = "AuthProvider"; + + /** Epoch milliseconds. */ + public static final String TOKEN_EXPIRES_AT_HEADER = "TokenExpiresAt"; + + /** The headers the handshake stamps on a socket; a client's own value for any never survives. */ + public static final List STAMPED_HEADERS = + List.of(USER_ID_HEADER, SESSION_ID_HEADER, PROVIDER_HEADER, TOKEN_EXPIRES_AT_HEADER); + + /** An identity no token expiry bounds. */ + public HandshakeIdentity(String userId, String sessionId, String provider) { + this(userId, sessionId, provider, null); + } + + /** The value stamped as {@link #TOKEN_EXPIRES_AT_HEADER}; null when no expiry bounds the socket. */ + public String tokenExpiresAtHeaderValue() { + return tokenExpiresAt == null ? null : String.valueOf(tokenExpiresAt.toEpochMilli()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/Jetty12WebSocketHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/Jetty12WebSocketHandler.java index 198e056e7c7f..3f34a9cf7411 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/socket/Jetty12WebSocketHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/Jetty12WebSocketHandler.java @@ -13,6 +13,12 @@ package org.openmetadata.service.socket; +import static org.openmetadata.service.socket.HandshakeIdentity.PROVIDER_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.SESSION_ID_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.STAMPED_HEADERS; +import static org.openmetadata.service.socket.HandshakeIdentity.TOKEN_EXPIRES_AT_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.USER_ID_HEADER; + import io.socket.engineio.server.EngineIoServer; import io.socket.engineio.server.EngineIoWebSocket; import java.nio.ByteBuffer; @@ -40,10 +46,6 @@ @WebSocket(autoDemand = true) public class Jetty12WebSocketHandler extends EngineIoWebSocket { - private static final String USER_ID_HEADER = "UserId"; - private static final String SESSION_ID_HEADER = "SessionId"; - private static final String PROVIDER_HEADER = "AuthProvider"; - private final EngineIoServer server; private final HandshakeIdentity handshakeIdentity; private Session session; @@ -133,21 +135,20 @@ public void onOpen(Session session) { */ private static void stampValidatedIdentity( Map> headers, HandshakeIdentity handshakeIdentity) { - headers - .keySet() - .removeIf( - name -> - USER_ID_HEADER.equalsIgnoreCase(name) - || SESSION_ID_HEADER.equalsIgnoreCase(name) - || PROVIDER_HEADER.equalsIgnoreCase(name)); - if (handshakeIdentity.userId() != null && !handshakeIdentity.userId().isBlank()) { - headers.put(USER_ID_HEADER, List.of(handshakeIdentity.userId())); - } - if (handshakeIdentity.sessionId() != null && !handshakeIdentity.sessionId().isBlank()) { - headers.put(SESSION_ID_HEADER, List.of(handshakeIdentity.sessionId())); - } - if (handshakeIdentity.provider() != null && !handshakeIdentity.provider().isBlank()) { - headers.put(PROVIDER_HEADER, List.of(handshakeIdentity.provider())); + headers.keySet().removeIf(Jetty12WebSocketHandler::isStampedHeader); + putIfPresent(headers, USER_ID_HEADER, handshakeIdentity.userId()); + putIfPresent(headers, SESSION_ID_HEADER, handshakeIdentity.sessionId()); + putIfPresent(headers, PROVIDER_HEADER, handshakeIdentity.provider()); + putIfPresent(headers, TOKEN_EXPIRES_AT_HEADER, handshakeIdentity.tokenExpiresAtHeaderValue()); + } + + private static boolean isStampedHeader(String name) { + return STAMPED_HEADERS.stream().anyMatch(name::equalsIgnoreCase); + } + + private static void putIfPresent(Map> headers, String name, String value) { + if (value != null && !value.isBlank()) { + headers.put(name, List.of(value)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedSocketPolicy.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedSocketPolicy.java new file mode 100644 index 000000000000..422f30369ee5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedSocketPolicy.java @@ -0,0 +1,44 @@ +/* + * 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.socket; + +import java.time.Clock; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; + +/** + * What {@link WebSocketManager} judges an open socket against. + * + * @param appliedProvider the provider the handshake filter validates under. A reload publishes its + * configuration before it initializes the new authenticator and rolls back if that fails, so + * this follows the filter, which only a reload that succeeded replaces + * @param clock what a socket's token expiry is compared with + * @param isUserGone whether a socket's user was deleted; asked by the sweep + * @param notifyPeersAccessEnded tells the other servers to close a deleted user's sockets + */ +public record PushFeedSocketPolicy( + Supplier appliedProvider, + Clock clock, + Predicate isUserGone, + Consumer notifyPeersAccessEnded) { + + /** Judges sockets against {@code appliedProvider} only: no user is gone and no peer is told. */ + public static PushFeedSocketPolicy validatingUnder(Supplier appliedProvider) { + return new PushFeedSocketPolicy( + appliedProvider, Clock.systemUTC(), userId -> false, userId -> {}); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedUserPresence.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedUserPresence.java new file mode 100644 index 000000000000..03c62c38161b --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/PushFeedUserPresence.java @@ -0,0 +1,52 @@ +/* + * 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.socket; + +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; + +/** + * Whether the user behind a push-feed socket still exists, for the sweep that closes the sockets + * of a deleted user on a server the delete never reached + * (ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted). + */ +@Slf4j +public final class PushFeedUserPresence { + private PushFeedUserPresence() {} + + /** + * True only when the user is hard or soft deleted. A lookup that fails for another reason is not + * a deletion: the sockets stay, and the next sweep asks again. + */ + public static boolean isGone(UUID userId) { + boolean gone; + try { + Entity.getEntityReferenceById(Entity.USER, userId, Include.NON_DELETED); + gone = false; + } catch (EntityNotFoundException notFound) { + gone = true; + } catch (RuntimeException lookupFailure) { + LOG.warn( + "Could not check whether user {} still exists; keeping their push-feed sockets until the" + + " next sweep", + userId, + lookupFailure); + gone = false; + } + return gone; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketAddressFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketAddressFilter.java index bda516a97a8c..3a2b5520b538 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketAddressFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketAddressFilter.java @@ -13,6 +13,13 @@ package org.openmetadata.service.socket; +import static org.openmetadata.service.socket.HandshakeIdentity.PROVIDER_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.SESSION_ID_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.STAMPED_HEADERS; +import static org.openmetadata.service.socket.HandshakeIdentity.TOKEN_EXPIRES_AT_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.USER_ID_HEADER; + +import com.auth0.jwt.RegisteredClaims; import com.auth0.jwt.interfaces.Claim; import io.socket.engineio.server.utils.ParseQS; import jakarta.servlet.Filter; @@ -22,6 +29,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import java.time.Instant; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -179,28 +187,33 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha } } - /** The token binds the socket to its user only when the caller-id agrees — else it is invalid. */ + /** Null when the handshake presents no token. */ private TokenIdentity resolveTokenIdentity( JwtFilter validator, HttpServletRequest request, Map query, String requestedUserId) { String tokenWithType = resolveHandshakeToken(request, query); - if (!hasText(tokenWithType)) { - return null; - } + return hasText(tokenWithType) + ? validatedTokenIdentity(validator, tokenWithType, requestedUserId) + : null; + } + + /** The token binds the socket to its user only when the caller-id agrees — else it is invalid. */ + private TokenIdentity validatedTokenIdentity( + JwtFilter validator, String tokenWithType, String requestedUserId) { if (validator == null) { // A credential was presented but this filter has no configuration to validate it. throw new HandshakeRejectedException( HttpServletResponse.SC_UNAUTHORIZED, HANDSHAKE_UNAUTHORIZED_MESSAGE); } - ValidatedTokenPrincipal tokenPrincipal = validatePrefixedTokenRequest(validator, tokenWithType); - UUID resolvedUserId = getUserIdForPrincipal(tokenPrincipal.userName()); + ValidatedToken validated = validateToken(validator, tokenWithType); + UUID resolvedUserId = getUserIdForPrincipal(validated.principal().userName()); if (requestedUserId != null && !requestedUserId.equals(resolvedUserId.toString())) { throw new HandshakeRejectedException( HttpServletResponse.SC_FORBIDDEN, SOCKET_USER_TOKEN_MISMATCH_MESSAGE); } - return new TokenIdentity(tokenPrincipal, resolvedUserId); + return new TokenIdentity(validated.principal(), resolvedUserId, validated.expiresAt()); } private void sendHandshakeError(ServletResponse response, int status, String message) @@ -312,6 +325,10 @@ && hasText(session.get().getUserId()) */ public static ValidatedTokenPrincipal validatePrefixedTokenRequest( JwtFilter jwtFilter, String prefixedToken) { + return validateToken(jwtFilter, prefixedToken).principal(); + } + + private static ValidatedToken validateToken(JwtFilter jwtFilter, String prefixedToken) { String token = JwtFilter.extractToken(prefixedToken); Map claims = jwtFilter.verifySignatureOnly(token); String userName = jwtFilter.resolveUserName(claims, token); @@ -320,7 +337,15 @@ public static ValidatedTokenPrincipal validatePrefixedTokenRequest( claims.containsKey(JWTTokenGenerator.SESSION_ID_CLAIM) ? claims.get(JWTTokenGenerator.SESSION_ID_CLAIM).asString() : null; - return new ValidatedTokenPrincipal(userName, sessionId); + return new ValidatedToken(new ValidatedTokenPrincipal(userName, sessionId), expiryOf(claims)); + } + + /** The verified exp; null when the token has none, as an Unlimited bot token or PAT may lack. */ + private static Instant expiryOf(Map claims) { + Claim expiresAt = claims.get(RegisteredClaims.EXPIRES_AT); + return expiresAt == null || expiresAt.isNull() || expiresAt.isMissing() + ? null + : expiresAt.asInstant(); } private UUID getUserIdForPrincipal(String userName) { @@ -380,7 +405,17 @@ private static HandshakeIdentity identity( throw new HandshakeRejectedException( HttpServletResponse.SC_UNAUTHORIZED, HANDSHAKE_UNAUTHORIZED_MESSAGE); } - return new HandshakeIdentity(userId, sessionId, provider); + return new HandshakeIdentity( + userId, sessionId, provider, sessionlessTokenExpiry(sessionId, tokenIdentity)); + } + + /** + * A socket with a session is governed by that session, which the sweep re-checks; only a socket + * accepted on its token alone is bounded by the token's exp. + * ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted + */ + private static Instant sessionlessTokenExpiry(String sessionId, TokenIdentity tokenIdentity) { + return hasText(sessionId) || tokenIdentity == null ? null : tokenIdentity.expiresAt(); } private static ValidatedTokenPrincipal tokenPrincipal(TokenIdentity tokenIdentity) { @@ -393,23 +428,26 @@ private static ValidatedTokenPrincipal tokenPrincipal(TokenIdentity tokenIdentit */ private static void stampIdentity( HeaderRequestWrapper requestWrapper, HandshakeIdentity identity) { - requestWrapper.removeHeader("UserId"); - requestWrapper.removeHeader("SessionId"); - requestWrapper.removeHeader("AuthProvider"); - if (hasText(identity.userId())) { - requestWrapper.addHeader("UserId", identity.userId()); - } - if (hasText(identity.sessionId())) { - requestWrapper.addHeader("SessionId", identity.sessionId()); - } - if (hasText(identity.provider())) { - requestWrapper.addHeader("AuthProvider", identity.provider()); + STAMPED_HEADERS.forEach(requestWrapper::removeHeader); + stampIfPresent(requestWrapper, USER_ID_HEADER, identity.userId()); + stampIfPresent(requestWrapper, SESSION_ID_HEADER, identity.sessionId()); + stampIfPresent(requestWrapper, PROVIDER_HEADER, identity.provider()); + stampIfPresent(requestWrapper, TOKEN_EXPIRES_AT_HEADER, identity.tokenExpiresAtHeaderValue()); + } + + private static void stampIfPresent( + HeaderRequestWrapper requestWrapper, String name, String value) { + if (hasText(value)) { + requestWrapper.addHeader(name, value); } } public record ValidatedTokenPrincipal(String userName, String sessionId) {} - private record TokenIdentity(ValidatedTokenPrincipal tokenPrincipal, UUID userId) {} + private record ValidatedToken(ValidatedTokenPrincipal principal, Instant expiresAt) {} + + private record TokenIdentity( + ValidatedTokenPrincipal tokenPrincipal, UUID userId, Instant expiresAt) {} private record SessionValidationResult(String sessionId, String userId) { private static SessionValidationResult accepted() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketTokenExpiries.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketTokenExpiries.java new file mode 100644 index 000000000000..a36d1496bc50 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/SocketTokenExpiries.java @@ -0,0 +1,59 @@ +/* + * 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.socket; + +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.extern.slf4j.Slf4j; + +/** + * The exp of the token each socket opened without a session was accepted on, as the handshake + * stamped it. One entry per registered socket, dropped on every disconnect path, so it is bounded + * by the live connections. + * ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted + */ +@Slf4j +final class SocketTokenExpiries { + private final Map expiresAt = new ConcurrentHashMap<>(); + + /** The handshake stamps epoch milliseconds; a value the server cannot read fails closed. */ + void record(String socketId, String stampedEpochMillis) { + Instant expiry; + try { + expiry = Instant.ofEpochMilli(Long.parseLong(stampedEpochMillis.trim())); + } catch (NumberFormatException unreadable) { + LOG.warn( + "Push-feed socket {} carries a token expiry the server cannot read; treating its token" + + " as expired", + socketId); + expiry = Instant.EPOCH; + } + expiresAt.put(socketId, expiry); + } + + /** Strictly before now, with no leeway, as {@code JwtFilter} judges the token on REST. */ + boolean hasExpired(String socketId, Instant now) { + Instant expiry = expiresAt.get(socketId); + return expiry != null && expiry.isBefore(now); + } + + boolean isTracked(String socketId) { + return expiresAt.containsKey(socketId); + } + + void forget(String socketId) { + expiresAt.remove(socketId); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/socket/WebSocketManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/socket/WebSocketManager.java index b33197f9e0e8..0aacda9fccf1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/socket/WebSocketManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/socket/WebSocketManager.java @@ -1,7 +1,12 @@ package org.openmetadata.service.socket; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import static org.openmetadata.service.Entity.USER; +import static org.openmetadata.service.socket.HandshakeIdentity.PROVIDER_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.SESSION_ID_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.TOKEN_EXPIRES_AT_HEADER; +import static org.openmetadata.service.socket.HandshakeIdentity.USER_ID_HEADER; import com.google.common.annotations.VisibleForTesting; import io.socket.engineio.server.EngineIoServer; @@ -9,6 +14,8 @@ import io.socket.socketio.server.SocketIoNamespace; import io.socket.socketio.server.SocketIoServer; import io.socket.socketio.server.SocketIoSocket; +import java.time.Clock; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -16,6 +23,8 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Predicate; import java.util.function.Supplier; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -53,6 +62,14 @@ public class WebSocketManager { public static final String CHART_DATA_STREAM_CHANNEL = "chartDataStream"; public static final String QUERY_RUNNER_CHANNEL = "queryRunnerChannel"; + /** + * Sent to a socket opened without a session right before the sweep closes it because its token + * expired. The UI reconnects with its renewed token only after this notice; every other server + * close is final. + * ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted + */ + public static final String TOKEN_EXPIRED_CHANNEL = "tokenExpiredChannel"; + @Getter private final Map> activityFeedEndpoints = new ConcurrentHashMap<>(); @@ -61,6 +78,7 @@ public class WebSocketManager { TimeUnit.MINUTES.toMillis(1); private final Map socketSessionIds = new ConcurrentHashMap<>(); private final Map socketSessionValidatedAt = new ConcurrentHashMap<>(); + private final SocketTokenExpiries socketTokenExpiries = new SocketTokenExpiries(); // Cross-pod delivery for sendToOne; a Redis or DB relay is injected at startup (no-op by // default). @@ -73,11 +91,17 @@ public class WebSocketManager { */ private final Supplier appliedProvider; - private WebSocketManager( - EngineIoServerOptions eiOptions, Supplier appliedProvider) { + private final Clock clock; + private final Predicate isUserGone; + private final Consumer notifyPeersAccessEnded; + + private WebSocketManager(EngineIoServerOptions eiOptions, PushFeedSocketPolicy policy) { engineIoServer = new EngineIoServer(eiOptions); socketIoServer = new SocketIoServer(engineIoServer); - this.appliedProvider = appliedProvider; + this.appliedProvider = policy.appliedProvider(); + this.clock = policy.clock(); + this.isUserGone = policy.isUserGone(); + this.notifyPeersAccessEnded = policy.notifyPeersAccessEnded(); initializeHandlers(); } @@ -90,64 +114,71 @@ private void initializeHandlers() { @VisibleForTesting void onConnection(SocketIoSocket socket) { - List remoteAddress = socket.getInitialHeaders().get("RemoteAddress"); Map> initialHeaders = socket.getInitialHeaders(); - List userIdHeaders = listOrEmpty(initialHeaders.get("UserId")); - List sessionIdHeaders = listOrEmpty(initialHeaders.get("SessionId")); - List providerHeaders = listOrEmpty(initialHeaders.get("AuthProvider")); + List remoteAddress = initialHeaders.get("RemoteAddress"); // The socket identity, session and provider come exclusively from the headers stamped by // SocketAddressFilter after validating the handshake credential. The raw query params are // client-controlled and must never key a socket. - String userId = userIdHeaders.isEmpty() ? null : userIdHeaders.get(0); - String sessionId = sessionIdHeaders.isEmpty() ? null : sessionIdHeaders.get(0); - String validatedProvider = providerHeaders.isEmpty() ? null : providerHeaders.get(0); - + String userId = firstHeader(initialHeaders, USER_ID_HEADER); if (userId != null && !userId.isEmpty()) { LOG.info("Client : {} with Remote Address:{} connected", userId, remoteAddress); + UUID id = UUID.fromString(userId); + listenForClose(socket, id, remoteAddress); + register(socket, id, initialHeaders); + disconnectIfValidatedUnderAnotherProvider( + id, socket, firstHeader(initialHeaders, PROVIDER_HEADER)); + } + } - // On Socket Disconnect - socket.on( - "disconnect", - args1 -> { - LOG.info("Client from: {} with Remote Address:{} disconnected.", userId, remoteAddress); - UUID id = UUID.fromString(userId); - activityFeedEndpoints.computeIfPresent( - id, - (key, connections) -> { - connections.remove(socket.getId()); - socketSessionIds.remove(socket.getId()); - socketSessionValidatedAt.remove(socket.getId()); - return connections.isEmpty() ? null : connections; - }); - }); - - // On Socket Connection Error - socket.on( - "connect_error", - args1 -> - LOG.error( - "Connection ERROR for user:{} with Remote Address:{} disconnected", - userId, - remoteAddress)); - - // On Socket Connection Failure - socket.on( - "connect_failed", - args1 -> - LOG.error( - "Connection failed ERROR for user: {} with Remote Address: {} disconnected", - userId, - remoteAddress)); + private void listenForClose(SocketIoSocket socket, UUID userId, List remoteAddress) { + socket.on( + "disconnect", + args -> { + LOG.info("Client from: {} with Remote Address:{} disconnected.", userId, remoteAddress); + forgetSocket(socket.getId()); + activityFeedEndpoints.computeIfPresent( + userId, + (key, connections) -> { + connections.remove(socket.getId()); + return connections.isEmpty() ? null : connections; + }); + }); + socket.on( + "connect_error", + args -> + LOG.error( + "Connection ERROR for user:{} with Remote Address:{} disconnected", + userId, + remoteAddress)); + socket.on( + "connect_failed", + args -> + LOG.error( + "Connection failed ERROR for user: {} with Remote Address: {} disconnected", + userId, + remoteAddress)); + } - UUID id = UUID.fromString(userId); - Map userSocketConnections = - activityFeedEndpoints.computeIfAbsent(id, k -> new ConcurrentHashMap<>()); - userSocketConnections.put(socket.getId(), socket); - if (sessionId != null && !sessionId.isEmpty()) { - socketSessionIds.put(socket.getId(), sessionId); - } - disconnectIfValidatedUnderAnotherProvider(id, socket, validatedProvider); + /** The per-socket entries come first, so a sweep never sees a socket without them. */ + private void register( + SocketIoSocket socket, UUID userId, Map> initialHeaders) { + String socketId = socket.getId(); + String sessionId = firstHeader(initialHeaders, SESSION_ID_HEADER); + if (sessionId != null && !sessionId.isEmpty()) { + socketSessionIds.put(socketId, sessionId); + } + String tokenExpiresAt = firstHeader(initialHeaders, TOKEN_EXPIRES_AT_HEADER); + if (tokenExpiresAt != null) { + socketTokenExpiries.record(socketId, tokenExpiresAt); } + activityFeedEndpoints + .computeIfAbsent(userId, k -> new ConcurrentHashMap<>()) + .put(socketId, socket); + } + + private static String firstHeader(Map> headers, String name) { + List values = listOrEmpty(headers.get(name)); + return values.isEmpty() ? null : values.getFirst(); } /** @@ -242,31 +273,36 @@ public void sendToManyWithUUID(Set receivers, String event, String message } /** - * Force-close every Socket.IO connection this pod is holding for the given user. Called locally - * by {@code SessionService} when a session is revoked and via the cache-invalidation pub/sub - * when revocation happens on another pod. Idempotent — a no-op if the user has no open sockets - * on this pod. + * Force-close every Socket.IO connection this pod is holding for the given user. Called when a + * provider switch closes every socket, when the user is deleted (here through {@link + * #endAccessForUser}, on peers through the cache-invalidation pub/sub), and by the sweep for a + * user who is gone. Idempotent: a no-op if the user has no open sockets on this pod. */ public void disconnectAllForUser(UUID userId) { - if (userId == null) { - return; - } - Map sockets = activityFeedEndpoints.remove(userId); - if (sockets == null || sockets.isEmpty()) { - return; + Map sockets = + userId == null ? null : activityFeedEndpoints.remove(userId); + if (!nullOrEmpty(sockets)) { + LOG.info("Force-disconnecting {} socket(s) for user {}", sockets.size(), userId); + sockets.values().forEach(socket -> disconnectSocket(userId, socket)); } - LOG.info( - "Force-disconnecting {} socket(s) for user {} on session revocation", - sockets.size(), - userId); - for (SocketIoSocket socket : sockets.values()) { - disconnectSocket(userId, socket); + } + + /** + * Ends a deleted user's push feed: closes their sockets on this server and tells the other + * servers to close theirs. The session revocation a delete performs cannot reach a socket opened + * with a token that carries no session. + * ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted + */ + public void endAccessForUser(UUID userId) { + if (userId != null) { + disconnectAllForUser(userId); + notifyPeersAccessEnded.accept(userId); } } /** * Closes every socket this server holds, with or without a session: a socket opened with a - * provider token has no session the sweep could re-check. + * provider token has no session the sweep could re-check against the new provider. */ public void disconnectAll() { activityFeedEndpoints.keySet().forEach(this::disconnectAllForUser); @@ -304,32 +340,84 @@ public void disconnectInactiveSessions(SessionService sessionService) { disconnectInactiveSessions(sessionService, DEFAULT_SESSION_REVALIDATION_INTERVAL_MILLIS); } + /** + * One sweep pass over this server's sockets. A socket opened without a session closes, after the + * token expired notice, once its token's exp is before now; every socket of a user who is gone + * closes; a socket with a session closes once its session is no longer active, checked at most + * once per interval. + */ public void disconnectInactiveSessions( SessionService sessionService, long sessionRevalidationIntervalMillis) { - if (sessionService == null || activityFeedEndpoints.isEmpty()) { - return; + SweepPass pass = + new SweepPass( + sessionService, + clock.instant(), + sessionRevalidationIntervalMillis, + appliedProvider.get()); + activityFeedEndpoints.forEach((userId, sockets) -> sweepUser(pass, userId, sockets)); + } + + /** Only users holding a socket without a session are looked up: sessions end with a delete. */ + private void sweepUser(SweepPass pass, UUID userId, Map sockets) { + if (hasSocketWithoutSession(sockets) && isUserGone.test(userId)) { + LOG.info("Closing every push-feed socket of user {}: the user no longer exists", userId); + disconnectAllForUser(userId); + } else { + socketsMatching(sockets, socketId -> socketTokenExpiries.hasExpired(socketId, pass.now())) + .forEach(socket -> closeForExpiredToken(userId, socket)); + closeSocketsWhoseSessionEnded(pass, userId, sockets); + activityFeedEndpoints.computeIfPresent( + userId, (key, connections) -> connections.isEmpty() ? null : connections); } - long now = System.currentTimeMillis(); - AuthProvider applied = appliedProvider.get(); - activityFeedEndpoints.forEach( - (userId, sockets) -> { - List socketsToDisconnect = new ArrayList<>(); - sockets.forEach( - (socketId, socket) -> { - String sessionId = socketSessionIds.get(socketId); - if (sessionId != null - && isSessionRevalidationDue(socketId, now, sessionRevalidationIntervalMillis)) { - if (isSessionActiveForUser(sessionService, sessionId, userId, applied)) { - socketSessionValidatedAt.put(socketId, now); - } else { - socketsToDisconnect.add(socket); - } - } - }); - socketsToDisconnect.forEach(socket -> disconnectSocket(userId, socket)); - activityFeedEndpoints.computeIfPresent( - userId, (key, connections) -> connections.isEmpty() ? null : connections); - }); + } + + private boolean hasSocketWithoutSession(Map sockets) { + return sockets.keySet().stream().anyMatch(socketId -> !socketSessionIds.containsKey(socketId)); + } + + /** The notice goes out first; both ride the socket's ordered write buffer. */ + private void closeForExpiredToken(UUID userId, SocketIoSocket socket) { + LOG.info( + "Closing push-feed socket {} of user {}: the token it was opened with has expired", + socket.getId(), + userId); + try { + socket.send(TOKEN_EXPIRED_CHANNEL); + } catch (RuntimeException sendFailure) { + LOG.debug( + "Could not send the token expired notice to socket {}", socket.getId(), sendFailure); + } + disconnectSocket(userId, socket); + } + + private void closeSocketsWhoseSessionEnded( + SweepPass pass, UUID userId, Map sockets) { + if (pass.sessionService() != null) { + socketsMatching(sockets, socketId -> failsSessionRevalidation(pass, userId, socketId)) + .forEach(socket -> disconnectSocket(userId, socket)); + } + } + + /** True when the socket's session was due for a recheck and failed it; a pass is recorded. */ + private boolean failsSessionRevalidation(SweepPass pass, UUID userId, String socketId) { + String sessionId = socketSessionIds.get(socketId); + long now = pass.now().toEpochMilli(); + boolean failed = false; + if (sessionId != null && isSessionRevalidationDue(socketId, now, pass.intervalMillis())) { + failed = !isSessionActiveForUser(pass.sessionService(), sessionId, userId, pass.applied()); + if (!failed) { + socketSessionValidatedAt.put(socketId, now); + } + } + return failed; + } + + private static List socketsMatching( + Map sockets, Predicate socketIdMatches) { + return sockets.entrySet().stream() + .filter(entry -> socketIdMatches.test(entry.getKey())) + .map(Map.Entry::getValue) + .toList(); } private boolean isSessionRevalidationDue( @@ -359,18 +447,23 @@ private boolean isSessionActiveForUser( private void disconnectSocket(UUID userId, SocketIoSocket socket) { try { - socketSessionIds.remove(socket.getId()); - socketSessionValidatedAt.remove(socket.getId()); + forgetSocket(socket.getId()); Map sockets = activityFeedEndpoints.get(userId); if (sockets != null) { sockets.remove(socket.getId()); } socket.disconnect(true); - } catch (Exception e) { + } catch (RuntimeException e) { LOG.warn("Failed to disconnect socket {} for user {}", socket.getId(), userId, e); } } + private void forgetSocket(String socketId) { + socketSessionIds.remove(socketId); + socketSessionValidatedAt.remove(socketId); + socketTokenExpiries.forget(socketId); + } + public void sendToManyWithString( List receivers, String event, String message) { receivers.forEach(e -> sendToOne(e.getId(), event, message)); @@ -384,9 +477,17 @@ public static void build(EngineIoServerOptions eiOptions) { build(eiOptions, () -> null); } + /** Judged against {@code appliedProvider}; no user is treated as gone, no peer is told. */ public static void build( EngineIoServerOptions eiOptions, Supplier appliedProvider) { - instance = new WebSocketManager(eiOptions, appliedProvider); + build(eiOptions, PushFeedSocketPolicy.validatingUnder(appliedProvider)); + } + + public static void build(EngineIoServerOptions eiOptions, PushFeedSocketPolicy policy) { + instance = new WebSocketManager(eiOptions, policy); } } + + private record SweepPass( + SessionService sessionService, Instant now, long intervalMillis, AuthProvider applied) {} } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java index b2ddcae73122..fb2bef58b8db 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/OpenMetadataApplicationAuthReloadTest.java @@ -45,6 +45,8 @@ import org.openmetadata.schema.services.connections.metadata.AuthProvider; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; +import org.openmetadata.service.cache.CacheBundle; +import org.openmetadata.service.cache.CacheInvalidationPubSub; import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.security.AuthServeletHandler; import org.openmetadata.service.security.auth.AuthenticatorHandler; @@ -221,6 +223,30 @@ void buildPushFeedSockets_closesEverySocketOfAUserWhoIsGone() { assertEquals(Set.of(presentUser), sockets.getActivityFeedEndpoints().keySet()); } + /** Peers already close every socket of a user on a revoke that carries no session id. */ + @Test + void publishUserAccessEnded_publishesARevokeWithoutASessionId() { + UUID userId = UUID.randomUUID(); + CacheInvalidationPubSub pubSub = mock(CacheInvalidationPubSub.class); + + try (MockedStatic cache = mockStatic(CacheBundle.class)) { + cache.when(CacheBundle::getCacheInvalidationPubSub).thenReturn(pubSub); + + OpenMetadataApplication.publishUserAccessEnded(userId); + } + + verify(pubSub).publish("session", userId, null, "revoke"); + } + + @Test + void publishUserAccessEnded_doesNothingWithoutRedis() { + try (MockedStatic cache = mockStatic(CacheBundle.class)) { + cache.when(CacheBundle::getCacheInvalidationPubSub).thenReturn(null); + + assertDoesNotThrow(() -> OpenMetadataApplication.publishUserAccessEnded(UUID.randomUUID())); + } + } + private static UserSession googleSession(String sessionId, UUID userId) { long now = System.currentTimeMillis(); return UserSession.builder() diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java index 532e220d8ba4..890e5dbdce5d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/socket/Jetty12WebSocketHandlerTest.java @@ -13,6 +13,7 @@ import io.socket.engineio.server.EngineIoServer; import java.io.IOException; import java.nio.channels.ClosedChannelException; +import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -130,6 +131,20 @@ void clientTokenExpiryHeaderIsDroppedBeforeStamping() { assertEquals(List.of("UserId"), List.copyOf(stamped.getConnectionHeaders().keySet())); } + @Test + void validatedTokenExpiryIsStampedAsEpochMillis() { + Jetty12WebSocketHandler stamped = + new Jetty12WebSocketHandler( + mock(EngineIoServer.class), + new HandshakeIdentity( + "user-uuid", null, "google", Instant.ofEpochMilli(1_790_000_000_000L))); + + stamped.onOpen(upgradeSession(Map.of(), Map.of("TokenExpiresAt", List.of("1")))); + + assertEquals(List.of("1790000000000"), stamped.getConnectionHeaders().get("TokenExpiresAt")); + assertEquals(List.of("google"), stamped.getConnectionHeaders().get("AuthProvider")); + } + /** The handshake query carries the bearer token, so no log line may contain it at any level. */ @Test void handshakeTokenNeverReachesTheLog() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/socket/PushFeedUserPresenceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/socket/PushFeedUserPresenceTest.java new file mode 100644 index 000000000000..4ad7bde911b2 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/socket/PushFeedUserPresenceTest.java @@ -0,0 +1,63 @@ +/* + * 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.socket; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mockStatic; + +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; + +class PushFeedUserPresenceTest { + private final UUID userId = UUID.randomUUID(); + + @Test + void aUserThatIsNotFoundAmongTheUndeletedIsGone() { + try (MockedStatic entities = mockStatic(Entity.class)) { + entities + .when(() -> Entity.getEntityReferenceById(Entity.USER, userId, Include.NON_DELETED)) + .thenThrow(EntityNotFoundException.byId(userId.toString())); + + assertTrue(PushFeedUserPresence.isGone(userId)); + } + } + + @Test + void aUserThatIsFoundIsNotGone() { + try (MockedStatic entities = mockStatic(Entity.class)) { + entities + .when(() -> Entity.getEntityReferenceById(Entity.USER, userId, Include.NON_DELETED)) + .thenReturn(new EntityReference().withId(userId)); + + assertFalse(PushFeedUserPresence.isGone(userId)); + } + } + + /** A failed read is not a deletion: closing on it would end sockets the UI never reopens. */ + @Test + void aLookupThatFailsIsNotADeletion() { + try (MockedStatic entities = mockStatic(Entity.class)) { + entities + .when(() -> Entity.getEntityReferenceById(Entity.USER, userId, Include.NON_DELETED)) + .thenThrow(new IllegalStateException("connection pool exhausted")); + + assertFalse(PushFeedUserPresence.isGone(userId)); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java index cd9d43415c7f..69a43271478f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/socket/WebSocketManagerTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; @@ -30,8 +31,14 @@ import static org.mockito.Mockito.when; import io.dropwizard.core.setup.Environment; +import io.socket.engineio.server.Emitter; import io.socket.engineio.server.EngineIoServerOptions; import io.socket.socketio.server.SocketIoSocket; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -41,9 +48,12 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Predicate; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.MockedStatic; import org.openmetadata.schema.api.configuration.MCPConfiguration; @@ -66,6 +76,11 @@ class WebSocketManagerTest { /** The wire name the UI listens for; pinned here so a rename cannot silently break the UI. */ private static final String TOKEN_EXPIRED_CHANNEL = "tokenExpiredChannel"; + @Test + void tokenExpiredChannelIsTheNameTheUiListensFor() { + assertEquals(TOKEN_EXPIRED_CHANNEL, WebSocketManager.TOKEN_EXPIRED_CHANNEL); + } + private WebSocketManager manager; private AuthenticationConfiguration configuredBefore; private SocketAddressFilter handshakeFilter; @@ -417,6 +432,22 @@ void disconnectInactiveSessions_sendsTheTokenExpiredNoticeBeforeClosing() { closing.verify(expired).disconnect(true); } + /** The notice is best effort: a socket whose transport already failed still closes. */ + @Test + void disconnectInactiveSessions_closesAnExpiredSocketEvenWhenTheNoticeCannotBeSent() { + UUID userId = UUID.randomUUID(); + SocketIoSocket expired = + connectWithTokenExpiry(userId, "socket-expired", epochMillisAgo(1_000)); + doThrow(new IllegalStateException("transport closed")) + .when(expired) + .send(TOKEN_EXPIRED_CHANNEL); + + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + verify(expired, times(1)).disconnect(true); + assertFalse(manager.getActivityFeedEndpoints().containsKey(userId)); + } + /** The expiry is server-stamped; a value the server cannot read fails closed. */ @Test void onConnection_treatsAMalformedExpiryAsExpired() { @@ -429,6 +460,129 @@ void onConnection_treatsAMalformedExpiryAsExpired() { assertFalse(manager.getActivityFeedEndpoints().containsKey(userId)); } + /** Exp is the last instant the token is valid: kept at exp, closed just after, as on REST. */ + @Test + void disconnectInactiveSessions_keepsASessionlessSocketUntilItsTokenExpires() { + MutableClock clock = new MutableClock(Instant.parse("2026-11-26T10:00:00Z")); + buildManager(policy(clock, userId -> false, userId -> {})); + UUID userId = UUID.randomUUID(); + SocketIoSocket socket = + connectWithTokenExpiry(userId, "socket-at-exp", millisOf(clock.instant())); + + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + verify(socket, never()).disconnect(anyBoolean()); + + clock.advance(Duration.ofMillis(1)); + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + verify(socket, times(1)).disconnect(true); + assertFalse(manager.getActivityFeedEndpoints().containsKey(userId)); + } + + /** An Unlimited bot token or a personal access token without exp is not bounded by expiry. */ + @Test + void disconnectInactiveSessions_keepsASessionlessSocketWhoseTokenHasNoExpiry() { + MutableClock clock = new MutableClock(Instant.parse("2026-11-26T10:00:00Z")); + buildManager(policy(clock, userId -> false, userId -> {})); + UUID userId = UUID.randomUUID(); + SocketIoSocket socket = connect(userId, "socket-unlimited", null, AuthProvider.GOOGLE); + + clock.advance(Duration.ofDays(3650)); + manager.disconnectInactiveSessions(mock(SessionService.class), 0L); + + verify(socket, never()).disconnect(anyBoolean()); + assertEquals( + Set.of("socket-unlimited"), manager.getActivityFeedEndpoints().get(userId).keySet()); + } + + /** + * A peer without Redis never hears of a delete, and a handshake validated just before the delete + * can register after it: the sweep closes every socket of a user who is gone, session or not. + */ + @Test + void disconnectInactiveSessions_closesEverySocketOfAUserWhoIsGone() { + UUID goneUser = UUID.randomUUID(); + UUID presentUser = UUID.randomUUID(); + buildManager(policy(Clock.systemUTC(), goneUser::equals, userId -> {})); + SocketIoSocket sessionless = connect(goneUser, "socket-token", null, AuthProvider.GOOGLE); + SocketIoSocket withSession = + connect(goneUser, "socket-session", "session-g", AuthProvider.GOOGLE); + SocketIoSocket presentUsers = connect(presentUser, "socket-present", null, AuthProvider.GOOGLE); + + manager.disconnectInactiveSessions(mock(SessionService.class), 60_000L); + + verify(sessionless, times(1)).disconnect(true); + verify(withSession, times(1)).disconnect(true); + verify(presentUsers, never()).disconnect(anyBoolean()); + assertEquals(Set.of(presentUser), manager.getActivityFeedEndpoints().keySet()); + } + + /** A delete revokes the user's sessions, which closes such sockets, so they cost no lookup. */ + @Test + void disconnectInactiveSessions_neverLooksUpUsersWhoseSocketsAllHaveSessions() { + List lookedUp = new ArrayList<>(); + buildManager( + policy( + Clock.systemUTC(), + userId -> { + lookedUp.add(userId); + return false; + }, + userId -> {})); + UUID sessionUser = UUID.randomUUID(); + UUID tokenUser = UUID.randomUUID(); + SessionService sessionService = + sessionServiceStoring( + AuthProvider.GOOGLE, sessionIssuedBy(AuthProvider.GOOGLE, "session-g", sessionUser)); + connect(sessionUser, "socket-session", "session-g", AuthProvider.GOOGLE); + connect(tokenUser, "socket-token", null, AuthProvider.GOOGLE); + + manager.disconnectInactiveSessions(sessionService, 0L); + + assertEquals(List.of(tokenUser), lookedUp); + } + + @Test + void endAccessForUser_closesLocalSocketsAndSignalsPeers() { + List signalled = new ArrayList<>(); + buildManager(policy(Clock.systemUTC(), userId -> false, signalled::add)); + UUID deletedUser = UUID.randomUUID(); + UUID otherUser = UUID.randomUUID(); + SocketIoSocket sessionless = connect(deletedUser, "socket-token", null, AuthProvider.GOOGLE); + SocketIoSocket withSession = + connect(deletedUser, "socket-session", "session-g", AuthProvider.GOOGLE); + SocketIoSocket othersSocket = connect(otherUser, "socket-other", null, AuthProvider.GOOGLE); + + manager.endAccessForUser(deletedUser); + manager.endAccessForUser(null); + + verify(sessionless, times(1)).disconnect(true); + verify(withSession, times(1)).disconnect(true); + verify(othersSocket, never()).disconnect(anyBoolean()); + assertEquals(List.of(deletedUser), signalled); + assertEquals(Set.of(otherUser), manager.getActivityFeedEndpoints().keySet()); + } + + /** Every per-socket entry goes with its socket, whichever side closes it. */ + @Test + void disconnect_forgetsTheSocketsExpiry() throws Exception { + UUID userId = UUID.randomUUID(); + SocketIoSocket closedByClient = + connectWithTokenExpiry(userId, "socket-client", epochMillisAgo(-60_000)); + connectWithTokenExpiry(userId, "socket-server", epochMillisAgo(-60_000)); + + disconnectListenerOf(closedByClient).call(); + + assertFalse(tokenExpiries().isTracked("socket-client")); + assertTrue(tokenExpiries().isTracked("socket-server")); + + manager.disconnectAllForUser(userId); + + assertFalse(tokenExpiries().isTracked("socket-server")); + assertTrue(manager.getActivityFeedEndpoints().isEmpty()); + } + @Test void disconnectInactiveSessions_keepsASessionBoundSocketWhoseSessionIsActive() { UUID userId = UUID.randomUUID(); @@ -611,6 +765,61 @@ private SocketIoSocket connect( return socket; } + private void buildManager(PushFeedSocketPolicy policy) { + WebSocketManager.WebSocketManagerBuilder.build(EngineIoServerOptions.newFromDefault(), policy); + manager = WebSocketManager.getInstance(); + } + + private PushFeedSocketPolicy policy( + Clock clock, Predicate isUserGone, Consumer notifyPeers) { + return new PushFeedSocketPolicy( + handshakeFilter::validatingProvider, clock, isUserGone, notifyPeers); + } + + private static String millisOf(Instant instant) { + return String.valueOf(instant.toEpochMilli()); + } + + private static Emitter.Listener disconnectListenerOf(SocketIoSocket socket) { + ArgumentCaptor listener = ArgumentCaptor.forClass(Emitter.Listener.class); + verify(socket).on(eq("disconnect"), listener.capture()); + return listener.getValue(); + } + + private SocketTokenExpiries tokenExpiries() throws Exception { + java.lang.reflect.Field field = WebSocketManager.class.getDeclaredField("socketTokenExpiries"); + field.setAccessible(true); + return (SocketTokenExpiries) field.get(manager); + } + + /** A clock the test moves by hand, so expiry is checked at exact instants. */ + private static final class MutableClock extends Clock { + private Instant now; + + private MutableClock(Instant now) { + this.now = now; + } + + private void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } + /** A sessionless socket stamped the way the handshake stamps one opened with a provider token. */ private SocketIoSocket connectWithTokenExpiry(UUID userId, String socketId, String expiresAt) { SocketIoSocket socket = mock(SocketIoSocket.class); From 9291b46411c45366a5ca2d2829ee574897aad132 Mon Sep 17 00:00:00 2001 From: deepinsight coder Date: Thu, 26 Nov 2026 10:25:13 +0100 Subject: [PATCH 3/4] Reconnect the push feed after the server closes a socket whose token expired The server now sends tokenExpiredChannel right before it closes a socket opened without a session at its token's exp. The UI retries only that close, with the token it holds now, which it renewed before exp. Every other server close stays final. --- .../main/resources/ui/src/constants/constants.ts | 1 + .../context/WebSocketProvider/WebSocketProvider.tsx | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts b/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts index a46983b8ea4e..da1019b373fd 100644 --- a/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts +++ b/openmetadata-ui/src/main/resources/ui/src/constants/constants.ts @@ -372,6 +372,7 @@ export const SOCKET_EVENTS = { MOVE_GLOSSARY_TERM_CHANNEL: 'moveGlossaryTermChannel', CHART_DATA_STREAM: 'chartDataStream', QUERY_RUNNER_CHANNEL: 'queryRunnerChannel', + TOKEN_EXPIRED_CHANNEL: 'tokenExpiredChannel', }; export const CACHE_WARMUP_APPLICATION_NAME = 'CacheWarmupApplication'; diff --git a/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.tsx b/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.tsx index 7d5ce4f17571..fef2efd33b53 100644 --- a/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/context/WebSocketProvider/WebSocketProvider.tsx @@ -22,7 +22,7 @@ import { useState, } from 'react'; import { io, Socket } from 'socket.io-client'; -import { ROUTES } from '../../constants/constants'; +import { ROUTES, SOCKET_EVENTS } from '../../constants/constants'; import { useApplicationStore } from '../../hooks/useApplicationStore'; import { getBasePath } from '../../utils/HistoryUtils'; import { getOidcToken } from '../../utils/SwTokenStorageUtils'; @@ -50,11 +50,16 @@ type SocketDisposer = () => void; * token read (service worker / IndexedDB). So reconnection is driven here: read the current * token first, then reconnect. An expired initial token can therefore never burn through the * reconnect budget. + * + * A server close is final, except the one that follows the token expired notice: the server ends a + * socket opened without a session once its token expires, and by then the app has renewed the + * token, so the reconnect reads the renewed one. */ const driveReconnects = (socket: Socket): SocketDisposer => { let attempts = 0; let timer: number | undefined; let disposed = false; + let tokenExpiredByServer = false; const scheduleReconnect = () => { if (disposed || timer || attempts >= RECONNECT_ATTEMPTS) { @@ -81,10 +86,14 @@ const driveReconnects = (socket: Socket): SocketDisposer => { attempts = 0; }); socket.on('connect_error', scheduleReconnect); + socket.on(SOCKET_EVENTS.TOKEN_EXPIRED_CHANNEL, () => { + tokenExpiredByServer = true; + }); socket.on('disconnect', (reason) => { - if (!NON_RETRIABLE_DISCONNECT_REASONS.has(reason)) { + if (!NON_RETRIABLE_DISCONNECT_REASONS.has(reason) || tokenExpiredByServer) { scheduleReconnect(); } + tokenExpiredByServer = false; }); return () => { From 3dbb869269ffb136a0902e0b0161cbeb23735e58 Mon Sep 17 00:00:00 2001 From: deepinsight coder Date: Thu, 26 Nov 2026 10:25:46 +0100 Subject: [PATCH 4/4] Record the push feed socket lifetime rule and update the session design doc Adds the decision record for sockets without a session, amends the record on push feed handshakes to say that trust in such a token lasts until its exp, and updates the multi node session design to match. --- ...ush-feed-handshakes-always-authenticate.md | 12 +++- ...ts-token-expires-or-its-user-is-deleted.md | 59 +++++++++++++++++++ docs/session-management-multi-node-design.md | 44 +++++++++++--- 3 files changed, 107 insertions(+), 8 deletions(-) create mode 100644 docs/decisions/2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted.md diff --git a/docs/decisions/2026-10-26-push-feed-handshakes-always-authenticate.md b/docs/decisions/2026-10-26-push-feed-handshakes-always-authenticate.md index e1a2e3069085..1eda3e5f5c72 100644 --- a/docs/decisions/2026-10-26-push-feed-handshakes-always-authenticate.md +++ b/docs/decisions/2026-10-26-push-feed-handshakes-always-authenticate.md @@ -1,7 +1,8 @@ # Push-feed socket handshakes are always authenticated - **Status:** Accepted -- **Revisions:** v1 2026-10-26 (initial) +- **Revisions:** v1 2026-10-26 (initial) · v2 2026-11-26 (trust in a token without a session ends + at its `exp`) - **Deciders:** TeddyCr - **Guard:** `SocketAddressFilterTest` (unit) — the credential-less regression test fails any change that re-opens a token-less, cookie-less handshake under the default configuration, and the @@ -67,3 +68,12 @@ Because a presented token must validate, the browser cannot reconnect with a tok the socket was down; the UI therefore drives its own bounded reconnection, reading the current token before each attempt instead of relying on socket.io's automatic reconnect, whose handshake query is fixed at construction. + +## Amendment + +v2 (2026-11-26): a socket accepted on a token without the session claim is trusted on that token's +validation only until the token's `exp` (#38245). The handshake stamps the verified `exp` on such a +socket, the sweep closes it at its first pass after `exp`, and deleting its user closes it at once. +A token without `exp` sets no such bound. A socket with a session stays governed by its session. +ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted +records the rule. diff --git a/docs/decisions/2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted.md b/docs/decisions/2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted.md new file mode 100644 index 000000000000..e5eb97c86596 --- /dev/null +++ b/docs/decisions/2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted.md @@ -0,0 +1,59 @@ +# A push-feed socket without a session ends when its token expires or its user is deleted + +- **Status:** Accepted +- **Revisions:** v1 2026-11-26 (initial) +- **Deciders:** Vamsi-klu (proposed in #38245; maintainers review) +- **Guard:** `WebSocketManagerTest` (the sweep closes a socket whose token expired, keeps one at + `exp`, keeps one without `exp`, sends the notice before closing, closes every socket of a user who + is gone, never looks up a user whose sockets all have sessions, `endAccessForUser` closes and + signals peers); `SocketAddressFilterTest` (the expiry is stamped only on a handshake without a + session, on both transports, and a client's copy is dropped); `Jetty12WebSocketHandlerTest`; + `PushFeedUserPresenceTest`; `OpenMetadataApplicationAuthReloadTest` + (`buildPushFeedSockets_closesEverySocketOfAUserWhoIsGone`, + `publishUserAccessEnded_publishesARevokeWithoutASessionId`); `WebSocketProvider.test.tsx`; + `SsoPushFeedSocketIT`; `SessionMultiNodeIT` + (`pushFeedSocketOpenedWithAPersonalAccessTokenClosesWhenItsUserIsDeletedOnAnotherNode`) +- **Related:** #38245, #38248, ADR:2026-10-26-push-feed-handshakes-always-authenticate, + ADR:2026-10-20-a-refresh-ends-sessions-issued-by-a-provider-no-longer-configured, #38247, #38246 + +## Context + +A push-feed handshake that presents a token without the session claim (a public-client SSO +provider token, a bot token, a personal access token) is accepted on token validation alone. The +websocket transport, the only one the UI uses, is checked once, at the upgrade. Nothing re-checked +such a socket afterwards: the sweep re-checks only sockets with a session, and revocation closes +sockets by session. A socket therefore stayed open after its token expired, and after its user was +deleted, until the client went away or the server restarted. + +## Decision + +- A socket with a session is governed by its session, which the sweep already re-checks. Its access + token is a renewable proof of that session and puts no bound on the socket. +- A handshake accepted without a session stamps the verified `exp` of its token as the server-owned + `TokenExpiresAt` header (epoch milliseconds) on both transports; a client's copy of that header is + always dropped. A value the server cannot read counts as expired. +- The existing sweep closes such a socket at its first pass after `exp`: `exp` before now, the same + strict comparison and zero leeway as `JwtFilter`. The bound is `exp` plus one sweep interval (60 s + by default, 15 s at least). Before closing, the server sends `tokenExpiredChannel` to that socket. +- A token without `exp` (an Unlimited bot token or personal access token) puts no expiry bound on its + socket, as on REST. Deleting the user, a provider switch and a restart still end it. +- Deleting a user, soft or hard, closes all their sockets on this server after the delete, from the + `beginDeleteLifecycle` closure that every delete path runs, and publishes `session`/`revoke` with + the user id and no session id, which peers already answer by closing all that user's sockets. + Each sweep also checks whether a user who holds a socket without a session still exists, and + closes all their sockets when not; a failed lookup is not a deletion and is retried at the next + pass. That covers peers without Redis (one interval plus the 30 s entity cache), tokens without + `exp`, and a handshake validated just before the delete that registers after it. +- The UI retries a server close only when `tokenExpiredChannel` came first, reading the current + token, which it renews before `exp`. Every other server close stays final. + +## Consequences + +Public-client SSO tabs reconnect on their own about once per provider token lifetime. Other clients +that hold a token with `exp` must reconnect after `tokenExpiredChannel`; a UI built before this +ignores the notice and loses push until it is reloaded. A deleted user loses their sockets at once. +Revoking one personal access token or bot token while its user stays does not close its socket +before `exp`; that is a follow-up. The new per-socket expiry map is one entry per registered socket, +removed on every disconnect path, so it is bounded by live connections. Revisit if sockets with a +session should also end at their access token's `exp`: basic and confidential tabs would then drop +every hour. diff --git a/docs/session-management-multi-node-design.md b/docs/session-management-multi-node-design.md index f0b17ddba751..62aca6f88ebc 100644 --- a/docs/session-management-multi-node-design.md +++ b/docs/session-management-multi-node-design.md @@ -378,10 +378,13 @@ mode is enabled. ### 8.2 Socket Tracking -`WebSocketManager` maintains two local maps per pod: +`WebSocketManager` maintains these local maps per pod: - `activityFeedEndpoints`: `userId -> socketId -> SocketIoSocket` - `socketSessionIds`: `socketId -> sessionId` +- `socketSessionValidatedAt`: `socketId -> last session recheck` +- `socketTokenExpiries` (`SocketTokenExpiries`): `socketId -> exp` of the token a socket without a + session was accepted on On connection: @@ -390,8 +393,12 @@ On connection: paths. 3. Store the socket in the user's local socket map. 4. Store the socket-to-session mapping when a session ID is available. +5. Store the token expiry when the handshake stamped one (`TokenExpiresAt`, epoch milliseconds). The + handshake stamps it only when it accepted the socket without a session; a value the server cannot + read counts as expired. A client's own `TokenExpiresAt` header is always dropped. -On disconnect, both maps are cleaned up. +On every disconnect path, all per-socket maps are cleaned up, so they stay bounded by the live +connections. The connection log records user and remote address only. It does not log initial headers, so bearer tokens are not written to logs. @@ -413,6 +420,13 @@ tokens are not written to logs. This gives targeted disconnects. Logging out one browser session does not force-close other sessions for the same user. +Deleting a user, soft or hard, ends all their sockets, including those opened with a token that +carries no session, which session revocation cannot reach. `UserRepository.beginDeleteLifecycle`, +which every delete path runs, hands `WebSocketManager.endAccessForUser(userId)` to +`PostCommitActionQueue`, so inside a transaction scope it runs after the commit. It closes the +user's sockets on the local pod and publishes a `"session"` message with the user id and no session +ID, which peers answer with `disconnectAllForUser(userId)`. + ### 8.4 Periodic WebSocket Validation `OpenMetadataApplication.WebSocketSessionValidator` runs every `60s` by default. Operators can tune @@ -427,9 +441,19 @@ Each run calls `WebSocketManager.disconnectInactiveSessions(sessionService, inte socket's revalidation interval is due. 3. Disconnects sockets whose session is missing, not `ACTIVE`, expired, issued by a provider other than the one the push-feed handshake filter validates under, or owned by a different user. +4. Sends `tokenExpiredChannel` to each socket without a session whose token `exp` is before now, then + disconnects it. A socket whose token has no `exp` is not bounded by expiry. +5. For each user holding a socket without a session, checks that the user still exists + (`PushFeedUserPresence`, a cached lookup) and disconnects all their sockets when not. A failed + lookup is not a deletion; the next pass tries again. This is the fallback when there is no cross-pod pub/sub. With JDBC and no pub/sub, a socket on a -remote node is closed within the validator interval instead of immediately. +remote node is closed within the validator interval instead of immediately; for a deleted user it +is the interval plus the 30 s entity cache. + +The UI retries a server close only when `tokenExpiredChannel` came first: it reconnects with the +token it holds now, which it renews before `exp`. Every other server close is final +(ADR:2026-11-26-a-push-feed-socket-without-a-session-ends-when-its-token-expires-or-its-user-is-deleted). A security reload that changes the configured provider closes every socket on that server, with or without a session (`closeSocketsOnProviderSwitch`). A socket whose handshake was validated just @@ -516,9 +540,14 @@ Websocket consistency has two layers: - event-driven disconnect through local revocation listeners and optional cache invalidation pub/sub - polling-based validation with a `60s` default interval and `15s` minimum -The event path is immediate when revocation occurs on the same pod or pub/sub delivers the remote -event. The polling path bounds staleness when pub/sub is unavailable, and each socket is fresh -loaded at most once per validation interval. +The event path is immediate when revocation or a user delete occurs on the same pod or pub/sub +delivers the remote event. The polling path bounds staleness when pub/sub is unavailable, and each +socket is fresh loaded at most once per validation interval. + +A socket without a session is bounded by its token: it closes at the first pass after `exp`, so at +most one interval late. Its user's deletion closes it at once on the pod that ran the delete, on +peers through pub/sub, and on peers without pub/sub at the next pass after the entity cache drops +the user. ## 11. Operational Characteristics @@ -530,7 +559,8 @@ loaded at most once per validation interval. | Refresh | load session, acquire CAS lease, complete CAS update | | Logout | fresh load session, CAS revoke, clear cookie | | WebSocket handshake | validate JWT, optionally fresh load cookie session | -| WebSocket validator | throttled fresh load for each tracked socket with `sessionId` | +| WebSocket validator | throttled fresh load for each tracked socket with `sessionId`; cached user lookup for each user holding a socket without one | +| User delete | close the user's sockets on this pod, publish a `"session"` revoke without a session ID | Redis deployments should monitor Redis availability as auth-critical infrastructure. When Redis is configured for sessions, the service refuses to start without it.