Skip to content

fix(realtime): skip re-resolving connections on user events that change no access - #14038

Merged
ArnabChatterjee20k merged 10 commits into
fix/realtime-impersonationfrom
fix/realtime-skip-user-events
Oct 1, 2026
Merged

ArnabChatterjee20k merged 10 commits into
fix/realtime-impersonationfrom
fix/realtime-skip-user-events

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

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

What

#14021 sets permissionsChanged on every users.* event, so a prefs, name or avatar update re-fetches the user and rebuilds roles for all of their open realtime connections.

This adds USER_EVENTS_WITHOUT_ACCESS_CHANGE (next to RESOURCE_LEAF_NAMES): user events, written after users.{userId} with * for an ID segment, that neither shape roles nor end a session. fromPayload() doesn't flag those. Anything not listed still re-resolves, so a new user event is safe by default.

Deliberately not skipped

  • update.password, recovery.*.update — with invalidateSessions on, these delete sessions directly without emitting sessions.*.delete.
  • sessions.*.create — the session limit hook and ID-token sign-in delete older sessions directly, and magic URL, OTP and OAuth sign-in can set emailVerification / phoneVerification.
  • update.email, update.phone — reset emailVerification / phoneVerification, which changes the verified/unverified roles.
  • update.status, update.labels, update.verification, verification.*.update, sessions.*.delete, sessions.delete, delete.

update.mfa and the other MFA events are skipped because the realtime connection doesn't check MFA factors. If MFA enforcement is added there, they need to come off the list.

Tests

  • testFromPayloadUserEventsChangePermissions now also covers email, phone, password, verification and recovery updates.
  • New testFromPayloadUserEventsWithoutAccessChange checks every skipped event returns permissionsChanged: false.

🤖 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 B · Needs changes before merging

Expiry enforcement still allows authenticated message operations after expiry, and the previously reported re-resolution test gap remains open.

The PR skips permission re-resolution for user events that do not change access, while retaining conservative handling for other events. It also tracks impersonator bindings and revokes impersonated connections when the actor loses access. The latest changes add session and JWT expiry tracking, refresh session deadlines after extension, and check expiry before event delivery, with unit and E2E coverage.

Latest changes: The newest commits revoke connections when impersonator capability is removed and add session/JWT expiry enforcement, session-extension handling, and regression tests.

Verdict New comments Fixed Still open
🛑 Changes requested 1 1 1
Finding Where
🟠 Enforce expiry before authenticated message operations too app/realtime.php:801
Fix with agent prompt
### Issue 1
app/realtime.php:801-807
**Enforce expiry before authenticated message operations too**

Expiry is checked only on event delivery: `onMessage` still dispatches using the stored user and roles, so an expired JWT/session connection with no subscriptions can keep issuing `presence` messages and writing presence documents indefinitely (`Presence.php:68–95`). Please check expiry before dispatching authenticated operations as well, rather than relying on a future subscribed event to close the socket.

### Issue 2
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php:1128-1134
**Exercise an access-changing target event before revoking the actor**

The name update is now allowlisted, so this test never rebuilds the target's connection state and still passes if the impersonator restoration at `app/realtime.php:690` is removed. Use an access-changing update, such as labels or verification, before deleting the actor's session to actually verify that the binding survives re-resolution.

---

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 Records the impersonator's owning project and resolves session/JWT expiry metadata.
app/realtime.php Preserves impersonator bindings, handles revocation and session extension, and rejects expired event deliveries.
src/Appwrite/Messaging/Adapter/Realtime.php Classifies no-access-change events and preserves and queries connection authentication/expiry state.
src/Appwrite/Realtime/EventTailRegistry.php Exposes tail connection IDs for expiry checks.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Updates session expiry and clears JWT expiry when authenticating with a session.
src/Appwrite/Utopia/Database/Documents/User.php Adds session-expiry timestamp lookup.
tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php Tests that console tail connections end when their JWT expires.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Covers impersonator revocation, session extension, and JWT expiry.
tests/unit/Messaging/MessagingTest.php Tests event classification, authentication-state preservation, connection lookup, and expiry.
tests/unit/Realtime/EventTailRegistryTest.php Tests enumeration and removal of tail connections.
tests/unit/Utopia/Database/Documents/UserTest.php Tests session-expiry lookup and missing-session cases.
⏳ Still open from earlier reviews · 1
✅ Fixed since the last review · 1
  • Close impersonated connections when impersonation is revoked · app/realtime.php:636

Reviewed the commits since 89f6a8a · 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

@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-impersonator-account-key (before) → fix/realtime-skip-user-events (after).

Metric Before After Change
🚀 Requests/sec 191.41 198.59 ⚪ +3.8%
⏱️ Latency P50 86.47 ms 87.33 ms ⚪ +1%
⏱️ Latency P95 220.67 ms 204.77 ms 🟢 -7.2%
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 87.33 204.77 12,483 198.59 -15.9
Account 163.91 315.93 657 11.11 -53.46
TablesDB 84.11 162.28 6,789 110.16 -15.29
Storage 80.25 183 3,285 55.07 +10.88
Functions 121.39 242.25 1,752 29.98 -22.79

