# Add Security Headers to an aiohttp App

Yes. An agent adds a security-headers middleware to your aiohttp app with a CSP fitted to your templates, covers redirects and error pages, tests it and opens a PR.

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

## What the agent does

In an app like the polls demo in aio-libs/aiohttp-demos, the agent reads `aiohttpdemo_polls/main.py`: `init_app` creates `web.Application()`, sets up `aiohttp_jinja2` with a `PackageLoader` for `templates/`, appends `pg_context` to `cleanup_ctx`, registers the routes from `routes.py` (`GET /`, `GET /poll/{question_id}`, `GET /poll/{question_id}/results`, `POST /poll/{question_id}/vote`) and a static route at `/static/`, and calls `setup_middlewares`, which appends one error middleware from `middlewares.py` that renders `404.html` and `500.html` for those statuses. `web.run_app` listens on the `host` and `port` from `config/polls.yaml`, `127.0.0.1:8080`, so TLS, if any, ends at a proxy in front. The templates are the input to the policy: `base.html` links `style.css` through `url('static', filename='style.css')` and has no inline script or style, `detail.html` posts a form to the vote route, `results.html` links back. `views.vote` ends with `raise web.HTTPFound`, and `poll` and `results` raise `HTTPNotFound`. `requirements-dev.txt` pins `aiohttp==3.13.5`, `aiohttp-jinja2==1.6`, `pytest==9.1.1` and `pytest-aiohttp==1.1.1`; `pytest.ini` sets `asyncio_mode = auto` and `filterwarnings = error`; `tests/test_integration.py` runs against Postgres through the `cli` fixture in `conftest.py`, and the repository's `ci.yml` provides that database as a service and runs `make lint` and `make test`.

The agent adds `security_headers_middleware` to `middlewares.py` as a `@web.middleware` coroutine. The policy is derived from what the templates load: `default-src 'self'`, `script-src 'self'`, `style-src 'self'`, `img-src 'self' data:`, `form-action 'self'` because the vote form posts to the same origin, `frame-ancestors 'none'`, `base-uri 'self'` and `object-src 'none'`. Beside it go `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy: camera=(), microphone=(), geolocation=()` and `Cross-Origin-Opener-Policy: same-origin`. `Strict-Transport-Security` is set only when a new `https` key in `polls.yaml`, added to the trafaret in `utils.py` with a default of false, says the app is served over TLS, since sending HSTS from a plain-HTTP host would be wrong and the demo listens on plain HTTP. Every header is applied with `setdefault`, so a handler that sets its own policy wins.

Two aiohttp details decide whether the headers reach every response. First, a handler that ends with `raise web.HTTPFound` or `HTTPNotFound` raises out of `await handler(request)`, so the middleware catches `web.HTTPException`, writes the headers onto `ex.headers` and re-raises; otherwise the redirect after a vote and the 404 pages would go out bare. Second, middleware order: `setup_middlewares` appends the error middleware, and the agent inserts the security middleware at index 0 so it is outermost and wraps the 404 and 500 pages the error middleware renders as well as the `FileResponse` objects the static route returns. The debug toolbar that `get_app` adds for `aiohttp-devtools` injects inline scripts, so the pull request says that under the toolbar `script-src` needs relaxing, and shows the one-line override for development.

The tests come in two layers so the headers can be checked without a database. `tests/test_security_headers.py` builds a bare `web.Application()` with the middleware, a handler that returns 200, one that raises `HTTPFound` and one that raises `HTTPNotFound`, and asserts every header on each through `aiohttp_client`; one more case on the `cli` fixture checks `/`, `/no-such-route`, which the error middleware renders as a page, and `/static/style.css`. Under `filterwarnings = error` any deprecation from the new code fails the run, which is the point of keeping it. The agent runs `flake8 aiohttpdemo_polls` and `pytest tests` in its sandbox; the integration cases need the Postgres that `init_db.py` expects at `localhost:5432` with the `postgres` superuser, and with no Docker in the sandbox it installs PostgreSQL from apt, sets that password and runs the suite as `ci.yml` does.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add security headers to the polls app in this aiohttp repository. Read aiohttpdemo_polls/main.py, middlewares.py, routes.py, views.py, settings.py, utils.py, every template under aiohttpdemo_polls/templates, config/polls.yaml, tests/conftest.py, pytest.ini, requirements-dev.txt and the repository's CI workflow first. Write a middleware that sets a Content-Security-Policy derived from what the templates actually load, plus X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy and Cross-Origin-Opener-Policy, with Strict-Transport-Security only behind a config flag that says the app is served over TLS. Make sure responses produced by raising HTTPException, the error pages and static files get the headers too, and register the middleware outermost. Add tests on a bare application and on the real one. Run flake8 and the test suite, and open a pull request with the 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

