Skip to content

fix(realtime): keep open connections in step with the user record - #14021

Merged
ArnabChatterjee20k merged 19 commits into
mainfrom
fix/realtime-session-lifecycle
Oct 1, 2026
Merged

ArnabChatterjee20k merged 19 commits into
mainfrom
fix/realtime-session-lifecycle

Conversation

@Meldiron

Copy link
Copy Markdown
Contributor

What does this PR do?

Realtime re-resolves a user's open connections on team-membership events, but not on changes to the user record itself. This PR closes that gap so a connection reflects the same state the HTTP API would resolve for its next request.

  • User events re-resolve connections. users.* events now flag permissionsChanged, like membership events already did, so roles derived from the user document (verification, labels, status, sessions) are refreshed on that user's open connections.
  • Connections remember their session. The realtime connection container gains store, proofForToken and session resources mirroring the HTTP ones. The session a connection was opened with (cookie, x-appwrite-session, fallback cookies, or a session-bound JWT) is recorded on the connection entry and kept across resubscribes and in-band authentication. Impersonated connections run on the impersonator's session, so they are not bound to one of the target user's.
  • Ended sessions end the connection. During re-resolution, a connection whose session no longer exists, or whose user is blocked or deleted, keeps its roles for that one event, receives it, and is then sent a 401 error frame and closed. SDKs reconnect and authenticate from their current cookie state.
  • Realtime::subscribe() now preserves impersonatedUserId and sessionId alongside authorization across resubscribes.

Test Plan

  • tests/unit/Messaging/MessagingTest.php: users.* events flag permissionsChanged; subscribe() keeps connection authorization state.
  • tests/e2e/Services/Realtime/RealtimeCustomClientTest.php::testConnectionEndsWithSession: deleting another session leaves the connection open and working; deleting its own session (account API, users API, delete-all, session-bound JWT), blocking the user, or deleting the user delivers the event and then closes the socket with a 401 error frame.
  • testChannelAccount now expects the close that follows the password recovery, which invalidates every session of the user by default.
  • RealtimeBase::receiveUntilClosed() reads frames until the server closes the socket, replacing sleep-and-close checks.

Pint, PHPStan and Rector pass on the touched files; the Messaging unit suite passes locally. E2E runs in CI.

Related PRs and Issues

  • Follows the pattern of membership permission changes in app/realtime.php.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

🤖 Generated with Claude Code

Connections now remember the session they were opened with, and every
`users.*` event re-resolves that user's open connections the way
membership events already do. A connection whose session has ended, or
whose user is blocked or deleted, receives that event and is then closed
with a 401 error frame; its next attempt authenticates from scratch, as
an HTTP request would.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@ghost

ghost commented Sep 30, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The PR refreshes realtime authorization after access-changing user events, tracks session and JWT expiry, and closes connections when access ends. Impersonated connections remain bound to the impersonator’s session, and authentication metadata survives resubscriptions. Unit and end-to-end coverage exercises revocation, expiry, session extension, and impersonator lifecycle behavior.

Latest changes: The newest commit adds an E2E test that verifies ping succeeds before JWT expiry, then receives a 401 error and socket closure after expiry without any outbound event triggering the close.

Verdict New comments Fixed Still open
✅ Approved 0 2 0
📂 Walkthrough · 12
File Change
app/init/realtime/connection.php Resolves connection authentication, session/JWT expiry, and the impersonator’s source project.
app/realtime.php Refreshes affected connections and enforces revoked or expired access on delivery and inbound dispatch.
src/Appwrite/Messaging/Adapter/Realtime.php Identifies access-changing events, preserves authentication metadata, and adds connection lookup and expiry checks.
src/Appwrite/Realtime/EventTailRegistry.php Exposes tail connection IDs for expiry checks before flushing.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Records the authenticated session and expiry while clearing prior JWT expiry.
src/Appwrite/Utopia/Database/Documents/User.php Adds session-expiry timestamp lookup.
tests/e2e/Services/Realtime/RealtimeBase.php Adds a helper to collect frames until server-initiated closure.
tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php Tests JWT expiry on console live-tail connections.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Tests revocation, blocking, deletion, impersonation, session extension, and JWT expiry; uses labels to exercise target refresh.
tests/unit/Messaging/MessagingTest.php Tests access-change flags, retained authentication metadata, connection lookup, and expiry.
tests/unit/Realtime/EventTailRegistryTest.php Tests enumeration of connections holding tails.
tests/unit/Utopia/Database/Documents/UserTest.php Tests session-expiry lookup and missing-session behavior.
✅ Fixed since the last review · 2
  • Enforce connection expiry before dispatching inbound messages · app/realtime.php:801
  • Exercise a target change that actually rebuilds the connection · tests/e2e/Services/Realtime/RealtimeCustomClientTest.php:1128

