# Add CSRF Protection to a CodeIgniter 4 App

Yes. An agent turns on CodeIgniter 4's CSRF filter, hardens the token settings, adds the meta tag for fetch callers, proves the 403 in feature tests, and opens a PR.

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

## What the agent does

The agent reads the filter and security config before changing anything, because CodeIgniter 4 ships CSRF protection switched off rather than missing. In an app started from codeigniter4/appstarter, `composer.json` requires `php` ^8.2 and `codeigniter4/framework` ^4.7 with PHPUnit ^10.5.16, and `app/Config/Filters.php` already maps the alias `csrf` to `CodeIgniter\Filters\CSRF` but lists it commented out under `$globals['before']`, beside `honeypot` and `invalidchars`. `app/Config/Security.php` holds the defaults: `csrfProtection` set to `cookie`, `tokenRandomize` false, `tokenName` and `cookieName` still at `csrf_test_name` and `csrf_cookie_name`, the header `X-CSRF-TOKEN`, a two-hour `expires`, `regenerate` true, and `redirect` true only in production. `app/Config/Routes.php` defines one route, `GET /` to `Home::index`, which renders `app/Views/welcome_message.php`; there is no form and no `POST` route yet, which is the moment to turn the filter on, before one exists without it.

Reading the framework shows what the filter does and does not check. `Security::verify` returns early for anything but `POST`, `PUT`, `DELETE` and `PATCH`; for those it takes the token from the `POST` field named by `tokenName`, then from the `X-CSRF-TOKEN` header, then from a JSON or form-encoded raw body, and throws a `SecurityException` on a mismatch, which the `CSRF` filter turns into a redirect back with an error when `redirect` is on and the request is not AJAX, and into a `403` otherwise. The `form_helper`'s `form_open()` appends `csrf_field()` on its own, and `csrf_meta()` renders the header name and hash as a `<meta>` tag for JavaScript callers. The agent uses all of that rather than writing a token check of its own.

The change is four files. In `Filters.php` the agent uncomments `csrf` in `$globals['before']` and shows the `except` form in a comment for a future `api/*` prefix that takes a bearer token instead. In `Security.php` it sets `tokenRandomize` true, which the framework offers to mask the token against compression attacks, and renames `tokenName` and `cookieName` to `csrf_token` and `csrf_cookie`, since the `_test_name` defaults read like leftovers in a production cookie jar. It leaves `csrfProtection` on `cookie`, because the app has no session configured for CSRF and `app/Config/Cookie.php` already sets `httponly` true and `samesite` Lax, which is the right pair for a cookie-based token. In `welcome_message.php`, as the example layout, it adds `<?= csrf_meta() ?>` in the head and a short note on reading the meta tag into a `fetch` header.

