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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.
Original file line number Diff line number Diff line change
@@ -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.
44 changes: 37 additions & 7 deletions docs/session-management-multi-node-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> connectError = new AtomicReference<>();
private final List<String> 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<String> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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<String> 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 {
Expand Down Expand Up @@ -528,6 +567,18 @@ private HttpResponse<String> getRawWithBearer(HttpClient client, String bearerTo
return client.send(request, HttpResponse.BodyHandlers.ofString());
}

private HttpResponse<String> 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<String> pushFeedHandshake(
HttpClient client, SessionCookies cookies, String baseUrl) throws Exception {
HttpRequest request =
Expand Down
Loading
Loading