# Add CSRF Protection to a Fiber App

Yes. An agent adds Fiber v3's csrf middleware to your app, hands the token to the page, sends it from the fetch call, tests the 403 and the success, and opens a PR.

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

## What the agent does

The agent reads how requests reach the app first. In a service laid out like gofiber/boilerplate, `go.mod` targets Go 1.26 with `github.com/gofiber/fiber/v3` v3.6.1 and `github.com/gofiber/utils/v2`; `app.go` builds the app in `main()` with `recover` and `logger`, a `/api/v1` group with `GET /users` and `POST /users`, `static.New("./static/public")` for everything else, a `NotFound` handler, and `app.Listen` with `EnablePrefork` behind the `-prod` flag. `handlers/handlers.go` reads `c.FormValue("user")` into an in-memory slice guarded by a mutex in `database/database.go`, and `static/public/js/app.js` posts that form with `fetch` and `FormData` to `/api/v1/users`. There are no `_test.go` files; `.github/workflows/test.yml` runs `go test ./... -v -race` on Go 1.26 and 1.27 on Linux and Windows runners, and `lint.yml` runs golangci-lint v2.14 through gofiber's shared workflow with the `modernize` linter enabled in `.golangci.yml`.

Fiber v3 ships the middleware in `github.com/gofiber/fiber/v3/middleware/csrf`, with token extraction in the `extractors` package. Its defaults are the ones the agent keeps: a cookie named `csrf_` with `SameSite=Lax`, a token from `utils.SecureToken`, and `extractors.FromHeader("X-Csrf-Token")` as the place the token must come back in. Safe methods (`GET`, `HEAD`, `OPTIONS`, `TRACE`, `QUERY`) pass untouched; every other method without a matching token is answered `403` by the default `ErrorHandler`. The agent sets `CookieSessionOnly: true` and `CookieHTTPOnly: true`, which is safe because the page never reads the cookie, and does not point the extractor at the cookie: the middleware panics at startup if the extractor reads the same cookie it sets, which is the double-submit mistake it exists to prevent.

The page needs the token, so the agent adds `GET /api/v1/csrf` returning `{"token": csrf.TokenFromContext(c)}`, registers `csrf.New(...)` on the app before the group so the `GET` issues the cookie, and changes `app.js` to fetch that route once on `DOMContentLoaded` and send the value as `X-Csrf-Token` on the `POST`. One thing in this app needs saying in the pull request: with no `Session` store the middleware runs in double-submit mode and keeps issued tokens in `Storage`, which defaults to in-memory, and with `-prod` the app preforks, so a token issued by one child process is unknown to the next. The agent writes that down, points at a shared `fiber.Storage` implementation as the fix for prefork, and mentions `csrf.NewCrossOriginProtection`, the tokenless middleware that checks `Sec-Fetch-Site` and `Origin` and needs no storage at all, as the alternative for an API that only browsers on the same origin call.

To test it the agent moves the app construction out of `main()` into a `newApp()` function and adds `app_test.go`: a `POST /api/v1/users` with no header is `403`; a `GET /api/v1/csrf` followed by a `POST` carrying the returned token and the `csrf_` cookie is `200` with `"success": true`; a `GET /` is still served from `static/public`. It runs `go build ./...`, `go test ./... -v -race` and `golangci-lint run` with the repository's config (the `modernize` linter rejects a `for i := 0; i < n` loop that could be a range, so the test is written the way the linter wants), then opens 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 this Fiber v3 app. Read go.mod, app.go, handlers/handlers.go, database/database.go, static/public/index.html, static/public/js/app.js, .golangci.yml and .github/workflows/test.yml first. Register github.com/gofiber/fiber/v3/middleware/csrf before the /api/v1 group with the default cookie name, SameSite and X-Csrf-Token header extractor, CookieSessionOnly and CookieHTTPOnly set, and no extractor that reads the cookie. Add GET /api/v1/csrf returning the token from csrf.TokenFromContext, and change app.js to fetch it once and send it as X-Csrf-Token on the POST. Move app construction into a newApp function and add app_test.go covering the 403 without a token, the 200 with the token and cookie from the csrf route, and that static files still serve. Run go build ./..., go test ./... -v -race and golangci-lint run until they pass. In the pull request explain that in-memory Storage does not work across prefork workers and name a shared Storage and csrf.NewCrossOriginProtection as the two ways around 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

