# Add Security Headers to a Slim 4 App

Yes. An agent adds a PSR-15 middleware to your Slim 4 app that sets a Content Security Policy and the other security headers, tests it, and opens a PR.

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

## What the agent does

The agent reads how the app is wired before adding a middleware, because Slim 4 has no framework-level security headers and the order of middleware decides whether an error page gets them too. In an app started from slimphp/Slim-Skeleton, `composer.json` requires `php` ^7.4 || ^8.0, `slim/slim` ^4.12, `slim/psr7`, `php-di/php-di` ^6.4 and `monolog/monolog`, with PHPUnit ^9.6, phpstan at level 4 over `src` and `phpcs` on PSR-12 for development. `public/index.php` builds the container, adds the middleware from `app/middleware.php`, which registers only `SessionMiddleware`, then the routes from `app/routes.php`, then the routing, body-parsing and error middleware, with `HttpErrorHandler` as the default error handler. `app/routes.php` has a catch-all `OPTIONS` route for CORS preflights, `GET /` writing a hello-world string, and a `/users` group with `ListUsersAction` and `ViewUserAction`, which answer JSON through `ActionPayload`. `app/settings.php` sets `displayErrorDetails` true with a comment to turn it off in production. `tests/TestCase.php` builds the same app in `getAppInstance` and `createRequest` makes PSR-7 requests, so middleware is covered by the existing action tests' path.

The agent writes `src/Application/Middleware/SecurityHeadersMiddleware.php` as a PSR-15 `MiddlewareInterface`, the shape `SessionMiddleware` already uses, which calls the handler and adds headers to the response it gets back. The set is `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`, since the app answers plain text and JSON and nothing it serves runs in a browser, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, `Permissions-Policy` disabling camera, microphone and geolocation, and `Cross-Origin-Resource-Policy: same-origin`. `Strict-Transport-Security` with a one-year `max-age` and `includeSubDomains` is added only when the request's URI scheme is `https` or the request carries `X-Forwarded-Proto: https`, which `php -S` and the `docker-compose.yml` service, both plain HTTP on `8080`, never do, and the pull request says so. The header values live in a `securityHeaders` entry in `app/settings.php` beside the logger settings, so a deployment that later serves a page can widen the policy without touching the class, and the middleware takes them from `SettingsInterface` through the container.

Registration order is the point that a copied snippet gets wrong. Slim runs middleware last-in, first-out, and `public/index.php` adds the error middleware after `app/middleware.php` runs, so error middleware is outermost and a middleware added in `app/middleware.php` sits inside it; a `404` or a `500` produced by `HttpErrorHandler` would then pass back out through the security headers middleware and carry the headers. The agent adds it in `app/middleware.php` after `SessionMiddleware` and confirms in a test that the `404` from `/users/9999` through `ViewUserAction` has them. The catch-all `OPTIONS` route is left as it is, and the pull request notes that it answers every path with an empty `200` and that a real CORS policy is a separate change.

Tests follow the repository's own pattern. `tests/Application/Middleware/SecurityHeadersMiddlewareTest.php` extends `Tests\TestCase`, builds the app with `getAppInstance`, sends `GET /`, `GET /users` and `GET /users/9999` with `createRequest`, and asserts every header on the `200`, the JSON `200` and the `404`, then sends a request whose URI scheme is `https` and one with `X-Forwarded-Proto: https` and asserts the HSTS header on both and its absence on a plain request. In the sandbox the agent runs `composer install`, `composer test`, `vendor/bin/phpstan` and `vendor/bin/phpcs`, as `.github/workflows/tests.yml` does on its analysis job, starts `composer start` and runs `curl -I` on `/` and `/users` and `/users/9999`, and opens the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add security headers to this Slim 4 app. Read composer.json, public/index.php, app/middleware.php, app/routes.php, app/settings.php, app/dependencies.php, src/Application/Middleware/SessionMiddleware.php, src/Application/Handlers/HttpErrorHandler.php, tests/TestCase.php, phpunit.xml, phpstan.neon.dist, phpcs.xml and .github/workflows/tests.yml first. Add src/Application/Middleware/SecurityHeadersMiddleware.php as a PSR-15 middleware that reads its header values from a securityHeaders entry you add to app/settings.php and sets Content-Security-Policy default-src 'none'; frame-ancestors 'none', X-Content-Type-Options nosniff, X-Frame-Options DENY, Referrer-Policy no-referrer, a Permissions-Policy disabling camera, microphone and geolocation, and Cross-Origin-Resource-Policy same-origin on every response, plus Strict-Transport-Security with a one-year max-age and includeSubDomains only when the request scheme is https or X-Forwarded-Proto is https. Register it in app/middleware.php after SessionMiddleware and explain in the pull request why error responses still receive the headers given the order in public/index.php. Leave the OPTIONS catch-all route alone but mention it. Add tests/Application/Middleware/SecurityHeadersMiddlewareTest.php extending Tests\\TestCase that asserts the headers on GET /, GET /users and the 404 from GET /users/9999, and the HSTS header on an https request and a forwarded one but not on a plain one. Run composer install, composer test, vendor/bin/phpstan and vendor/bin/phpcs, start the app with composer start and curl -I the three paths, then open a pull request that pastes the curl output.",
  "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 adds `src/Application/Middleware/SecurityHeadersMiddleware.php` and `tests/Application/Middleware/SecurityHeadersMiddlewareTest.php`, and changes `app/middleware.php` and `app/settings.php`. The description pastes `curl -I` for `/`, `/users` and `/users/9999`, with the policy, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`, `Permissions-Policy` and `Cross-Origin-Resource-Policy` on all three, including the `404`, and a paragraph on why HSTS is absent on a plain `curl` to port `8080`.

