# Add CSRF Protection to Ktor Form Posts

Yes. An agent installs Ktor's CSRF plugin for your form routes, allows your own origin from config, tests both outcomes with testApplication and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-csrf-protection/ktor/). 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 before it adds a check. In a Ktor app shaped like the `mvc-web` sample of ktorio/ktor-samples, `build.gradle.kts` applies `kotlin("jvm") 2.4.20` and `io.ktor.plugin 3.6.0`, depends on `ktor-server-core-jvm`, `ktor-server-config-yaml-jvm`, `ktor-server-netty-jvm`, `ktor-server-freemarker`, `ktor-server-status-pages`, Exposed `0.61.0` and H2 `2.4.240` from `gradle.properties`, declares `ktor-server-test-host-jvm` and `kotlin-test-junit` for tests, and sets `jvmToolchain(17)`. `application.yaml` loads `com.example.MVCApplicationKt.module` on port `8080` with an H2 file database at `./build/db`. There is no `src/test` directory.

`plugins/Routing.kt` installs `StatusPages` and one `route("wish")` block: `post("make")` reads the `wish` field with `receiveParameters()` and redirects to `/wish/list`, `get("list")` renders `wishlist.ftl`, `post("cancel")` reads `id` and deletes the row, and `get("topwishes")` renders the other template. `wishlist.ftl` holds the two forms, `action="make"` and `action="cancel"`, both `method="post"` with no token and no header. Nothing checks where a submission came from, so a page on another site can post a wish or cancel one by id on behalf of anyone who opens it.

Ktor ships the plugin as `io.ktor:ktor-server-csrf`, in `io.ktor.server.plugins.csrf`, so the agent adds that one artifact and installs it in a new `plugins/Security.kt` called from `MVCApplication.kt`. `originMatchesHost()` requires the host in the `Origin` header to match the `Host` header, which fits the sample's direct Netty listener; `allowOrigin` entries come from a new `ktor.application.allowedOrigins` list in `application.yaml`, read with `environment.config`, so a deployment behind a proxy can name its public origin without a code change. `onFailure` replaces the default `400` plus message with a logged line and a plain `403`. Browsers send `Origin` on form posts, so the two forms in `wishlist.ftl` do not change; the pull request notes that `checkHeader` is available if a JavaScript client is added later.

Then the agent writes `src/test/kotlin/com/example/CsrfTest.kt` with `testApplication` from `ktor-server-test-host`, which picks up `application.yaml` from the classpath, and `kotlin-test-junit` assertions. The cases: a `POST /wish/make` with `Origin: http://localhost:8080` and a form body answers the `302` redirect to `/wish/list` the route already sends; the same post with `Origin: https://evil.example` answers `403`; the same post with no `Origin` header answers `403`; and `GET /wish/list` with no `Origin` still answers `200`, which the agent keeps true by scoping the plugin so reads stay open. It runs `./gradlew test` in the sandbox and pastes the task output in the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add CSRF protection to this Ktor application and open a pull request. Read build.gradle.kts, gradle.properties, src/main/resources/application.yaml, src/main/kotlin/com/example/MVCApplication.kt, plugins/Routing.kt, plugins/Templating.kt and both FreeMarker templates first. Add the io.ktor:ktor-server-csrf artifact at the Ktor version the plugin block already uses and install CSRF in a new plugins/Security.kt: originMatchesHost, allowOrigin for each entry of a new ktor.application.allowedOrigins list in application.yaml, and onFailure that logs and answers 403. Keep the two forms in wishlist.ftl unchanged and keep GET routes open. Create src/test/kotlin with testApplication cases: POST /wish/make with Origin http://localhost:8080 and a form body answers 302 to /wish/list, the same with Origin https://evil.example answers 403, the same with no Origin answers 403, and GET /wish/list with no Origin answers 200. Run ./gradlew test and paste the output in the pull request. Do not change the Exposed models, the H2 datasource or the port.",
  "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 with one dependency line in `build.gradle.kts`, a new `plugins/Security.kt` with the `install(CSRF)` block, a one-line call in `MVCApplication.kt`, a new `allowedOrigins` list in `application.yaml`, and a new `src/test` tree with four cases. The description shows the `403` and the `302` from the test run and the output of `./gradlew test` from the sandbox.

The sample repository has no workflow for this module, so the pasted Gradle output is the check. On a repository with a Gradle workflow the same cases run on the pull request. Because the templates are unchanged, the pages look the same; the difference is only visible to a request without a matching `Origin`.

A reviewer checks that `allowedOrigins` carries the public origin exactly as a browser sends it, that `originMatchesHost()` is right for the deployment (it does not work behind a proxy that rewrites `Host`, which the plugin's own documentation says), and that the `403` handler leaks nothing about why. Then they set the list per environment before merging.

## Run it on every security finding on a form

A team with several Ktor services that render forms sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own routes and templates, so a service whose forms already carry a token gets a note instead of a second check, and a JSON API behind bearer tokens gets the explanation that `Origin` checks apply to its browser callers only. Each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `session_url` to read the pull request from, so the allowed-origin lists can be reviewed against each deployment before merging.

## Why run it on Rush?

A CSRF plugin that is configured wrong fails in one of two quiet ways: it blocks your own forms in production because the origin string is off by a scheme or a port, or it blocks nothing because the check is scoped to the wrong routes. In a Rush sandbox the agent sends the real form posts through `testApplication` with and without an `Origin`, and the `302` and `403` responses are kept in the run's record beside the Gradle output, so the pull request shows both outcomes.

The code is a few lines; the work is reading the routes, deciding what stays open, and writing the test tree a sample without one needs. The agent does that in one pass, runs Gradle with the JDK 17 toolchain the build declares, and the same request works unchanged on the next Ktor service.

## Frequently asked questions

### Do the forms need a hidden token?

Not for this plugin. Ktor's CSRF plugin checks the `Origin` header against `allowOrigin` entries or the `Host`, and optionally a custom header with `checkHeader`. Browsers send `Origin` on form posts, so `wishlist.ftl` does not change. A token-in-form scheme would be a separate design.

### What if the app runs behind a proxy?

`originMatchesHost()` compares `Origin` with `Host`, and the plugin's documentation says that does not work behind a proxy. That is why the public origin also goes in `allowedOrigins` in `application.yaml`, so the check passes on the proxied host without a code change.

### Why 403 instead of the default?

The plugin's default failure answers `400` with the error text. The `onFailure` handler logs the reason and answers a plain `403`, which the plugin's documentation recommends so the message does not describe the check to the caller.

### Will GET pages still open?

Yes. The test suite includes `GET /wish/list` with no `Origin` expecting `200`, and the agent scopes the plugin so that case passes. Reads are not what the check protects.

## More Ktor jobs

- [Add Cursor Pagination to a Ktor API](https://getrush.ai/run/add-cursor-pagination/ktor/)
- [Add Flyway Migrations to a Ktor App](https://getrush.ai/run/add-flyway-migrations/ktor/)
- [Add Graceful Shutdown to a Ktor Server](https://getrush.ai/run/add-graceful-shutdown/ktor/)

## The same job on other stacks

- [Add CSRF Protection to a Litestar App](https://getrush.ai/run/add-csrf-protection/litestar/)
- [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/)

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