# Add Security Headers to a CodeIgniter 4 App

Yes. An agent enables CodeIgniter's secureheaders filter, adds the HSTS and Permissions-Policy it lacks, turns on the nonce CSP, tests each header and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/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 configuration first, because CodeIgniter 4 ships most of this job switched off rather than missing. In an app laid out like codeigniter4/appstarter, `composer.json` requires PHP `^8.2` and `codeigniter4/framework` `^4.7` with `phpunit/phpunit` `^10.5.16` for tests, and `app/Config/Filters.php` already maps the alias `secureheaders` to `CodeIgniter\Filters\SecureHeaders` beside `csrf`, `honeypot`, `invalidchars`, `cors` and `forcehttps`. Its `$globals['after']` list has `'secureheaders'` present but commented out, and `$required` runs `forcehttps` and `pagecache` before every request and `pagecache`, `performance` and `toolbar` after. `app/Config/App.php` has `$forceGlobalSecureRequests = false` and `$CSPEnabled = false`, and the `env` template repeats both as commented lines. `app/Config/Routes.php` has one route, `GET /` to `Home::index`, which renders `app/Views/welcome_message.php`.

Then it reads what the framework's filter sends, in `system/Filters/SecureHeaders.php` of the installed framework: `X-Frame-Options: SAMEORIGIN`, `X-Content-Type-Options: nosniff`, `X-Download-Options: noopen`, `X-Permitted-Cross-Domain-Policies: none` and `Referrer-Policy: same-origin`, with `X-XSS-Protection` left commented out on purpose. Nothing there sets `Strict-Transport-Security`, and the `forcehttps` filter does not fill the gap: its `force_https()` helper in `system/Common.php` returns early when the request is already secure and sets the HSTS header only on the `307` redirect it sends to an insecure one, so a browser that already uses HTTPS never receives it. There is no `Permissions-Policy` either. Those two are the headers the agent has to write itself.

The change is small and lands in four files. `app/Config/Filters.php` gets `'secureheaders'` uncommented in `$globals['after']`, with the alias pointed at a new `App\Filters\SecureHeaders` that extends the framework's class and adds `Permissions-Policy: camera=(), microphone=(), geolocation=()` and `Cross-Origin-Opener-Policy: same-origin` to the inherited `$headers`, and sets `Strict-Transport-Security: max-age=31536000; includeSubDomains` in `after()` only when `$request->isSecure()` is true, so a `localhost:8080` developer never pins HTTPS on their browser. `app/Config/App.php` flips `$CSPEnabled` to `true`; `app/Config/ContentSecurityPolicy.php` already defaults `scriptSrc`, `styleSrc`, `imageSrc` and `objectSrc` to `self` with `autoNonce` on, and the agent sets `frameAncestors` to `self` to match `X-Frame-Options` and leaves `reportOnly` false because `welcome_message.php` already carries `{csp-style-nonce}` on its `<style>` block and `{csp-script-nonce}` on its one inline `<script>`, so the page renders with no console violation. `app/Config/Cookie.php` keeps `httponly` true and `samesite` `Lax`; the agent leaves `$secure` false and says why in the pull request, since flipping it breaks cookies on plain HTTP in development.

The test goes in `tests/unit/SecureHeadersTest.php` beside the existing `HealthTest.php`, as a `CIUnitTestCase` using `FeatureTestTrait`: `$this->get('/')` then `assertOK()`, `assertHeader('X-Frame-Options', 'SAMEORIGIN')`, `assertHeader('X-Content-Type-Options', 'nosniff')`, `assertHeader('Permissions-Policy', ...)` and `assertHeaderMissing('Strict-Transport-Security')` on the plain request, a second call with `$_SERVER['HTTPS']` set to `on` that asserts the HSTS value, and an assertion that `Content-Security-Policy` names `script-src 'self' 'nonce-` for the rendered page. The agent runs `composer test` the way `.github/workflows/phpunit.yml` does on its PHP 8.2 and 8.5 matrix, then `php spark serve` and `curl -sI localhost:8080/` to capture the real response headers, once with the default `env` and once with `CI_ENVIRONMENT = production` so the `toolbar` filter is out of the picture.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add security headers to this CodeIgniter 4 app. Read composer.json, app/Config/Filters.php, app/Config/App.php, app/Config/ContentSecurityPolicy.php, app/Config/Cookie.php, app/Views/welcome_message.php, tests/unit/HealthTest.php, phpunit.dist.xml and .github/workflows/phpunit.yml first, and read the framework's SecureHeaders filter and force_https helper in vendor to see which headers they do and do not send. Enable the secureheaders filter globally after every request through an app filter that extends the framework's and adds Permissions-Policy, Cross-Origin-Opener-Policy and a Strict-Transport-Security header sent only on secure requests. Enable the Content Security Policy with frame-ancestors matching X-Frame-Options and keep the existing nonce tags working in the welcome view. Leave Cookie secure as it is and say why. Add a feature test that asserts each header on GET / over plain HTTP and the HSTS header with HTTPS on. Run phpunit, start spark serve and curl -I the home page in development and production, then open a pull request listing every header with its value.",
  "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` for the uncommented global and the re-pointed alias, `app/Config/App.php` for `$CSPEnabled`, `app/Config/ContentSecurityPolicy.php` for `frameAncestors`, and adds `app/Filters/SecureHeaders.php` and `tests/unit/SecureHeadersTest.php`. The description lists every header the home page now sends with its value, pasted from the `curl -sI` output in development and in production, and the `phpunit --coverage-text` lines for the new test.

