fix(app): restrict default CORS origins to deploy_url in prod mode

Merged
FA
21d ago
+308-52

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Description

closes #7640

The ["*"] default for cors_allowed_origins let any site connect to the backend. This PR makes the default mode-aware, following the design in @masenf's review:

  • Dev mode: unchanged, any origin is allowed.
  • Prod mode, deploy_url unset (the new default): CORS is left unconfigured. No CORSMiddleware is installed and the Socket.IO server keeps Engine.IO's same-origin default, which is what a backend that serves its own frontend needs. Browsers cannot read cross-origin responses.
  • Prod mode, deploy_url set: only that origin is allowed, serialized the way browsers serialize Origin (lowercase host, no path, default port omitted; non-default ports and IPv6 hosts kept).
  • Explicit cors_allowed_origins (from rxconfig.py or REFLEX_CORS_ALLOWED_ORIGINS) is used as is in both modes, so ["*"] remains an opt-in to the old behavior. Explicitness is detected via Config._non_default_attributes.

Both enforcement points, the Starlette CORSMiddleware and the Socket.IO AsyncServer, resolve their origins through one helper, _cors_allowed_origins() in reflex/app.py.

Config changes

  • deploy_url now defaults to None instead of http://localhost:3000, and is no longer derived from frontend_port. It is only meant for frontends hosted on a different origin than the backend.
  • New Config.frontend_url property: deploy_url when set, otherwise http://localhost:<frontend_port> (the previous deploy_url default). The sitemap plugin builds absolute links from it.

Notes

  • Integration tests are unaffected: AppHarness pins dev mode before building the app and sets deploy_url itself.
  • The docs site keeps its http://localhost:3000 sitemap origin through frontend_url.

Tests

Unit tests cover dev vs prod, unset deploy_url (no middleware, Socket.IO same-origin default), path-bearing and default-port deploy_url forms, explicit lists, explicit ["*"] via kwargs and via env, request-level enforcement through Starlette's TestClient and Engine.IO's origin resolution, the frontend_url fallback, and the sitemap plugin. News fragments added for reflex and reflex-base (both breaking).

https://claude.ai/code/session_01C1xrGYmKsaacgEafTz9BTJ