The run's record holds `composer install`, the PHPUnit run with the existing action and domain tests plus the new cases, the phpstan and phpcs runs, and the three requests. The actions, the error handler and the routes are untouched; the only wiring change is one line in `app/middleware.php`.

Before merging, a reviewer decides whether the app will ever serve HTML, in which case the policy in `app/settings.php` needs script and style sources, whether `displayErrorDetails` should be turned off at the same time since error pages now carry headers that say the app is an API, and what the `OPTIONS` catch-all should become once a CORS policy is chosen.

## Run it on every new Slim service

A team with several Slim services starts one run per repository from its own server: 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 what that service serves, so a service with Twig views gets a policy written from its templates and a JSON service gets `default-src 'none'`.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a route that returns HTML or a template, check that the securityHeaders policy in app/settings.php allows what the page loads and comment with the directive it needs" keeps the policy and the routes from drifting apart. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

In Slim 4 the headers are easy and the ordering is not: a middleware added in the wrong place leaves every `404` and `500` bare, and that is the response an attacker reads first. The agent reads `public/index.php` to see which middleware is outermost, places the new one so error responses pass through it, and proves it with a test and a `curl` against a running server in its own sandbox rather than reasoning about the stack.

The sandbox keeps the test, phpstan and phpcs runs and the curl headers with the run, and the pull request cites them. For a team with many PHP services, each gets its own run and its own pull request with a policy that matches what that service serves.

## Frequently asked questions

### Why default-src 'none' for the whole app?

Because every route in `app/routes.php` answers plain text or JSON and nothing the app serves runs in a browser, so the tightest policy costs nothing. The values live in `app/settings.php`, so the day the app serves a page the policy is widened in one place and the middleware class stays as it is.

### Do error responses get the headers?

Yes. `public/index.php` adds the error middleware after `app/middleware.php` has run, and Slim wraps later additions around earlier ones, so the error middleware is outermost and the security headers middleware sits inside it. A `404` from `HttpErrorHandler` is created inside the chain and passes back out through the new middleware. The test on `/users/9999` is what shows it.

### Why is HSTS missing when I curl localhost?

The middleware sends it only when the request scheme is `https` or a proxy set `X-Forwarded-Proto: https`, because sending it over plain HTTP is meaningless and the skeleton runs on plain `8080` under both `composer start` and `docker-compose`. Behind a TLS-terminating proxy that sets the forwarded header the line appears, and the test covers both cases.

### What about the OPTIONS catch-all route?

It stays. It answers every path with an empty `200` for CORS preflights, which is a CORS decision, not a header one, and changing it means choosing allowed origins. The pull request names it so the reviewer can schedule that as its own change; the new headers are applied to its responses too.

## More Slim jobs

- [Add Structured Logging to a Slim 4 App](https://getrush.ai/run/add-structured-logging/slim/)
- [Add Twig Templates to a Slim 4 App](https://getrush.ai/run/add-twig-views/slim/)
- [Upgrade PHPUnit in a Slim 4 App](https://getrush.ai/run/upgrade-phpunit/slim/)

## The same job on other stacks

- [Add Security Headers to a SvelteKit App](https://getrush.ai/run/add-security-headers/sveltekit/)
- [Add Security Headers to a Symfony App](https://getrush.ai/run/add-security-headers/symfony/)
- [Add Security Headers With a Traefik Middleware](https://getrush.ai/run/add-security-headers/traefik/)

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