Tests use the framework's feature-test tools so no new dependency is needed. `tests/feature/CsrfFilterTest.php` extends `CIUnitTestCase` with `FeatureTestTrait`, uses `withRoutes` to register a temporary `POST submit` route for the test alone, and makes three calls: a `POST` with no token, expecting a `SecurityException` since `redirect` is false outside production; a `POST` carrying `csrf_token() => csrf_hash()` in its body, expecting `200`; and a JSON `POST` with `withHeaders` setting `X-CSRF-TOKEN` to `csrf_hash()` and `withBodyFormat('json')`, expecting `200`. A fourth call confirms `GET /` still answers `200`, since the filter ignores reads. In the sandbox the agent runs `composer install` and `vendor/bin/phpunit` as `.github/workflows/phpunit.yml` does, starts `php spark serve`, shows `curl` on `/` with the meta tag in the HTML, and 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 CodeIgniter 4 app. Read composer.json, app/Config/Filters.php, app/Config/Security.php, app/Config/Cookie.php, app/Config/Routes.php, app/Controllers/Home.php, app/Views/welcome_message.php, tests/unit/HealthTest.php, phpunit.dist.xml and .github/workflows/phpunit.yml first, and read the framework's Security::verify and the CSRF filter in vendor to confirm which methods and token sources are checked. Enable csrf in $globals before in Filters.php and leave a commented except entry for api/* with a note. In Security.php set tokenRandomize true and rename tokenName to csrf_token and cookieName to csrf_cookie, keeping cookie-based protection, and explain why in the pull request. Add csrf_meta() to the head of welcome_message.php with a short comment on sending X-CSRF-TOKEN from fetch. Add tests/feature/CsrfFilterTest.php using CIUnitTestCase and FeatureTestTrait with a temporary POST submit route from withRoutes, asserting a SecurityException on a POST without a token, 200 with csrf_token() => csrf_hash() in the body, 200 with the X-CSRF-TOKEN header on a JSON body via withBodyFormat('json'), and 200 on GET /. Run composer install and vendor/bin/phpunit, start php spark serve and curl / to show the meta tag, then open a pull request that pastes the test output and the curl excerpt.",
  "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 that changes `app/Config/Filters.php`, `app/Config/Security.php` and `app/Views/welcome_message.php` and adds `tests/feature/CsrfFilterTest.php`. The description lists the four settings that changed and why, quotes the methods `Security::verify` protects and the three places it reads the token from, and pastes the PHPUnit output with the four new cases beside `HealthTest`, plus the `<meta name="X-CSRF-TOKEN">` line from the served home page.

The run's record holds `composer install`, the test run, the `spark serve` start and the request. The routes, the controller and the rest of the configuration are untouched; `Routes.php` still defines one `GET` route, now behind a filter that will cover the first `POST` route anyone adds.

Before merging, a reviewer decides whether any route will take a bearer token or a webhook and needs the `except` entry filled in, whether `expires` of two hours fits the app's forms, and whether to set `redirect` true outside production too, which turns the `403` into a redirect back with a flash error, the behaviour a browser form user expects.

## Run it on every Linear issue labelled security

An automation on the Project with a `linear` trigger on `linear.issue.labeled` filtered to the label `security`, in `exec` mode, with the prompt "read the issue; if it asks for CSRF, filter or security-config hardening in this CodeIgniter app, make the change with feature tests and open a pull request that links the issue" turns the label into the pull request above. The trigger adds the issue after the prompt and needs a Linear connection for the automation's runner; only a change made by someone in your Rush org fires it, never one made by an app integration.

A team with several CodeIgniter apps starts one run per repository from its own server instead: one `POST /o/{org}/sessions` each, 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 rather than a second pull request. Each run reads that app's own `Filters.php`, so an app with an `api/*` group gets the `except` entry filled in rather than commented.

## Why run it on Rush?

The filter is one uncommented line, which is exactly why it is still commented out: nobody wants to be the one who turns it on and breaks a form or a JSON client. The agent reads the framework's `verify` to list which methods and token sources are checked, writes the feature tests that show a bare `POST` refused and a tokened one accepted, and leaves the settings in a state a reviewer can read rather than guess at.

In its own sandbox the agent runs the full PHPUnit suite and a real server, and the run keeps the output for the pull request. For a team with many CodeIgniter apps, each gets its own run and its own pull request with the `except` list read from that app's routes.

## Frequently asked questions

### Will enabling the filter break existing forms?

This app has none, which is why now is cheap. For an app that does, forms built with `form_open()` already include `csrf_field()`, and hand-written forms need the hidden field added. The pull request says which pattern the app uses; a JSON client sends the hash from `csrf_meta()` in the `X-CSRF-TOKEN` header.

### Why cookie-based and not session-based protection?

The app has no session configured for the filter to use, and `app/Config/Cookie.php` already sets `httponly` true and `samesite` Lax, which is the right protection for a token cookie. Switching to `session` later is one setting once the app uses sessions for sign-in.

### What does tokenRandomize change?

The framework masks the token with a random value on each render and unmasks it in `verify`, so the same underlying hash never appears twice in a response body, a defence against compression-based attacks. The helpers `csrf_hash()` and `csrf_field()` return the masked form, so templates need no change.

### Why does the test expect an exception rather than a 403 page?

`redirect` is true only when `ENVIRONMENT` is production, and the test environment is `testing`, so the filter rethrows the `SecurityException` instead of redirecting back, and PHPUnit can assert on it directly. In a browser against a production build the same request becomes a redirect to the previous page with an error message.

## More CodeIgniter jobs

- [Add Database Migrations to a CodeIgniter 4 App](https://getrush.ai/run/add-database-migrations/codeigniter/)
- [Write a Dockerfile for a CodeIgniter 4 App](https://getrush.ai/run/add-dockerfile/codeigniter/)
- [Add File Uploads to a CodeIgniter 4 App](https://getrush.ai/run/add-file-uploads/codeigniter/)

## The same job on other stacks

- [Add CSRF Protection to a Fastify App](https://getrush.ai/run/add-csrf-protection/fastify/)
- [Add CSRF Protection to a Fiber App](https://getrush.ai/run/add-csrf-protection/fiber/)
- [Add CSRF Protection to a Hono App with Cookie Sessions](https://getrush.ai/run/add-csrf-protection/hono/)

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