# Add Security Headers to a Litestar App

Yes. An agent writes an ASGI middleware for your Litestar app that sets CSP, HSTS and the other security headers, tests it against the health route, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/litestar/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the app is assembled before it picks a policy, because a Content Security Policy that is wrong for the frontend blanks the page. In an app laid out like litestar-org/litestar-fullstack, `src/py/app/server/asgi.py` builds `Litestar(plugins=[ApplicationCore()])`, and `ApplicationCore.on_app_init` in `server/core.py` sets `cors_config`, an `OpenAPIConfig` whose `ScalarRenderPlugin` loads its script from a CDN, and the plugin list: structlog, Granian, SQLAlchemy, Vite, SAQ, problem details, OAuth2 providers, email and the domain plugin. `lib/settings.py` holds `ALLOWED_CORS_ORIGINS` (default `["*"]`), `COOKIE_SECURE` (default `False`), a `ViteSettings` with `mode="spa"` whose bundle lands in `server/static/web` under `/static/`, and `VITE_DEV_MODE`, which hands asset serving to the Vite dev server on the port in `VITE_PORT`. Nothing in `src/py/app` sets `Strict-Transport-Security`, `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` or a Content Security Policy; the one custom middleware, `StructlogMiddleware` in `lib/log.py`, only binds a logging context.

The frontend decides the policy. `src/js/web/index.html` preconnects to `fonts.googleapis.com` and `fonts.gstatic.com`, loads an Inter and Syne stylesheet from Google Fonts, and loads `/src/main.tsx` as a module; `vite.config.ts` writes the production bundle to `../../py/app/server/static/web`. So the production policy is `default-src 'self'`, `script-src 'self'`, `style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`, `font-src https://fonts.gstatic.com`, `img-src 'self' data:` and `connect-src 'self'`, with `frame-ancestors 'none'`. In dev mode the agent widens `script-src` and `connect-src` to the Vite dev server's origin, including its WebSocket, so hot reload keeps working, and it excludes the OpenAPI path from the strict policy because the Scalar renderer's script and stylesheet come from a CDN the policy would otherwise block.

The middleware itself is a `litestar.middleware.ASGIMiddleware` subclass in `src/py/app/lib/security_headers.py`, following the shape Litestar's own request-timing example uses: `handle` wraps `send`, and on each `http.response.start` message it opens the headers with `MutableScopeHeaders.from_message` and sets them. `scopes` is HTTP only, and `exclude_path_pattern` carries the OpenAPI path. The headers come from a new `SecuritySettings` dataclass in `settings.py`, read with the same `get_env` helper the other settings use, so a deployment can change the CSP or turn HSTS off with an environment variable; HSTS is only set when `COOKIE_SECURE` is true, since sending it over plain HTTP in development does nothing useful. The agent appends the middleware in `on_app_init` through `app_config.middleware`, beside the CORS config the file already sets, and adds an `ALLOWED_HOSTS` setting wired to `app_config.allowed_hosts`, which makes Litestar answer `400` to a request whose `Host` header is not in the list.

To check it, the agent writes `src/py/tests/integration/system/routes/test_security_headers.py` beside the existing `test_health.py`, using the `AsyncTestClient` fixtures from `tests/integration/conftest.py` to request `/health` and assert each header, and one test that the OpenAPI path is excluded. The integration suite uses `pytest-databases` to start Postgres in a container, so the agent installs Docker in its sandbox first (`sudo apt-get install -y docker.io`, then starts `dockerd`) and runs `uv run pytest src/py/tests/integration/system`, then `make lint`, which runs ruff, mypy, pyright, slotscheck, biome and codespell, and `uv run pre-commit run --all-files` as the `validate` job in `ci.yaml` does. It also builds the frontend with `make build-assets`, starts the app, loads it in its browser and keeps the console free of CSP refusals before it opens the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add security headers to this Litestar app. Read src/py/app/server/asgi.py, server/core.py, server/plugins.py, config.py, lib/settings.py, lib/log.py, src/js/web/index.html, src/js/web/vite.config.ts, src/py/tests/conftest.py, src/py/tests/integration/conftest.py and the tests under src/py/tests/integration/system first. Write an ASGIMiddleware in src/py/app/lib/security_headers.py that sets Content-Security-Policy, X-Content-Type-Options, X-Frame-Options, Referrer-Policy and Permissions-Policy on every HTTP response, and Strict-Transport-Security only when COOKIE_SECURE is true. Build the CSP from what index.html actually loads, widen it for the Vite dev server when VITE_DEV_MODE is on, and exclude the OpenAPI path since Scalar loads from a CDN. Put the values in a SecuritySettings dataclass read from the environment, add an ALLOWED_HOSTS setting wired to app_config.allowed_hosts, and register the middleware in on_app_init. Write integration tests for the headers on /health and the OpenAPI exclusion. Install Docker in the sandbox so pytest-databases can start Postgres, run the system integration tests, make lint and pre-commit, build the frontend, load the app in a browser and confirm no CSP refusals, and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `src/py/app/lib/security_headers.py` and `src/py/tests/integration/system/routes/test_security_headers.py`, and changes `lib/settings.py` (the `SecuritySettings` dataclass and `ALLOWED_HOSTS`), `config.py` and `server/core.py` (the registration) and `.env.local.example` (the new variables with their defaults). Its description shows the production and dev-mode policies side by side, lists each header with the reason for its value, and pastes the pytest, `make lint` and pre-commit output plus a `curl -i` of `/health` showing the header block.