The pull request changes `aiohttpdemo_polls/middlewares.py`, `aiohttpdemo_polls/utils.py`, `config/polls.yaml` and `config/polls_test.yaml`, and adds `tests/test_security_headers.py`. Its description shows the policy line by line with the template or route that justifies each directive, the response headers of `/`, of the redirect after a vote and of the 404 page, and the flake8 and pytest output.

The `CI` workflow runs on the pull request with its `lint` and `test` jobs, the latter against the Postgres and Redis services it already defines, so a reviewer sees the new tests pass beside the existing integration tests. The run's record keeps the sandbox suite and the `curl -i` output for each route.

Before merging, a reviewer decides whether the vote form will ever post across origins, which would loosen `form-action`, whether `frame-ancestors 'none'` fits any embedding the site needs, and what the `https` flag should be in each deployment. The views, the templates and the database code are unchanged.

## Run it on every aiohttp service without security headers

A team with several aiohttp services sends this body to `POST /o/{org}/sessions` once per repository, each with its own 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 opening a second pull request. Each run derives its policy from its own templates: a service whose pages load a CDN script gets that host in `script-src`, an API with no HTML gets a policy that forbids everything, and a service already behind TLS termination gets the flag set in its config.

After the first pull request, 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 script, stylesheet, image or form to a template, say whether the Content-Security-Policy in middlewares.py still allows it" keeps the policy and the templates in step. The trigger adds the pull request after the prompt, and only work by an owner, member or collaborator fires it.

## Why run it on Rush?

A security-headers middleware is short, but a policy copied from a blog post breaks the site's own stylesheet, and in aiohttp the redirect after a form post and the custom error pages take a different path through the middleware than a normal response. The agent reads the templates to write the policy, reads the handlers to find the raised responses, and requests every route in its own sandbox to show the headers on each.

The header dumps, the flake8 run and the test suite against a real Postgres stay with the run and are quoted in the pull request. Several services get the same treatment at once, each with a policy derived from its own templates rather than one policy pasted into all of them.

## Frequently asked questions

### Why does the middleware catch HTTPException?

Because in aiohttp a handler ends a request by raising `HTTPFound` or `HTTPNotFound`, and that exception leaves `await handler(request)` before any header can be set on a return value. Catching it, writing to its `headers` and re-raising is what puts the headers on the redirect after a vote and on the 404 the error middleware then renders.

### Will the Content-Security-Policy break the pages?

It is written from the templates: one stylesheet from `/static/`, no scripts, no inline styles, one same-origin form. The tests request the index, a poll page and the stylesheet and check the headers; the agent also loads the pages in its sandbox browser and reads the console for policy violations before opening the pull request.

### Why is HSTS behind a flag?

The app listens on plain HTTP on `127.0.0.1:8080` and TLS, if present, ends at a proxy. A browser that receives `Strict-Transport-Security` over HTTP ignores it, and a proxy that already sets it would send it twice, so the header is sent only when the configuration says the app is reached over TLS.

### What about the debug toolbar?

`get_app`, used by `aiohttp-devtools`, adds `aiohttp_debugtoolbar`, which injects inline scripts the policy forbids. The pull request leaves the toolbar in place and shows a relaxed `script-src` for that entry point only, so development keeps the toolbar and production keeps the policy.

## More aiohttp jobs

- [Add Structured Logging to an aiohttp App](https://getrush.ai/run/add-structured-logging/aiohttp/)
- [Add WebSockets to an aiohttp App](https://getrush.ai/run/add-websockets/aiohttp/)
- [Turn Sentry Errors Into Fix Pull Requests for an aiohttp App](https://getrush.ai/run/fix-sentry-errors/aiohttp/)

## The same job on other stacks

- [Add Security Headers to an Axum API](https://getrush.ai/run/add-security-headers/axum/)
- [Add Security Headers to a chi API](https://getrush.ai/run/add-security-headers/chi/)
- [Add Security Headers to a Cloudflare Worker](https://getrush.ai/run/add-security-headers/cloudflare-workers/)

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