Skip to content

fix(realtime): close connections when their session or JWT expires - #14039

Merged
ArnabChatterjee20k merged 7 commits into
fix/realtime-skip-user-eventsfrom
fix/realtime-session-expiry
Oct 1, 2026
Merged

ArnabChatterjee20k merged 7 commits into
fix/realtime-skip-user-eventsfrom
fix/realtime-session-expiry

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Stacked on #14038 (→ #14040 → #14024 → #14021).

Why

Expiry fires no event. #14021 closes a connection when its session is deleted or the user is blocked, but a session that simply times out was only noticed when some unrelated users.* event happened to re-check it. The HTTP API refuses that session's next request; realtime kept delivering.

What

  • Connections record two Unix timestamps (only per-connection memory, no DB reads):
    • expire: when the session the connection runs on ends (User::getSessionExpiry()). Set for cookie and JWT connections alike; for impersonated connections it's the impersonator's session.
    • jwtExpire: the exp claim of the JWT the connection was opened with, if any. A connection can't present a fresh token, so it ends with the JWT, as an HTTP request would.
  • Realtime::isExpired() checks both, before every send: event delivery, the console stats broadcast, and the console live-tail flush (via the new EventTailRegistry::getConnections()). An expired connection gets nothing more and is closed with the existing 401 error frame. There's no separate sweep: an idle expired connection stays open but receives nothing, and is closed at its next send.
  • sessions.*.update (session extension) comes back off the fix(realtime): skip re-resolving connections on user events that change no access #14038 skip list, so the role rebuild re-reads expire and an extended session keeps its connections.
  • A JWT that expires between the user resource verifying it and the session / jwtExpire resources decoding it again keeps its claims (the signature is checked before expiry), so the connection doesn't lose its expiry; it's closed at its first send.
  • Re-authenticating over the socket with a session cookie sets expire from that session and clears jwtExpire.
  • The 401 frame is now built once per worker and shared by both closing paths. $closing is keyed by connection so one connection isn't closed twice.

Behaviour change

JWT-authenticated sockets are now closed when the JWT expires (default 900s, max 3600s). Clients authenticating realtime with a JWT need to reconnect with a fresh one, same as for HTTP.

Not covered

  • An impersonated connection keeps the impersonator's session expiry from when it opened; extending the impersonator's session doesn't extend it (it'd need a reconnect).
  • The SDK-test broadcast in the 5s tick doesn't check expiry; it only reaches guests, who have none.

Tests

  • Unit: UserTest::testGetSessionExpiry, MessagingTest::testIsExpired, EventTailRegistryTest::testGetConnections; testSubscribeKeepsConnectionAuthorizationState covers carrying expire/jwtExpire across resubscribes; sessions.S.update moved to the re-resolving cases.
  • E2E: testConnectionEndsWithJwt opens one socket with a 2s JWT and one with the session cookie behind it, waits (polling) until GET /account refuses the JWT, then updates prefs: the cookie socket gets the event and stays open, the JWT socket gets nothing and is closed with 401. RealtimeCustomClientQueryTestWithMessage::testConsoleTailEndsWithJwt does the same for a console live tail opened with a 2s root JWT: no tail frames after expiry, then 401 and close. Not run locally (no Docker); relying on CI.

🤖 Generated with Claude Code

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

@ghost

ghost commented Oct 1, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

Limited by an open minor finding: Keep expiry when the session expires during connection setup

The pull request records session and JWT expiry on realtime connections and closes expired connections before event, stats, or console-tail delivery. It preserves expiry across subscriptions and updates it after session extensions, with unit and E2E coverage for JWT expiry. The latest changes also refresh impersonated connections when the actor's session is extended and close them when the actor loses impersonation capability.

Latest changes: The new commits refresh impersonated connections' session expiry, revoke them when impersonation capability is removed, and add E2E coverage for both behaviors.

Verdict New comments Fixed Still open
✅ Approved 0 0 2
Fix with agent prompt
### Issue 1
app/realtime.php:1040-1041
**Keep expiry when the session expires during connection setup**

If the session expires after the `user` resource authenticates it but before the `session` resource rechecks it, `connection.php:315–340` returns null while the authenticated user remains populated. This stores no session expiry or session ID, so a cookie socket can keep receiving protected events indefinitely until another access-change event; retain the originally authenticated session and its expiry, or reject setup when that session has just expired.

### Issue 2
app/realtime.php:689-693
**Cover session timeout and extension through realtime E2E tests**

