# Add CSRF Protection to a Litestar App

Yes. An agent finds the cookie-authenticated routes, turns on Litestar's CSRFConfig with the header the frontend already sends, fixes the tests and opens a PR.

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

## What the agent does

The agent starts by finding which requests a cookie alone can authorise, because those are the ones cross-site request forgery reaches. In litestar-org/litestar-fullstack, `uv.lock` holds Litestar 2.19.0 and litestar-vite 0.17.0. `src/py/app/domain/accounts/guards.py` builds `OAuth2PasswordBearerAuth`, so most of the API wants a bearer token in a header, which a cross-site form cannot set. But `src/py/app/domain/accounts/controllers/_access.py` sets a `refresh_token` cookie on login, `httponly`, `samesite="strict"`, path `/api/access`, and `POST /api/access/refresh` and `POST /api/access/logout` read that cookie with no bearer; `_mfa_challenge.py` sets an `mfa_challenge` cookie with `samesite="lax"` on path `/api/mfa` that its verify route reads. All of them sit in the `exclude` list of the JWT auth. `ApplicationCore.on_app_init` in `src/py/app/server/core.py` sets `cors_config` and never sets `csrf_config`.

Then it finds that half the work was already done on the other side. `src/js/web/src/main.tsx` installs a request interceptor on the generated client that reads `window.__LITESTAR_CSRF__` and sends it as `X-XSRF-TOKEN` on every method other than GET, HEAD and OPTIONS. That global is written by litestar-vite's SPA handler, whose `SPAConfig` has `inject_csrf` on by default, but the handler takes the token from the request scope, where only Litestar's CSRF middleware puts one. With no `CSRFConfig` the global is never set, the header is never sent and the interceptor is dead code. The agent writes this chain into the pull request, because it is the reason the change is small.

The change is one object and one line. `AppSettings` in `src/py/app/lib/settings.py` already has `SECRET_KEY` and `COOKIE_SECURE`, so the agent adds a `get_csrf_config()` beside `get_cors_config()` that returns `CSRFConfig(secret=self.SECRET_KEY, header_name="X-XSRF-TOKEN", cookie_secure=self.COOKIE_SECURE, cookie_samesite="lax")`, keeping the default `csrftoken` cookie name and the default safe methods, exposes it from `app/config.py` and assigns it to `app_config.csrf_config` in `on_app_init`. The header name must match `main.tsx` exactly; the agent reads it from there rather than from memory. Litestar's middleware then sets the cookie on the first safe request, and on an unsafe one requires the header, or a `_csrf_token` form field, to match the cookie, answering a `PermissionDeniedException` otherwise. Routes that must stay open to clients that never loaded the page, such as the OAuth callbacks under `/api/auth/oauth/`, go in `exclude`, and the agent lists each one with its reason.

The tests are where this change bites, and the agent fixes them rather than excluding the routes they hit. `src/py/tests/integration/accounts/routes/test_access.py` posts to `/api/access/login` through an `AsyncTestClient` with form data and no CSRF header, which the middleware would now refuse. The agent adds a fixture that makes one GET to obtain the `csrftoken` cookie and returns a client whose default headers carry it as `X-XSRF-TOKEN`, switches the helpers in `test_access.py`, `test_mfa.py` and the team route tests to it, and adds two cases: a refresh with the cookie but no header is refused, and one with both succeeds. It runs `uv sync --all-groups`, `uv run pre-commit run --all-files` and `uv run pytest src/py/tests` as `.github/workflows/ci.yaml` does, and pastes what came back, including any test the sandbox could not run because it needs the PostgreSQL container that `pytest-databases` starts.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CSRF protection to this Litestar app. Read uv.lock for the litestar and litestar-vite versions, src/py/app/server/core.py, src/py/app/lib/settings.py, src/py/app/config.py, the accounts guards and controllers, and src/js/web/src/main.tsx first. List every route a cookie alone can authorise. Check whether the frontend already sends a CSRF header and what global it reads, and whether anything on the server sets that global today. Add a CSRFConfig built from the existing SECRET_KEY and COOKIE_SECURE settings, with the header name the frontend sends, set it on the app config, and exclude only routes that must be reachable by clients that never loaded the page, listing each with its reason. Do not exclude a route just because a test posts to it: add a test fixture that fetches the CSRF cookie and sends it back as the header, update the integration tests to use it, and add cases showing a refresh without the header is refused and with it succeeds. Run uv sync --all-groups, uv run pre-commit run --all-files and uv run pytest src/py/tests, paste the output in the pull request, say plainly if any test could not run in your environment, and open it.",
  "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

