Repository navigation
Persist browser sessions without delaying hydration - #7363
Conversation
[High impact] No new blocking issue was identified in this PR. SummaryThis PR saves browser sessions in HttpOnly cookies without holding up hydration or ordinary WebSocket events.
No new actionable findings were identified. The supplied previous threads have no comment numbers, so Reviews (26) · Last reviewed commit: "Merge branch 'pr-7362' into pr-7363" · Reviewed by Greptile |
12859c9 to
d42c9b7
Compare
d42c9b7 to
da3a484
Compare
da3a484 to
a8786e0
Compare
77997ba to
f72f7b7
Compare
Introduce a stdlib HS256 session codec, environment-only signing keys with rotation, and persistent local secrets excluded from exports. Preserve the local secret during web reinitialization. Validation: 421 affected tests passed, plus unknown-key diagnostic coverage; Ruff and targeted pyright passed. Refs: ENG-12910
f72f7b7 to
c8b6820
Compare
- A socket that connected with a cookie always renews over HTTP and gets no credential. The backend compared against the session as it was at connect, so once that copy expired it sent an exchangeable credential to page scripts although the browser held a renewed cookie. - A session past its maximum age is sent to the session endpoint, which issues a new session. Before, the socket sent no reply and the page stayed on the ended session until a reload. - The same-host origin rule requires the scheme of the request, and in production the exact origin. A plain HTTP page could install a session for the HTTPS host. - link_token_to_sid works without an ambient event context, as on main. - The compatibility fixtures and the breaking changelog wording move to the pull request that changes the default mode.
…on lasting failures - Browser tests read the client token through a shared helper. The token lives under a sessionStorage key scoped to the backend URL, so tests that waited for the old "token" key timed out. - The navigation test polls for its routed socket. A tab without a session cookie opens the socket after the page mounts, and a routed socket fires no page event. - An exchange that fails three times in a row stops holding HTTP calls and keeps retrying. A proxy that answers 404 held uploads forever. - A successful exchange clears an earlier denial, so the next refresh is scheduled.
The test compares all cookies and all storage keys of the page. The session adds one HttpOnly cookie and one localStorage key, and the client token is under a key scoped to the backend URL.
There was a problem hiding this comment.
2 issues found across 11 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/reflex-frontend/src/utils/state.js">
<violation number="1" location="packages/reflex-frontend/src/utils/state.js:1649">
P2: After the third failure, the scheduled retry can recreate `initialSessionExchange` and hold new uploads again, contrary to the intended lasting-failure release. Gate readiness creation after the threshold or track a separate flag that keeps readiness released while retries continue.</violation>
</file>
<file name="tests/integration/utils.py">
<violation number="1" location="tests/integration/utils.py:18">
P2: These helpers do not actually select the current backend-scoped entry; they select the first matching suffix. A tab that retained storage from an older backend URL can make tests read a stale token or refresh time, causing false assertions or timeouts. Derive the exact current storage key (or require it from the caller) instead of searching by suffix.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
link_token_to_sid built its session check from the ambient event context. A harness that drives the namespace directly, such as the event benchmark, has none, so its setup failed with LookupError. The check runs directly in that case.
An upload that the server refuses before the event handler runs, for example a 403 because the browser has no valid session cookie, only wrote to the browser console. The page now shows it as a failed event handler is shown: an error toast with the status and the reason, or an alert when the app has no toast provider. A cancelled upload, a network error and a handler failure are unchanged.
The error toast repeated the server's reason to every visitor: "The session does not authorize this client token." Production now says "Your session has expired. Reload the page and try again." for a 403 and "The server rejected the upload." for another 4xx. Development keeps the status and the server's reason, as the backend error toast does.
The production same-origin rule compared the raw authority of the Origin with the Host header. A proxy that forwards the Host with the default port written out, or in another case, made a same-origin exchange fail.
- The backend's refresh notice no longer restarts an exchange that the backend denied for this page's origin. The guard moved from the scheduler into the request itself. - After three failed attempts, a later retry does not hold HTTP calls again while its request is open.
WebKit does not store a Secure cookie from plain HTTP, also on a loopback host, so local development in Safari had no session: fresh state on each reload and rejected uploads. Local development over plain HTTP now sends the plain SameSite=Lax cookie next to the secure partitioned one, and each browser keeps the form that it accepts. The middleware reads the plain cookie only there, and prefers the secure one. HTTPS and production are unchanged.
The secure partitioned cookie works in a normal tab and in a cross-site iframe, and WebKit accepts Secure cookies from loopback hosts since 310542@main. The plain fallback cookie is removed.
An event context without an authorized session read and parsed REFLEX_SESSION_TOKEN_MODE on each creation (1.9 us). The parsed mode is now cached by the raw environment value (0.36 us), so a change to the environment still takes effect.
HTTP calls wait whenever the socket delivers a credential, on a first connection and on a reconnection alike. The flag that exempted later credentials was never cleared on disconnect, so an upload after a reconnection with an expired cookie could start before the new cookie.
The benchmarks connect a namespace that has no server and address state with a plain token. A connection now issues a session over the socket, so test_on_event_router_data failed at setup. The fixture moves here from the integration PR.
Merging this PR will improve performance by 4.72%1 warning
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
# Conflicts: # packages/reflex-base/src/reflex_base/config.py # packages/reflex-base/src/reflex_base/session.py # tests/units/reflex_base/test_session.py
Let hydration and ordinary events run while the socket-delivered session credential is exchanged for an HttpOnly cookie. Credentials are never written to browser storage; routing-token and freshness keys are scoped to the backend URL. Web Locks coordinate simultaneous cold tabs, and duplicate tabs adopt server-issued replacement tokens.
Idle timers request fresh credentials over the authenticated socket; a connect or a tab that becomes visible requests one only when the saved refresh time passed. Failed HTTP exchanges retry with bounded backoff while readiness stays pending. Success releases waiting uploads and Enterprise HTTP helpers; teardown aborts the exchange and rejects readiness. When an existing cookie replaces the provisional token, readiness waits until the replacement socket connects.
Uploads reserve their cancellation controller before waiting, so cancellation works immediately. Waiting uploads do not block ordinary WebSocket events. Transport warmup for established sessions and CONNECT-packet hydration remain intact.
Depends on #7362; real browser and deployment coverage is in #7364. Enterprise helper compatibility is in reflex-dev/reflex-enterprise#240. Merged with current main, including its reconnect retry and CONNECT auth changes in
state.js.Validation: all 13 frontend runtime/lifecycle wrapper tests pass, including the actual upload helper, idle renewal, retry recovery, cancellation, late responses after teardown, and cookie-replacement reconnects. The new failure/reconnect regressions fail before their fixes. Full assembled stack: 12,147 unit tests passed with 80.15% coverage.
Review fixes:
getToken()returns a legacy tab token until the server replaces it.Second review round:
CLIENT_TOKEN_JSintests/integration/utils.py: the token is under asessionStoragekey scoped to the backend URL, so tests from main that waited for thetokenkey timed out./_reflex/sessionheld them forever).An upload that the server rejects with a 4xx status, for example a 403 when the browser has no valid session cookie, now shows an error toast (an alert when the app has no toast provider). Production says "Your session has expired. Reload the page and try again." for a 403 and "The server rejected the upload." for another 4xx; development shows the status and the server's reason. Before, it only wrote to the browser console. Cancelled uploads, network errors and handler failures are unchanged.
Related to ENG-12919, ENG-9088.