# Add CSRF Protection to an Actix Web App

Yes. An agent adds a per-session CSRF token to a cookie-session Actix app, puts it in every form as a hidden field, rejects a mismatch with 403 and opens a PR.

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

## What the agent does

The agent reads the forms and the session before it chooses a scheme. In an app shaped like the `basics/todo` member of actix/examples, `Cargo.toml` takes `actix-web` 4.11, `actix-session` 0.11 with the `cookie-session` feature, `actix-files` and the 2024 edition from the workspace, and pins `sqlx` 0.9 on SQLite and `tera` 2 itself. `src/main.rs` builds a `SessionMiddleware` over `CookieSessionStore` with a zeroed 64-byte signing key and `cookie_secure(false)`, and registers three handlers: `GET /` renders `templates/index.html.tera`, `POST /todo` creates a task from a `web::Form<CreateForm>`, and `POST /todo/{id}` reads a `_method` field of `put` or `delete` to toggle or remove one. `src/session.rs` already stores a flash message in the session under the key `flash`. Every state change is a plain HTML form post with no token, so any page the user has open can submit to `/todo` on their behalf.

The agent adds a `csrf` module beside `session.rs`. On each request that renders the page, `csrf::token(&session)` returns the token stored in the session under `csrf_token` or generates a 32-byte random one with `rand`, which the workspace already pins, base64-encodes it and stores it. `index` inserts it into the Tera context as `csrf_token`, and `templates/index.html.tera` gets `<input type="hidden" name="csrf_token" value="{{csrf_token}}">` in the create form and in both per-task forms. `CreateForm` and `UpdateForm` gain a `csrf_token` field, and a `csrf::verify(&session, &form.csrf_token)` call at the top of `create` and `update` compares it to the session value in constant time with `subtle` and returns `error::ErrorForbidden` on a mismatch, which the existing `ErrorHandlers` can map to a static page like `400.html` and `404.html`.

The cookie session's `SameSite` default of `Lax` already blocks most cross-site posts, and the pull request says so; the token is for browsers and embeds where that is not enough, and for a reviewer who wants defence that does not depend on a cookie attribute. The signing key comment in `main.rs` is left as the example has it, but the pull request notes the key must be real before `cookie_secure` is turned on.

The example has no tests, so the agent adds `src/tests.rs` using `actix_web::test::init_service` with the same session middleware and a temporary SQLite database created through the `migrations/` folder: a `GET /` yields a `Set-Cookie` and a token in the body, a `POST /todo` with that cookie and token answers `302`, the same post with a wrong token answers `403`, and a post with no cookie answers `403`. It runs `cargo check --workspace --bins --examples --tests` and `cargo test -p todo` with `DATABASE_URL=sqlite://./todo.db` after `sqlx database create` and `sqlx migrate run`, the steps `.github/workflows/ci.yml` performs, plus `cargo clippy` and the `just check` formatting pass, and pastes the output in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CSRF protection to the basics/todo app in this Actix Web repository and open a pull request. Read basics/todo/Cargo.toml, basics/todo/src/main.rs, basics/todo/src/api.rs, basics/todo/src/session.rs, basics/todo/templates/index.html.tera, basics/todo/.env, basics/todo/migrations/ and .github/workflows/ci.yml first. Add a csrf module that stores a random base64 token in the cookie session under csrf_token, generating it on first use with the rand crate from the workspace. Render it as a hidden csrf_token input in the create form and both per-task forms in the Tera template. Add a csrf_token field to CreateForm and UpdateForm and verify it against the session in constant time at the top of create and update, answering 403 on a mismatch or a missing session. Add tests with actix_web::test that cover a successful post with the token, a wrong token, and no cookie, against a temporary SQLite database built from the migrations. Run sqlx database create, sqlx migrate run, cargo check --workspace --bins --examples --tests, cargo clippy -p todo and cargo test -p todo, and paste the output in the pull request. Do not change other members of the workspace.",
  "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

What comes back is a pull request confined to `basics/todo/`: a new `src/csrf.rs`, a `mod csrf` line and three guarded handlers in `src/api.rs`, three hidden inputs in `templates/index.html.tera`, a `src/tests.rs` module, and `Cargo.toml` taking `rand` from the workspace and adding `subtle`. The description shows the `cargo test -p todo` summary, the `cargo check` and `clippy` results, and a `curl` transcript of a post without the token answering `403`.

On a repository with the examples' workflow, the pull request runs the `cargo check` across the whole workspace and `cargo test --workspace` on the matrix, after the workflow's own `sqlx database create` and `migrate run` steps, so the new tests execute under the same database setup CI already has.

A reviewer checks that the comparison is constant time, that the token is regenerated when the session is cleared, that `_method` handling in `update` is still reached only after verification, and whether they also want the token checked on a `Referer` or `Origin` mismatch. Then they replace the zeroed signing key and enable `cookie_secure` behind TLS.

## Run it on every security finding filed

A security review that files one finding per form-posting app can start one run per finding with this prompt and the finding's repository in `resources`, through a handler on the reader's server that calls `POST /o/{org}/sessions`. Each run reads its own templates and handlers, so an app with a dozen forms gets the hidden input in every one of them, and each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn finishes, with the `session_url` to read the pull request and the `403` transcript from.

## Why run it on Rush?

CSRF tokens are a cross-cutting change: a session helper, every form in every template, every handler that mutates state, and a test that proves the forbidden path actually fires. Doing it by hand means one missed form that silently stays open. In a Rush sandbox the agent edits them all, runs the suite with a real SQLite file built from the migrations, and keeps every `cargo` command and its output in the run's record.

The same request works on any Actix app that uses `actix-session` and server-rendered forms, and because the run opens a pull request through the Rush GitHub App, the fix for a finding arrives as a diff with the proof attached rather than as a ticket that waits.

## Frequently asked questions

### Isn't SameSite=Lax on the session cookie enough?

It blocks cross-site form posts in current browsers, and the pull request says so. The token covers browsers and contexts that do not honour it, and does not depend on a cookie attribute someone may later relax. Both together is the usual recommendation.

### Does it add a dependency?

Two: `rand` for the token bytes, which the workspace `Cargo.toml` already pins, and `subtle` for the constant-time comparison, added to the crate's own `Cargo.toml`. No CSRF middleware crate is added, because the app's forms and session are simple enough that a module of about forty lines is clearer.

### What happens to JSON or API clients?

This app has none; every mutation is a form post. If an API is added later, the pull request's note recommends a separate scope without the session middleware rather than exempting routes from the check.

### Will the token survive the flash message?

Yes. The flash helper in `session.rs` removes only its own `flash` key, so the token under `csrf_token` stays for the life of the cookie session. A fresh browser session gets a new token on its first page load.

## More Actix Web jobs

- [Add Cursor Pagination to an Actix Web API](https://getrush.ai/run/add-cursor-pagination/actix/)
- [Add Database Migrations to an Actix Web App](https://getrush.ai/run/add-database-migrations/actix/)
- [Add Graceful Shutdown to an Actix Web App](https://getrush.ai/run/add-graceful-shutdown/actix/)

## The same job on other stacks

- [Add CSRF Protection to an aiohttp App](https://getrush.ai/run/add-csrf-protection/aiohttp/)
- [Add CSRF Protection to a CodeIgniter 4 App](https://getrush.ai/run/add-csrf-protection/codeigniter/)
- [Add CSRF Protection to a Fastify App](https://getrush.ai/run/add-csrf-protection/fastify/)

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