The `PHPUnit` workflow runs on the pull request on PHP 8.2 and 8.5, so a reviewer sees the same assertions pass on both. The run's record keeps the `vendor` reads that justified writing HSTS by hand, the two `spark serve` sessions and each `curl`, so a reviewer can check a header's value against the command that produced it.

Before merging, a reviewer decides the HSTS `max-age` and whether `includeSubDomains` fits their domains, whether `Permissions-Policy` should deny more features, and whether `reportOnly` should be on for the first deploy if other views carry inline scripts without the nonce tag. The agent changes no controller and no route.

## Run it on every CodeIgniter repository without secure headers

A team with several CodeIgniter 4 services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with the 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 `Filters.php`, so a service that already lists `secureheaders` gets only the HSTS and CSP parts, and one whose views have inline scripts without `{csp-script-nonce}` gets `reportOnly` set to `true` and a list of the views to fix.

After that, an automation in the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a view with an inline script or style, check it carries the CSP nonce tag and does not loosen app/Config/ContentSecurityPolicy.php, and say so in a comment" keeps the policy honest. The trigger adds the pull request after the prompt and fires only for work by owners, members and collaborators.

## Why run it on Rush?

Security headers are easy to claim and easy to get wrong without a running app: a `secureheaders` line uncommented in the wrong list runs before the response exists, an HSTS header set on `localhost` pins a developer's browser to HTTPS for a year, and a CSP enabled with `autoNonce` silently blocks any inline script that lacks the tag. The agent reads the framework's own filter and helper in `vendor`, starts the real server in its sandbox and reads the real headers before it opens the pull request.

Every command stays with the run, from the `vendor` reads to each `curl -sI`, and the pull request quotes them. Doing the same for a dozen CodeIgniter apps at once costs no more attention than one, because each run has its own machine, its own record and its own pull request.

## Frequently asked questions

### Why write Strict-Transport-Security by hand when the framework has a forcehttps filter?

Because `force_https()` only sets that header on the `307` redirect it sends to an insecure request, and returns before setting anything when the request is already HTTPS. A browser that always arrives over HTTPS therefore never sees it. The app filter sends it on every secure response and skips plain HTTP, which is what the HSTS specification asks for anyway.

### Will the Content Security Policy break my existing views?

Only views with inline scripts or styles that lack the nonce tags. The config has `autoNonce` on, so a `<script {csp-script-nonce}>` block is allowed and one without the tag is blocked; `welcome_message.php` already uses both tags. The agent greps every file under `app/Views` for inline blocks and reports any without a tag, and a team that has many can start with `reportOnly` set to `true` and read the browser's violation reports first.

### Does the test really exercise the headers, or just the config?

It sends requests through `FeatureTestTrait`, which runs the full filter chain and returns a `TestResponse`, so `assertHeader` reads what a browser would receive. The HTTPS case sets the server variable the request reads in `isSecure()`, so the HSTS branch runs in the test too. The `curl -sI` output in the pull request is the second proof, against the real server.

### Why is Cookie secure left false?

Because `app/Config/Cookie.php` applies to every cookie including the session, and with `$secure` true a session cookie is never set over the `http://localhost:8080/` base URL the starter uses, which breaks local development. The pull request names the line and recommends setting it in the production `.env` instead, where the site is HTTPS only.

## More CodeIgniter jobs

- [Add Database Seeders to a CodeIgniter 4 App](https://getrush.ai/run/add-seed-data/codeigniter/)
- [Add User Registration to a CodeIgniter App](https://getrush.ai/run/add-user-registration/codeigniter/)
- [Write PHPUnit Tests for a CodeIgniter 4 App](https://getrush.ai/run/write-phpunit-tests/codeigniter/)

## The same job on other stacks

- [Add Security Headers to a Django REST Framework API](https://getrush.ai/run/add-security-headers/django-rest-framework/)
- [Add Security Headers to an Echo API](https://getrush.ai/run/add-security-headers/echo/)
- [Add Security Headers and a CSP to an Eleventy Site](https://getrush.ai/run/add-security-headers/eleventy/)

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