The pull request changes `app.go`, `handlers/handlers.go` and `static/public/js/app.js`, and adds `app_test.go`. Its description shows the middleware configuration with a line on each field it set and why the extractor reads a header rather than the cookie, quotes the `go test -v -race` output from the sandbox, and includes the prefork note with the two alternatives.

A reviewer checks the order of registration (the middleware must run before the group and before the static handler issues anything), decides whether the app's deployment preforks and therefore needs a shared `Storage` or the tokenless `NewCrossOriginProtection`, and confirms that any non-browser client of `POST /api/v1/users` is either moved to a safe method or given a way to fetch the token first.

Nothing changes for `GET` requests, so the page and its assets load as before; a `POST` from another origin, or a replayed one without the token, now gets `403` with the default error body.

## Run it on every Linear issue labelled security

An automation on the Project with a `linear` trigger on `linear.issue.labeled`, `security` in `config.labels`, and the prompt "this issue names a Fiber route or form that must be protected against cross-site requests; add or extend the csrf middleware configuration and the token hand-off for it, extend app_test.go, and open a pull request" starts one run per labelled issue once the middleware is in place. The trigger adds the issue after the prompt and fills in no placeholder, so a new admin form and a new JSON endpoint called from the page are handled by the same mechanism, each from the issue that describes it.

A team with several Fiber services sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that 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. Each run reads its own app: a service that already uses `middleware/session` gets the `Session` store wired into the config, which turns the middleware into synchronizer-token mode, and one with server-rendered templates gets the token in a hidden form field through `extractors.FromForm` instead of a fetch.

## Why run it on Rush?

CSRF middleware is easy to install and easy to install wrong: an extractor that reads the cookie it sets (which Fiber now refuses at startup), a token route that is itself protected, a static handler that runs before the middleware, or an in-memory token store behind preforked workers that only fails in production. The agent runs the app in its own sandbox, drives the real routes with and without the token, and keeps the test output and the linter run with the pull request.

A reviewer reads the configuration with a reason beside each field rather than a bare `csrf.New()`, and the prefork caveat is written down before it is discovered. A team with many Go services starts the same request across all of them at once.

## Frequently asked questions

### Does the page need to read the cookie?

No. The token comes from `GET /api/v1/csrf`, which calls `csrf.TokenFromContext`, and goes back in the `X-Csrf-Token` header. The cookie is `HttpOnly` and only ties the browser to the issued token. Configuring an extractor that reads the cookie would defeat the double-submit check, and Fiber v3 panics at startup if you try.

### What about the -prod prefork flag?

With the default in-memory `Storage`, each preforked child keeps its own set of issued tokens, so a token from one child is invalid at another. The pull request names two fixes: a shared `fiber.Storage` such as a Redis store from gofiber/storage, or `csrf.NewCrossOriginProtection`, which checks `Sec-Fetch-Site` and `Origin` and keeps no state.

### Will curl and other non-browser clients break?

Only on unsafe methods. A `POST /api/v1/users` from a script now needs the token and cookie from `GET /api/v1/csrf` first, which the test shows how to do. If the endpoint is meant for scripts rather than the page, the pull request suggests `Next` in the config to skip the middleware for a token-authenticated path.

### Is this the synchronizer-token pattern or double-submit?

Without a `Session` store it is double-submit with server-side tracking of issued tokens, which is Fiber's default. Passing a `session.Store` in `Session` switches it to the synchronizer-token pattern, and an app that already has sessions gets that configuration instead.

## More Fiber jobs

- [Add govulncheck to CI for a Fiber Multi-Module Repository](https://getrush.ai/run/add-govulncheck-to-ci/fiber/)
- [Add Graceful Shutdown to a Fiber App](https://getrush.ai/run/add-graceful-shutdown/fiber/)
- [Add Health Checks to a Fiber API](https://getrush.ai/run/add-health-checks/fiber/)

## The same job on other stacks

- [Add CSRF Protection to a Hono App with Cookie Sessions](https://getrush.ai/run/add-csrf-protection/hono/)
- [Add CSRF Protection to an htmx App](https://getrush.ai/run/add-csrf-protection/htmx/)
- [Add CSRF Protection to Ktor Form Posts](https://getrush.ai/run/add-csrf-protection/ktor/)

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