Reviewed the commits since e3fe027 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 2 blocking findings to address. Summary

Comment thread app/realtime.php Resolved
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 1/5

[Critical risk] Realtime connection lifecycle tied to user session state.

The PR is not safe to merge while impersonated sockets can lose their identity marker and the outstanding revocation and final-frame issues remain.

Fix All in Claude CodeFindings

  1. P1 Security Impersonation marker is lost ▶
  2. P1 Security Impersonated sockets outlive sessions ▶
  3. P1 Closing can overtake final frames ▶
  4. P2 Tests mirror internal state ▶
Fix with agent prompt
### Issue 1
src/Appwrite/Messaging/Adapter/Realtime.php:161
When an impersonated socket sends a `subscribe` message, `subscribe()` replaces its connection entry without preserving `impersonatedUserId`. Later messages lose the target-user metadata, and the authentication handler no longer recognizes the socket as impersonated, allowing it to bypass the prohibition on re-authentication. Preserve the marker across in-band subscriptions.

**How this was verified:** The subscribe handler calls `subscribe()` without restoring the marker, while the authentication guard reads that marker from the connection entry.

```suggestion
        foreach (['authorization', 'impersonatedUserId', 'sessionId'] as $key) {
```

### Issue 2
app/realtime.php:undefined-982
When an impersonator’s session is deleted, this code stores no session ID for the impersonated socket. The revocation check therefore skips that session, leaving the socket subscribed to the target user and able to receive their events after the session that authorized impersonation has ended.

**How this was verified:** Impersonated connections store a null session ID, and the revocation check validates sessions only when that ID is non-null.

### Issue 3
app/realtime.php:791-793
Under websocket backpressure, sending the final event and 401 error starts asynchronous pushes that can yield. This code closes the socket without waiting for either push to finish, so the client may miss the event or error frame, or receive them out of order.

### Issue 4
tests/unit/Messaging/MessagingTest.php:652-660
This test checks the internal `permissionsChanged` mapping rather than whether a user event changes what a socket can receive. The companion test directly edits and asserts `Realtime::$connections`. The repository requires tests of observable behavior, not assertions that mirror implementation details. These tests can pass while delivery or revocation is broken and must be brought into line with that requirement before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR refreshes open realtime connections on user-record events and tracks sessions so revoked connections receive an error and close.

  • The latest changes include connections without subscriptions in re-resolution and preserve owned presences during a rebuild.
  • In-band subscription now drops the impersonation marker, allowing the re-authentication guard to be bypassed.

Reviews (2) · Last reviewed commit: "fix(realtime): re-resolve every connecti..."

Comment thread app/realtime.php Resolved
Comment thread app/realtime.php Resolved
Comment thread tests/unit/Messaging/MessagingTest.php Resolved
@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/realtime-session-lifecycle (after).

Metric Before After Change
🚀 Requests/sec 199.26 209.85 🟢 +5.3%
⏱️ Latency P50 85.51 ms 82.34 ms ⚪ -3.7%
⏱️ Latency P95 210.95 ms 188.43 ms 🟢 -10.7%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 82.34 188.43 13,224 209.85 -22.52
Account 153.84 282.29 696 11.55 -71.41
TablesDB 78.82 143.01 7,192 116.44 -6.49
Storage 77.18 166.31 3,480 58.06 -9.48
Functions 119.5 238.79 1,856 31.6 -44.83

Top API waits (after)

API request Max wait (ms)
account.name.update 466.05
account.prefs.update 416.5
tablesdb.rows.update 378.54
tablesdb.rows.decrement 364.37
functions.create 345.47

Connections are looked up from connection state instead of the
subscription tree, so a connection opened without channels, or that
dropped its last subscription, is re-resolved too. The rebuild now
carries owned presences across, and the e2e helper catches the timeout
subclass before its parent.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