The new E2E tests exercise JWT expiry only, so they would still pass if cookie connections never recorded session expiry or session extensions failed to refresh it. Please add a short-lived cookie-session test covering both timeout delivery suppression and an extension that keeps the socket receiving past its original deadline, alongside the existing realtime session-revocation tests.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 11
File Change
app/init/realtime/connection.php Preserves verified JWT claims across setup-time expiry and resolves JWT expiry.
app/realtime.php Tracks expiry, checks it before delivery, and refreshes or revokes impersonated connections on actor changes.
src/Appwrite/Messaging/Adapter/Realtime.php Preserves expiry across subscriptions and adds the expiry predicate.
src/Appwrite/Realtime/EventTailRegistry.php Exposes tail connection IDs for expiry checks.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Sets session expiry and clears JWT expiry after socket re-authentication.
src/Appwrite/Utopia/Database/Documents/User.php Adds a session-expiry timestamp accessor.
tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php Adds console live-tail JWT expiry coverage.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Tests JWT expiry, impersonation capability revocation, and impersonator session extension.
tests/unit/Messaging/MessagingTest.php Tests expiry checks, preservation across subscriptions, and session-update re-resolution.
tests/unit/Realtime/EventTailRegistryTest.php Tests tail connection enumeration and removal.
tests/unit/Utopia/Database/Documents/UserTest.php Tests expiry lookup and missing-session cases.
⏳ Still open from earlier reviews · 2

Reviewed the commits since eb623ca · 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 D · 2 blocking findings to address. Summary

Comment thread app/init/realtime/connection.php Resolved
Comment thread app/realtime.php Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

@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 D · See the inline comments. Summary

Comment thread app/realtime.php Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix/realtime-skip-user-events (before) → fix/realtime-session-expiry (after).

Metric Before After Change
🚀 Requests/sec 164.03 183.08 🟢 +11.6%
⏱️ Latency P50 103.33 ms 93.48 ms 🟢 -9.5%
⏱️ Latency P95 257 ms 220.99 ms 🟢 -14%
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 93.48 220.99 11,400 183.08 -36.01
Account 181.94 360.41 600 10.3 -38.08
TablesDB 90 172.06 6,200 102.31 -40.83
Storage 87.71 195.39 3,000 50.99 -15.54
Functions 136.81 275.7 1,600 27.82 -19.21

Top API waits (after)

API request Max wait (ms)
account.name.update 554.84
functions.create 500.43
tablesdb.rows.create 478.32
account.prefs.update 475.34
functions.variables.update 438.94

@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

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

ArnabChatterjee20k and others added 4 commits October 1, 2026 12:05
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]>
@ArnabChatterjee20k
ArnabChatterjee20k force-pushed the fix/realtime-skip-user-events branch from 83f6dbf to 89f6a8a Compare October 1, 2026 06:35
@ArnabChatterjee20k
ArnabChatterjee20k force-pushed the fix/realtime-session-expiry branch from dde35a1 to eb623ca Compare October 1, 2026 06:36

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

…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]>

@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
Comment on lines +1040 to +1041
// Impersonated or not, the connection lasts only as long as the session it runs on.
$expire = $session !== null ? $user->getSessionExpiry($session->getId()) : null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Keep expiry when the session expires during connection setup

If the session expires after the user resource authenticates it but before the session resource rechecks it, connection.php:315–340 returns null while the authenticated user remains populated. This stores no session expiry or session ID, so a cookie socket can keep receiving protected events indefinitely until another access-change event; retain the originally authenticated session and its expiry, or reject setup when that session has just expired.

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/realtime.php
Line: 1040-1041

Comment:
**Keep expiry when the session expires during connection setup**

If the session expires after the `user` resource authenticates it but before the `session` resource rechecks it, `connection.php:315–340` returns null while the authenticated user remains populated. This stores no session expiry or session ID, so a cookie socket can keep receiving protected events indefinitely until another access-change event; retain the originally authenticated session and its expiry, or reject setup when that session has just expired.

---

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

🟡 Minor · bug · Reply if this doesn't apply.

Comment thread app/realtime.php
Comment on lines +689 to +693
// Re-read, as extending the session moves it. An impersonated
// connection has no sessionId and keeps what it was opened with.
$expire = $sessionId !== null
? $user->getSessionExpiry($sessionId)
: ($realtime->connections[$connection]['expire'] ?? null);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cover session timeout and extension through realtime E2E tests

The new E2E tests exercise JWT expiry only, so they would still pass if cookie connections never recorded session expiry or session extensions failed to refresh it. Please add a short-lived cookie-session test covering both timeout delivery suppression and an extension that keeps the socket receiving past its original deadline, alongside the existing realtime session-revocation tests.

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/realtime.php
Line: 689-693

Comment:
**Cover session timeout and extension through realtime E2E tests**

The new E2E tests exercise JWT expiry only, so they would still pass if cookie connections never recorded session expiry or session extensions failed to refresh it. Please add a short-lived cookie-session test covering both timeout delivery suppression and an extension that keeps the socket receiving past its original deadline, alongside the existing realtime session-revocation tests.

---

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

🟡 Minor · testing · Reply if this doesn't apply.

…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
@ArnabChatterjee20k
ArnabChatterjee20k merged commit f1fb8ba into fix/realtime-skip-user-events Oct 1, 2026
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.

1 participant