The `Tests and Linting` workflow runs the `validate` job and the `test` matrix on the pull request, so a reviewer sees the new test file counted in the coverage upload. The run's record keeps the browser session, including the console with no CSP refusals on the signed-out landing page.

Before merging, a reviewer decides whether `style-src` should keep `'unsafe-inline'` or whether the stylesheet injection the bundle does can be moved to a nonce, whether `ALLOWED_HOSTS` should default to the host in `APP_URL`, and whether the OAuth callback pages for Google and GitHub need anything the policy does not yet allow.

## Run it on every new deployment target

A team with several Litestar services sends this body once per repository to `POST /o/{org}/sessions`, each with its own repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than opening a second pull request. Each run reads its own frontend: a service with server-rendered Jinja templates and inline scripts gets a nonce-based `script-src` proposal and a note on which templates need the nonce, a pure JSON API gets a policy with no `style-src` or `font-src` at all.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a script, stylesheet, font or image from a new origin to src/js/web, check whether SecuritySettings in lib/settings.py still allows it and comment with the directive to change" keeps the policy honest as the frontend grows. The trigger adds the pull request after the prompt, and only work by an owner, member or collaborator fires it.

## Why run it on Rush?

Security headers are easy to add and easy to get wrong: a `font-src` that forgets `fonts.gstatic.com` drops every glyph on the page, an HSTS header sent in development makes the browser refuse `http://localhost` for as long as its `max-age` says, and nobody notices until a browser console shows the refusal. The agent reads `index.html` and the Vite config, derives the policy from what they load, starts the app in its own sandbox and loads it in a real browser before it opens anything.

The pytest run, the lint pass, the `curl -i` header block and the browser session all stay with the run, so the review is of evidence rather than of a diff that looks right. A platform team that owns a handful of Litestar services runs them at once and gets one pull request per repository with the same proof attached.

## Frequently asked questions

### Why a middleware instead of an after_request hook?

Both can set headers, but an `ASGIMiddleware` sees every response including the ones static file handlers and plugins produce, and it carries `exclude_path_pattern`, which is how the OpenAPI path is excused. The agent follows the pattern Litestar's own request-timing example uses: wrap `send`, edit the `http.response.start` message with `MutableScopeHeaders.from_message`.

### Will this break the Vite dev server?

Not when `VITE_DEV_MODE` is on. In that mode the app hands asset serving to Vite on the port in `VITE_PORT`, and the policy widens `script-src` and `connect-src` to that origin, including the WebSocket hot reload uses. The production policy, with the bundle served from `/static/`, stays strict.

### Why is HSTS tied to COOKIE_SECURE?

Because the app already uses that setting to mean "this deployment is behind HTTPS". `Strict-Transport-Security` tells a browser to refuse plain HTTP for the host for its `max-age`, which is right in production and wrong on a developer's `localhost`. Tying it to the existing flag means nobody has to remember a second one.

### Does the run need Docker?

Only for the integration tests, which use `pytest-databases` to start Postgres in a container. The sandbox has no Docker by default, so the agent installs `docker.io` and starts `dockerd` before running `pytest`. The unit tests under `src/py/tests/unit` and `make lint` need nothing.

## More Litestar jobs

- [Add Soft Delete to a Litestar App](https://getrush.ai/run/add-soft-delete/litestar/)
- [Add Structured Logging to a Litestar App](https://getrush.ai/run/add-structured-logging/litestar/)
- [Add WebSockets to a Litestar App](https://getrush.ai/run/add-websockets/litestar/)

## The same job on other stacks

- [Add Security Headers to a Node.js App](https://getrush.ai/run/add-security-headers/nodejs/)
- [Add Security Headers to a Nuxt App](https://getrush.ai/run/add-security-headers/nuxt/)
- [Add Security Headers to a Quarkus REST API](https://getrush.ai/run/add-security-headers/quarkus/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