Top API waits (after)

API request Max wait (ms)
account.name.update 600.27
tablesdb.rows.increment 492.73
storage.buckets.create 411.93
account.prefs.update 404.28
tablesdb.rows.create 373.62

@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 and others added 6 commits October 1, 2026 12:04
…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]>
@ArnabChatterjee20k
ArnabChatterjee20k force-pushed the fix/realtime-skip-user-events branch from 83f6dbf to 89f6a8a Compare October 1, 2026 06:35
@ArnabChatterjee20k
ArnabChatterjee20k changed the base branch from fix/realtime-session-lifecycle to fix/realtime-impersonator-account-key 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 D · 1 blocking finding to address. Summary

app/realtime.php:636-639

Close impersonated connections when impersonation is revoked

Setting /users/{actorId}/impersonator to false emits users.{actorId}.update.impersonator and reaches this new branch, but an active session still passes $revoked, leaving the socket receiving the target user's private events. Please also check the actor's impersonator capability here, matching the check in app/init/realtime/connection.php:348.

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

Comment:
**Close impersonated connections when impersonation is revoked**

Setting `/users/{actorId}/impersonator` to false emits `users.{actorId}.update.impersonator` and reaches this new branch, but an active session still passes `$revoked`, leaving the socket receiving the target user's private events. Please also check the actor's `impersonator` capability here, matching the check in `app/init/realtime/connection.php:348`.

---

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

🔴 Critical · security · Reply if this doesn't apply.


tests/e2e/Services/Realtime/RealtimeCustomClientTest.php:1128-1134

Exercise an access-changing target event before revoking the actor

The name update is now allowlisted, so this test never rebuilds the target's connection state and still passes if the impersonator restoration at app/realtime.php:690 is removed. Use an access-changing update, such as labels or verification, before deleting the actor's session to actually verify that the binding survives re-resolution.

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/e2e/Services/Realtime/RealtimeCustomClientTest.php
Line: 1128-1134

Comment:
**Exercise an access-changing target event before revoking the actor**

The name update is now allowlisted, so this test never rebuilds the target's connection state and still passes if the impersonator restoration at `app/realtime.php:690` is removed. Use an access-changing update, such as labels or verification, before deleting the actor's session to actually verify that the binding survives re-resolution.

---

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]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Re the latest Hansi review on 89f6a8a:

🔴 Close impersonated connections when impersonation is revoked — already fixed further up the stack, in #14041 (stacked on #14039 → this PR). The impersonating loop now also closes a connection when the actor's impersonator flag is no longer true, matching the HTTP check, and testConnectionEndsWithImpersonatorSession gains a step that turns the flag off and asserts a 401 and close. This loop comes from #14024, which this PR now sits on after the rebase.

🟡 Exercise an access-changing target event before revoking the actor — valid, and not covered elsewhere in the stack. This PR puts update.name on the skip list, so the name update in testConnectionEndsWithImpersonatorSession no longer rebuilds the target's connection, and the test would still pass if the impersonator restore in the rebuild were removed. The step should use an event that still re-resolves, e.g. PATCH /users/:targetId/labels (users.*.update.labels), before ending the actor's session; that belongs in this PR.

…oked

fix(realtime): end impersonated connections when the impersonator flag is removed
fix(realtime): close connections when their session or JWT expires
@ArnabChatterjee20k
ArnabChatterjee20k changed the base branch from fix/realtime-impersonator-account-key to fix/realtime-impersonation October 1, 2026 10:02
@ArnabChatterjee20k
ArnabChatterjee20k merged commit 89bfac8 into fix/realtime-impersonation Oct 1, 2026
7 of 8 checks passed

@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
Comment on lines +801 to +807
// Expiry fires no event, so it is checked on every send. Nothing more
// once the session or JWT has expired, as the HTTP API would refuse it;
// the connection is closed below.
if ($realtime->isExpired($id, $now)) {
$closing[$id] = true;
continue;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Enforce expiry before authenticated message operations too

Expiry is checked only on event delivery: onMessage still dispatches using the stored user and roles, so an expired JWT/session connection with no subscriptions can keep issuing presence messages and writing presence documents indefinitely (Presence.php:68–95). Please check expiry before dispatching authenticated operations as well, rather than relying on a future subscribed event to close the socket.

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

Comment:
**Enforce expiry before authenticated message operations too**

Expiry is checked only on event delivery: `onMessage` still dispatches using the stored user and roles, so an expired JWT/session connection with no subscriptions can keep issuing `presence` messages and writing presence documents indefinitely (`Presence.php:68–95`). Please check expiry before dispatching authenticated operations as well, rather than relying on a future subscribed event to close the socket.

---

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

🟠 Major · security · Reply if this doesn't apply.

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