Apply the CORS middleware once per request

FA
3h ago
+15-23

Why

Every backend response repeats Origin in Vary. Without an api_transformer a response carries Vary: Origin, Origin. With a Starlette or FastAPI api_transformer it carries Vary: Origin, Origin, Origin, also on /ping.

#7624 meant to apply CORS once ("Requests no longer pass through … duplicate CORS middleware"). The outer CORS layer in App.__call__ was added, but the internal API and each Starlette transformer kept a CORS layer of their own. Each layer runs the origin check and appends Origin to Vary. Each layer overwrites access-control-allow-origin, so the tests named "exactly once" did not see the extra layers.

What changed

  • Remove the CORS layer on the internal API and on each Starlette or FastAPI api_transformer, and the App._add_cors helper that added them.
  • The outer layer stays. It covers the internal API, the transformer routes, the routes that a callable transformer adds, and the 500 responses of the outermost error handler.
  • Reflex no longer adds CORS middleware to the app passed as api_transformer. An app served through app() behaves the same.

How tested

  • Regression test first (3c3f3d09f): test_api_transformer_routes_get_cors_headers and test_unhandled_route_error_gets_cors_headers now compare the complete Vary value. Before the fix: assert ['Origin, Origin'] == ['Origin']. After the fix: they pass.
  • The tests that called App._add_cors now use App._cors_options().
  • Before the fix, a dev app with a Starlette api_transformer answered /ping and /_reflex/session with vary: Origin, Origin, Origin in Chromium. I did not run the app again after the fix. The unit tests pin the single value.
  • tests/units passes. ruff check, ruff format --check and pyright are clean.

Known limits

  • test_registered_middleware_are_classes now iterates an empty list, because Reflex registers no middleware on the internal API. I kept it as a guard for middleware that is added later.

Type of change

  • Bug fix (non-breaking change which fixes an issue)