…nator

An impersonated connection carries the target user's roles but was opened
on the impersonator's session, so it now records who opened it (and on
which session) and is re-resolved on that user's events: it ends when
that session ends or that user is blocked or deleted, while the target's
own events keep refreshing its roles. `subscribe()` keeps the
impersonation keys across resubscribes, so the in-band authentication
guard holds after a later subscribe message.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ArnabChatterjee20k and others added 8 commits October 1, 2026 12:00
The user resource authenticates x-appwrite-key + x-appwrite-user against
the platform database on any project, but the impersonator binding used
the connection's project unless in admin mode or on the console. A
console impersonator using an account key on a custom project was bound
to that project: their console block, delete or session end never
closed the socket, while events for a project user with the same ID
could close it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ge no access

Every users.* event was flagged permissionsChanged, so a prefs or name
update re-fetched the user and rebuilt roles for all of their open
connections. User events that neither shape roles nor end a session are
now listed in USER_EVENTS_WITHOUT_ACCESS_CHANGE and skipped; anything not
listed still re-resolves, so new user events are safe by default.

update.password and recovery.*.update stay re-resolving: with
invalidateSessions they delete sessions without emitting
sessions.*.delete. update.email and update.phone reset verification.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Creating a session can end others without emitting sessions.*.delete:
the session limit hook and ID-token sign-in delete older sessions
directly. Magic URL, email/phone OTP and OAuth sign-in can also set
emailVerification or phoneVerification, which changes roles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Expiry fires no event, so a connection outlived the session or JWT it
was opened with until some other user event re-checked it, while the
HTTP API refuses that session's next request. Connections now record
when their session (`expire`) and JWT (`jwtExpire`) end; delivery skips
expired connections and closes them with a 401 frame, and a per-worker
tick closes expired connections that receive nothing.

Extending a session moves its expiry, so `sessions.*.update` re-resolves
the user's connections again and refreshes `expire`. Re-authenticating
with a session cookie replaces any JWT the connection was opened with.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the 60s sweep. Expiry is checked before every send instead: event
delivery, the console stats broadcast and the live-tail flush. An idle
expired connection stays open but receives nothing, and is closed at its
next send.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The user resource verifies the JWT, then the session and jwtExpire
resources decode it again. If it expired in between, they returned null
and the connection lost both its session and its JWT expiry. The
signature is checked before expiry, so on an expiry error their claims
are read unverified and the connection is closed at its first send.

Adds an e2e regression for a console live tail opened with a JWT: after
expiry it delivers no tail frames and is closed with 401.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g is removed

The HTTP API re-checks the impersonator flag on every request, but an
impersonated socket kept the target's roles until the impersonator's
session ended. users.*.update.impersonator now closes the connections
that user opened while impersonating.

The impersonator's events also refresh the expiry of those connections,
so extending the impersonator's session extends them instead of closing
them at the expiry they were opened with.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ArnabChatterjee20k and others added 6 commits October 1, 2026 12:10
…once extended

Runs on its own project with the 60s minimum session duration, extends
the impersonator's session, waits until an unextended session from the
same moment is refused, then checks the impersonated socket still gets
the target's events.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oked

fix(realtime): end impersonated connections when the impersonator flag is removed
fix(realtime): close connections when their session or JWT expires
…ount-key

fix(realtime): bind account-key impersonators to the console project
fix(realtime): skip re-resolving connections on user events that change no access
fix(realtime): keep impersonated connections in step with the impersonator

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 1 blocking finding to address. Summary

Comment thread app/realtime.php Resolved
Expiry was checked before every delivery, but onMessage still dispatched
requests from an expired connection, so a socket without subscriptions
could keep writing presences and getting responses. Inbound messages
now close an expired connection with the 401 frame, except
`authentication`, which replaces the expired credentials with a
session's. The 401 frame is built once at file scope and shared.

The impersonation e2e now updates the target's labels instead of its
name: name updates no longer rebuild the connection, so the step did not
prove the impersonator binding survives a rebuild.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

Comment thread app/realtime.php Resolved
Opens a socket with a 2s JWT and no channels, so no delivery can close
it, checks ping is answered, waits until the HTTP API refuses the JWT,
then asserts the next ping gets a 401 frame and the socket closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 81d17cf into main Oct 1, 2026
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants