Skip to content

Authorize browser state through session-aware transports - #7362

Merged
FarhanAliRaza merged 43 commits into
mainfrom
codex/session-transport
Nov 25, 2026
Merged

FarhanAliRaza merged 43 commits into
mainfrom
codex/session-transport

Conversation

@masenf

@masenf masenf commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

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 off mode also receive a routing token.

POST /_reflex/session installs 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/token contract is unchanged.

Event contexts inherit browser authority, explicit None means anonymous, and trusted server work can use SessionToken.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_middleware to preserve the public rx.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/session keeps a client token that the session does not own outside enforce, 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.
  • The exchange trusts a page on the host that the request reached. The frontend replaces a loopback API host with the host of its page, so a dev server opened through a LAN address got a 403.
  • Only POST /_reflex/session renews the cookie. The middleware no longer adds it to other responses, which a shared cache can store.
  • A socket that connected with a valid cookie gets no credential on session_refresh; the client renews the HttpOnly cookie over HTTP. The in-band credential stays for sockets without a valid cookie.
  • SharedState._link_to applies the session check when the link target is a client token, so enforce covers that path.
  • A request body nested past the recursion limit returns 400.

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 warn in this pull request. #7364 changes it to enforce, where the frontend that handles enforcement is present.

Structure changes after review:

  • authorize(session, token) in reflex_base.session is the one place that applies the session mode. EventContext, the upload route and the shared-state link call it.
  • SessionTokenManager.client_token_for decides a tab's token for both the socket connection and the session endpoint.
  • The socket sends a credential encoded for exchange: valid for one minute and only at POST /_reflex/session. 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, next refresh time and whether it connected with 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 (new rx.Config field, 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:

  • A socket that connected with a cookie always renews at POST /_reflex/session and 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.
  • A session past its maximum age is sent to the session endpoint for a new session, in place of no reply.
  • The same-host origin rule requires the scheme of the request, and in production the exact origin.
  • link_token_to_sid works 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.

@masenf
masenf added this pull request to stack #7365 September 30, 2026 00:41
@masenf masenf changed the title Authorize browser state through session-aware HTTP and WebSocket transports Authorize browser state through session-aware transports Sep 30, 2026
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] No unresolved blocking issue was found, with browser exchange and idle renewal supplied by PR #7363.

Summary

This 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.

  • Browsers get bounded sessions through cookies and a dedicated endpoint.
  • Socket events carry browser-session authority into state work.
  • State access checks whether a browser session owns the client token.
  • Uploads check session ownership and keep streamed work in its own transaction.
  • Dependency floors and small compatibility updates match the current main branch.

Reviews (24) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..." · Reviewed by Greptile

Comment thread reflex/app.py Resolved
Comment thread reflex/app.py Resolved
Comment thread reflex/app.py Resolved
@masenf
masenf force-pushed the codex/session-transport branch from 9eb0a30 to 9e6efe3 Compare October 5, 2026 21:24
@linear-code

linear-code Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

@masenf
masenf force-pushed the codex/session-transport branch from 9e6efe3 to 1ea0399 Compare October 8, 2026 17:55
@masenf
masenf force-pushed the codex/session-transport branch from 1ea0399 to 4962d46 Compare October 8, 2026 18:24
@masenf
masenf force-pushed the codex/session-transport branch 2 times, most recently from b23f99f to a931b1c Compare October 8, 2026 19:03
@masenf
masenf force-pushed the codex/session-transport branch from a931b1c to 9120624 Compare October 14, 2026 09:35
Comment thread reflex/session_middleware.py Resolved
…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.

@cubic-dev-ai cubic-dev-ai 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.

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

Comment thread reflex/istate/shared.py Resolved
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.

@cubic-dev-ai cubic-dev-ai 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.

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.
Comment thread reflex/app.py Resolved
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.

@cubic-dev-ai cubic-dev-ai 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.

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

Comment thread reflex/session_middleware.py Resolved
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.
Comment thread reflex/session_middleware.py Resolved
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.
@codspeed

codspeed Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 5.24%

1 warning

⚠️ 18 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

❌ 3 regressed benchmarks
✅ 143 untouched benchmarks
⏩ 8 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_get_state[memory] 1.1 ms 1.1 ms -5.46%
❌ test_on_event_router_data 2 ms 2.1 ms -5.14%
❌ test_yield_intermediate_update 1.4 ms 1.5 ms -5.11%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing codex/session-transport (f34272a) with main (38744ee)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Base automatically changed from codex/codex/session-token-primitives to main November 25, 2026 16:22
# Conflicts:
#	packages/reflex-base/src/reflex_base/config.py
#	packages/reflex-base/src/reflex_base/session.py
#	tests/units/reflex_base/test_session.py
@FarhanAliRaza
FarhanAliRaza merged commit ea5d16f into main Nov 25, 2026
170 of 171 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the codex/session-transport branch November 25, 2026 16:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Anything you want improved on deck PRs lined up to review / merge next roadmap https://github.com/reflex-dev/reflex/issues/2727 security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants