Skip to content

fix(litestar): register plugin middleware at the outer boundary - #731

Closed
CyberneticX-Tech wants to merge 1 commit into
litestar-org:mainfrom
CyberneticX-Tech:fix/correlation-middleware-ordering
Closed

fix(litestar): register plugin middleware at the outer boundary#731
CyberneticX-Tech wants to merge 1 commit into
litestar-org:mainfrom
CyberneticX-Tech:fix/correlation-middleware-ordering

Conversation

@CyberneticX-Tech

Copy link
Copy Markdown

Description

SQLSpecPlugin.on_app_init appended its middleware to app_config.middleware:

app_config.middleware = [*(app_config.middleware or []), *new_middlewares]

Litestar runs middleware outermost first, so appending makes the plugin's entries the innermost in the pipeline. Any user middleware that rejects a request early (auth, CORS, rate limiting) short-circuits before the correlation middleware ever runs, and the access log and error hooks for exactly the requests you most want to trace have no correlation ID.

Fix

Prepend instead, so the correlation context is established at the outer boundary:

app_config.middleware = [*new_middlewares, *(app_config.middleware or [])]

Verification

Reproduced with a small app: a user middleware that returns 401 before the handler, with X-Request-ID: abc-123 on the request.

Before:

status: 401
correlation seen by outer rejecting middleware: None

After:

status: 401
correlation seen by outer rejecting middleware: 'abc-123'

Tests

Added test_correlation_middleware_runs_before_user_middleware to the existing correlation middleware tests. It installs a middleware that rejects with 401, then asserts the correlation ID was populated at that point.

Confirmed it is a real regression test. With the fix reverted:

FAIL test_correlation_middleware_runs_before_user_middleware: AssertionError
6 passed, 1 failed

and with the fix restored all 7 pass. ruff check and ruff format --check pass on both touched files.

Closes #729

The plugin appended its middleware to app_config.middleware, which makes
them the innermost entries in the ASGI pipeline. A request rejected by
user middleware that runs earlier (auth, CORS, rate limiting) never
reached the correlation middleware, so its access log and error hooks had
no correlation ID.

Prepend instead so the correlation context is established before user
middleware runs.

Closes litestar-org#729
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(litestar): prepend CorrelationMiddleware so correlation context is established on all requests

1 participant