Repository navigation
Authorize browser state through session-aware transports - #7362
Conversation
[High impact] No unresolved blocking issue was found, with browser exchange and idle renewal supplied by PR #7363. SummaryThis PR binds HTTP requests, socket events, uploads, and shared-state links to browser sessions. It also separates socket exchange credentials from cookies and caps session renewal.
Reviews (24) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..." · Reviewed by Greptile |
9eb0a30 to
9e6efe3
Compare
9e6efe3 to
1ea0399
Compare
1ea0399 to
4962d46
Compare
b23f99f to
a931b1c
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
a931b1c to
9120624
Compare
…owner each - authorize(session, token) is the one place that applies the session mode. EventContext calls it, and so do the upload route and the shared state link, which built an EventContext only to trigger the check. - SessionTokenManager.client_token_for decides the token of a tab for both the socket connection and the session endpoint. The two copies of that rule disagreed before and made the client reconnect without end. - The socket sends a credential encoded for exchange: it is valid for one minute and only at the session endpoint. A cookie value is not accepted for exchange, and an exchange credential is not accepted as a cookie. - One record per socket holds its session, its next refresh time and whether it connected with a cookie, in place of three containers.
There was a problem hiding this comment.
All reported issues were addressed across 10 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
A session credential expired after session_token_ttl, but each renewal set a new expiry for the same session, so a credential that kept renewing never ended. The credential now carries the time of first issue. Renewal keeps that time, and the expiry cannot pass first issue plus session_token_max_age (seven days by default). A live socket gets no new credential after that age. The cookie Max-Age and the reported expires_in are the remaining lifetime.
There was a problem hiding this comment.
All reported issues were addressed across 7 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
A blank value read as unset, so reflex run generated a key. An environment file that holds the blank value restored it on the next config load, and each worker then generated its own key.
- Pass session_token_max_age from the config to the session manager; the setting had no effect. - A malformed Origin on the session exchange returns 403, not 500. - The shared-state link check runs before the earlier link changes, so a rejected link keeps the earlier one. - A connect that fails while linking its token drops its session record. - The cookie policy test compares the complete cookie attributes and warning. - Changelog: the upload rejection is a breaking change and returns 403.
A blank REFLEX_SECRET_KEY counts as not set: reflex run warns and generates a key, as for a missing one. The generated key now lives in an internal environment variable. An environment file that holds a blank REFLEX_SECRET_KEY restored that blank value in each worker, and each worker then generated its own key.
# Conflicts: # tests/units/reflex_base/test_session.py
The transport and the frontend that handle enforcement arrive in later pull requests of this stack, so the default changes to enforce in the last one. With enforce here, the transport pull request failed its browser tests against the frontend on main.
- 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.
There was a problem hiding this comment.
1 issue found across 10 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="reflex/session_middleware.py">
<violation number="1" location="reflex/session_middleware.py:265">
P2: This raw `netloc` comparison rejects valid same-origin production requests when the Host header preserves case or includes the default `:443`/`:80` port. Compare normalized host authorities, including default-port equivalence, so cookie-less bootstrap and renewal continue to work behind these proxies.</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.
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.
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.
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 degrade performance by 5.24%1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting 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
Bind HTTP requests, Reflex socket events, custom WebSocket routes, and uploads to verified browser sessions before accessing state. Cookie-less sockets receive session/client tokens in-band so hydration can start immediately. Fresh clients in
offmode also receive a routing token.POST /_reflex/sessioninstalls an HttpOnly cookie only from a trusted Origin when exchanging an in-band credential; wildcard CORS alone cannot authorize that exchange. Existing valid cookies take precedence. Cookies use Secure, SameSite=None, and Partitioned with the documented development fallback. Enterprise's/_reflex/auth/tokencontract is unchanged.Event contexts inherit browser authority, explicit
Nonemeans anonymous, and trusted server work can useSessionToken.SYSTEM. Custom WebSockets no longer inherit SYSTEM accidentally. Authenticated live sockets can renew their own credential after cookie expiry while preserving owner and tab bindings. HTTP responses advertise the refresh interval. Streamed uploads use a distinct transaction context.The internal transport module is named
reflex.session_middlewareto preserve the publicrx.session()database helper across import orders. Dependency floors and deprecation versions match current main.Depends on #7361; followed by #7363 and #7364. Merged with current main.
Validation: 390 transport/context/upload tests against an isolated real Redis server, two fresh-process database import regressions, full stack unit tests (12,147 passed; 80.15% coverage), and clean
pyright reflex tests. Regressions reproduce the custom-WebSocket authority, off-mode token, and idle-renewal failures before their fixes. Real Uvicorn/Granian/browser coverage is in #7364.Review fixes:
/_reflex/sessionkeeps a client token that the session does not own outsideenforce, as the socket connection does. A browser that stores no cookie (plain HTTP in prod, blocked cookies) got a new token on each connection, and the client reconnected without end.POST /_reflex/sessionrenews the cookie. The middleware no longer adds it to other responses, which a shared cache can store.session_refresh; the client renews the HttpOnly cookie over HTTP. The in-band credential stays for sockets without a valid cookie.SharedState._link_toapplies the session check when the link target is a client token, soenforcecovers that path.Not changed: any port of the backend host can open a socket in the same session, because cookies are not scoped by port. The guide in #7364 states this.
The default mode stays
warnin this pull request. #7364 changes it toenforce, where the frontend that handles enforcement is present.Structure changes after review:
authorize(session, token)inreflex_base.sessionis the one place that applies the session mode.EventContext, the upload route and the shared-state link call it.SessionTokenManager.client_token_fordecides a tab's token for both the socket connection and the session endpoint.POST /_reflex/session. A cookie value is not accepted for exchange, and an exchange credential is not accepted as a cookie.Maximum session age: the credential carries the time of first issue, renewal keeps it, and the expiry cannot pass first issue plus
session_token_max_age(newrx.Configfield, seven days by default). A live socket gets no new credential after that age. Before, each renewal set a new expiry for the same session, so a credential that kept renewing never ended.Second review round:
POST /_reflex/sessionand never receives a credential. The backend compared against the session as it was at connect, so an older socket received an exchangeable credential although the browser held a renewed cookie.link_token_to_sidworks without an ambient event context, as on main (the benchmark harness connects that way).Related to ENG-12911, ENG-12912, ENG-12913, ENG-12914, ENG-12915, ENG-9088.