# Add Security Headers to a Vapor App

Yes. An agent adds a Vapor middleware setting nosniff, frame, referrer, CSP and cache headers on every response, with HSTS behind a flag, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/vapor/). 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 configured before it writes a middleware. In a project shaped like vapor/template-fluent-postgres, `Package.swift` uses `swift-tools-version:6.3` and depends on `vapor` from 4.121.4, `fluent` 4.13.0, `fluent-postgres-driver` 2.12.0 and `swift-nio` 2.101.0, with the upcoming features `ExistentialAny`, `InternalImportsByDefault`, `MemberImportVisibility`, `InferIsolatedConformances` and `ImmutableWeakCaptures` turned on for both targets. `Sources/TemplateFluentPostgres/configure.swift` reads `DATABASE_HOST`, `DATABASE_PORT`, `DATABASE_USERNAME`, `DATABASE_PASSWORD` and `DATABASE_NAME` through `Environment.get`, registers `CreateTodo`, and leaves `FileMiddleware` commented out. `routes.swift` answers `/` and `/hello` and mounts `TodoController`, whose `GET /todos`, `POST /todos` and `DELETE /todos/:todoID` return JSON through `TodoDTO`. `entrypoint.swift` bootstraps logging from the environment and calls `app.execute()`. The `Dockerfile` builds a static binary on `swift:6.3-noble`, runs it on `ubuntu:noble` as the `vapor` user, and `docker-compose.yml` starts it with `serve --env production --hostname 0.0.0.0 --port 8080` beside a `postgres:18-alpine` service. Nothing terminates TLS, so HSTS is a deployment question, not a default.

It writes `Sources/TemplateFluentPostgres/Middleware/SecurityHeadersMiddleware.swift`, a struct conforming to `AsyncMiddleware` whose `respond(to:chainingTo:)` awaits the next responder and then sets `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, a `Content-Security-Policy` of `default-src 'none'; frame-ancestors 'none'`, which fits an API with no HTML, and `Cache-Control: no-store`, each only when the route has not already set it, using `response.headers.contains(name:)`. Because the `MemberImportVisibility` feature is on, the file imports `Vapor` and nothing else it does not use. `Strict-Transport-Security` is handled apart: the middleware reads `HSTS_MAX_AGE` the way `configure.swift` reads `DATABASE_HOST`, and sends the header only when that variable is set and the request arrived over TLS or carries `X-Forwarded-Proto: https`, so a plain `swift run` on port 8080 never sends it.

The registration order is the detail that matters. `configure.swift` gains `app.middleware.use(SecurityHeadersMiddleware(), at: .beginning)`. Vapor's default chain already holds `ErrorMiddleware`, which builds the response for a thrown `Abort`; a middleware appended with plain `use` sits inside it and never sees that response, so the `404` from `TodoController.delete` for an unknown id would go out bare. Placed at the beginning, the middleware wraps the error handler and the `404` carries the same headers as a `200`. The new variable is documented in `docker-compose.yml` under `x-shared_environment`, commented out beside `LOG_LEVEL`.

Tests join `Tests/TemplateFluentPostgresTests/TemplateFluentPostgresTests.swift`, which uses Swift Testing with a `@Suite("App Tests with DB", .serialized)` and a `withApp` helper that configures the app, runs `autoMigrate`, and reverts after each test. New cases call `app.testing().test(.GET, "hello")` and assert each header, request `DELETE /todos/<random UUID>` and assert the `404` carries them, check that `Strict-Transport-Security` is absent by default and present with `HSTS_MAX_AGE` set and `X-Forwarded-Proto: https` sent, and that a route that sets its own `Cache-Control` keeps it. The suite needs the Postgres from `docker-compose.yml`, so the agent starts that service, exports the `DATABASE_*` variables, and runs `swift build` and `swift test` as the `README.md` describes, then starts the server and keeps a `curl -i http://localhost:8080/hello` for the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add security response headers to this Vapor app and open a pull request. Read Package.swift, Sources/*/configure.swift, routes.swift, entrypoint.swift, Controllers/TodoController.swift, the test target, Dockerfile and docker-compose.yml first. Write a Middleware/SecurityHeadersMiddleware.swift conforming to AsyncMiddleware that sets X-Content-Type-Options nosniff, X-Frame-Options DENY, Referrer-Policy no-referrer, Content-Security-Policy default-src 'none'; frame-ancestors 'none', and Cache-Control no-store, each only when the response does not already carry it. Read HSTS_MAX_AGE from the environment and send Strict-Transport-Security only when it is set and the request is TLS or carries X-Forwarded-Proto https. Register it in configure.swift with at: .beginning so responses built by ErrorMiddleware carry the headers too, and document HSTS_MAX_AGE in docker-compose.yml. Add Swift Testing cases in the existing suite covering every header on GET /hello, the headers on a 404 from DELETE /todos/<unknown id>, HSTS off by default and on with the variable and header, and a route's own Cache-Control being kept. Start the Postgres service from docker-compose.yml, run swift build and swift test, start the server and paste a curl -i response for /hello and the test output in the pull request. Do not change any route or the Todo model.",
  "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 one file under `Sources/TemplateFluentPostgres/Middleware`, one `app.middleware.use` line to `configure.swift`, a commented variable to `docker-compose.yml`, and new `@Test` cases to the existing suite. The description shows a `curl -i` of `/hello` with the five headers and no `Strict-Transport-Security`, a second with `HSTS_MAX_AGE` set behind a forwarded-proto header, and the `swift test` summary.

This template ships no GitHub Actions workflow, so the pull request has no checks of its own; the test output in the description is the evidence. A reviewer who wants a check can ask the next run to add a workflow that runs `swift test` with a Postgres service, in the same shape the compose file already uses.

A reviewer checks that the `Content-Security-Policy` is right for a service that returns JSON only, that `Cache-Control: no-store` suits whoever calls `GET /todos`, that HSTS stays off for the plain `:8080` listener, and that the middleware sits at the beginning of the chain. Then they set `HSTS_MAX_AGE` in the deployment that has TLS in front of it.

## Run it on every new Vapor service

A team that runs several Vapor services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `configure.swift` and middleware chain, so a service that renders Leaf templates gets a policy that allows its own scripts and styles instead of `default-src 'none'`, and each opens its own pull request with its own tests.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so a handler on your server can post the link where that service's owners review.

## Why run it on Rush?

Headers are cheap to add and easy to add in the wrong place: a middleware appended after Vapor's defaults never touches the `404` and `500` responses that `ErrorMiddleware` builds, and HSTS from a plain-HTTP binary breaks every local run. In a Rush sandbox the agent builds the real binary with the Swift 6.3 toolchain, starts it, fetches a route with `curl -i`, and keeps that output in the run's record, so the pull request shows the exact header block the proxy will pass through.

A Swift server build is slow on a laptop and the test suite wants a Postgres beside it. Each run on Rush does the build and the database in its own sandbox and parks when the turn ends, and the same request body works on every Vapor service a team owns.

## Frequently asked questions

### Why at: .beginning instead of a plain use?

Vapor's default middleware includes `ErrorMiddleware`, which turns a thrown `Abort` into a response. A middleware added with `use` runs inside it and only sees responses that routes return, so a `404` would leave without headers. At the beginning, the middleware wraps the error handler and every response passes through it.

### Will HSTS break local development?

No. The header is sent only when `HSTS_MAX_AGE` is set and the request arrived over TLS or with `X-Forwarded-Proto: https`. A `curl http://localhost:8080` never receives it, and a test asserts that.

### Does the test suite need Docker?

It needs a Postgres, because `withApp` runs `autoMigrate` against `app.db`. The compose file's `db` service is the easiest source, and the agent starts it in the sandbox; any Postgres reachable through the `DATABASE_*` variables works the same.

### What if a route serves HTML later?

The policy is per response. A route that sets its own `Content-Security-Policy` keeps it, because the middleware only fills headers that are absent, and the pull request notes that a Leaf-rendered page needs a policy with `script-src` and `style-src` entries.

## More Vapor jobs

- [Add Seed Data to a Vapor App](https://getrush.ai/run/add-seed-data/vapor/)
- [Add Soft Delete to a Vapor App](https://getrush.ai/run/add-soft-delete/vapor/)
- [Add Structured JSON Logging to a Vapor App](https://getrush.ai/run/add-structured-logging/vapor/)

## The same job on other stacks

- [Add Security Headers to a Wagtail Site from a Linear Issue](https://getrush.ai/run/add-security-headers/wagtail/)
- [Add Security Headers to an Actix Web App](https://getrush.ai/run/add-security-headers/actix/)
- [Add Security Headers to an aiohttp App](https://getrush.ai/run/add-security-headers/aiohttp/)

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