A pull request that changes `settings.py`, `config.py` and `core.py` by a few lines each, adds one test fixture and two test cases, and updates the login helpers in the integration tests; `main.tsx` is not touched, because it was already right. The description traces the chain from `CSRFConfig` to the scope to litestar-vite's injected global to the interceptor's header, lists the excluded routes, and quotes the pre-commit and pytest output.

A reviewer checks the `exclude` list first, since every entry is a route left unprotected, and asks for a reason beside each. They check that the header name in `CSRFConfig` is the one in `main.tsx`, and that `cookie_secure` follows the same setting as the refresh cookie so the two behave alike behind a proxy. They also read the new refusal test to see the status the client gets.

The pull request also says what did not change: the refresh cookie keeps `SameSite=Strict`, which already stops a cross-site POST in current browsers; the middleware adds the check for clients and paths where that attribute is not honoured and makes the frontend's existing interceptor do its job.

## Run it on every Linear issue labelled security

Each later security finding takes the same path. In the console, add an automation on the Project that holds the repository with a `linear` trigger on `linear.issue.labeled` and the label `security`, and a prompt that says: read the finding the issue describes, fix it at the configuration or middleware level where one exists, keep the tests passing by making them send what a browser would rather than by excluding routes, and open a pull request. The issue is placed after the prompt as the event and fills in nothing, so the finding comes from whoever wrote the issue. The trigger needs a Linear connection for the automation's runner and fires only when the label is applied by someone in your Rush org.

## Why run it on Rush?

The hard part of this job is not writing `CSRFConfig`; it is knowing that the frontend already sends a header nobody receives, which routes a cookie alone opens, and which tests will start failing and why. The agent reads the server, the SPA and the libraries in the lockfile together, in its own sandbox, and runs the suite the way CI does, so the pull request describes failures it saw rather than failures it expects.

Every command stays in the run's transcript at `GET /o/{org}/sessions/{id}/messages`, including a test run that could not reach a database, and the changed files are listed with their diff at `GET /o/{org}/p/{project}/sessions/{id}/changes`. A reviewer who doubts the claim that the header is already sent reads the interceptor the agent quoted, with its file and line, before merging.

## Frequently asked questions

### The API uses bearer tokens; does it still need CSRF protection?

The routes that take a bearer token do not, because a cross-site page cannot set the header. The ones that read a cookie do: the refresh and logout routes read the `refresh_token` cookie, and the MFA verify route reads the `mfa_challenge` cookie, with no bearer required. The middleware covers those, and the bearer routes get the check for free because the SPA sends the header everywhere.

### The refresh cookie is already SameSite=Strict. Why add more?

SameSite stops a current browser from sending that cookie on a cross-site POST, which is most of the risk. The CSRF token adds a second check that does not depend on the browser honouring the attribute, and it is what the frontend was written to send. The pull request says both, so the reviewer can weigh it.

### Why do the existing tests fail after this, and how are they fixed?

They post forms to `/api/access/login` with no CSRF header, which the middleware now refuses. The agent adds a fixture that performs one GET to receive the `csrftoken` cookie and returns a client sending it back as `X-XSRF-TOKEN`, so the tests do what a browser does. Excluding the routes would have hidden the hole the change is meant to close.

### Does the frontend need to change?

No. `main.tsx` already reads `window.__LITESTAR_CSRF__` and sends it as `X-XSRF-TOKEN` on unsafe methods, and litestar-vite injects that global once the server has a CSRF token to inject. The server-side config is the missing half.

## More Litestar jobs

- [Add Cursor Pagination to a Litestar API](https://getrush.ai/run/add-cursor-pagination/litestar/)
- [Write a Dockerfile for a Litestar App](https://getrush.ai/run/add-dockerfile/litestar/)
- [Add Graceful Shutdown to a Litestar App](https://getrush.ai/run/add-graceful-shutdown/litestar/)

## The same job on other stacks

- [Add CSRF Protection to a Node.js App](https://getrush.ai/run/add-csrf-protection/nodejs/)
- [Add CSRF Protection to a Slim 4 App](https://getrush.ai/run/add-csrf-protection/slim/)
- [Add CSRF Protection to an Actix Web App](https://getrush.ai/run/add-csrf-protection/actix/)

## 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/)
