All jobs

Add CSRF Protection to an aiohttp App

Yes. An agent adds an encrypted session and a CSRF token to your aiohttp forms, rejects a POST without the token, tests both paths, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the app before it touches a form. In an app laid out like the demos/polls project in aio-libs/aiohttp-demos, requirements-dev.txt pins aiohttp==3.13.5, aiohttp-jinja2==1.6, asyncpg==0.32.0, SQLalchemy==2.0.54, trafaret_config==2.0.2, pytest==9.1.1 and pytest-aiohttp==1.1.1. aiohttpdemo_polls/main.py builds the web.Application in init_app: the config goes under config_key (a web.AppKey from typedefs.py), aiohttp_jinja2.setup loads templates from the package, app.cleanup_ctx.append(pg_context) opens the async SQLAlchemy engine into app[db_key], then setup_routes, setup_static_routes and setup_middlewares. routes.py registers GET /, GET /poll/{question_id} (poll), GET /poll/{question_id}/results (results) and POST /poll/{question_id}/vote (vote). views.py's vote reads await request.post(), takes data["choice"], calls db.vote and raises HTTPFound to the results page. templates/detail.html renders the form that posts there, with one radio input per choice and nothing else. middlewares.py maps 404 and 500 to templates and re-raises every other HTTPException. settings.py validates config/polls.yaml against the TRAFARET in utils.py. tests/conftest.py builds the app through aiohttp_client with config/polls_test.yaml, and tests/test_integration.py's test_vote posts {'choice': id} and expects 200 after the redirect and one more vote. pytest.ini sets asyncio_mode = auto and filterwarnings = error, so a deprecation warning fails the suite.

There is no session, so a token has nowhere to live; that comes first. The agent adds aiohttp-session[secure] to requirements-dev.txt, which brings cryptography, and calls aiohttp_session.setup(app, EncryptedCookieStorage(secret)) in init_app before the routes, with the secret read from a new session_secret key that it adds to TRAFARET, config/polls.yaml and config/polls_test.yaml, generated once with Fernet.generate_key() and documented in the README as a value to replace. EncryptedCookieStorage keeps the session in the cookie itself, encrypted, so no table and no Redis is needed for a demo-sized app, and the pull request says what changes when a shared store is wanted.

The CSRF part is a small module the agent writes rather than a package, because the maintained option for aiohttp is the session and a token, not a drop-in library. aiohttpdemo_polls/csrf.py has three pieces. get_csrf_token(request) reads the session and, when it has no token, stores secrets.token_urlsafe(32) under csrf_token. A context processor passed to aiohttp_jinja2.setup puts that token into every template context as csrf_token, and detail.html gains one line, a hidden _csrf_token input inside the vote form. csrf_middleware, appended after the session middleware in setup_middlewares, lets safe methods through and, for POST, PUT, PATCH and DELETE, reads _csrf_token from await request.post() and compares it to the session value with hmac.compare_digest, raising web.HTTPForbidden on a missing or wrong token. Because aiohttp caches the parsed form, the view's own await request.post() sees the same data. The 403 falls through the existing error middleware unchanged, since it only overrides 404 and 500, and the agent adds a 403.html next to them so the refusal renders like the other error pages.

The tests reuse the fixtures. test_vote_without_token posts the old body and expects 403 with the vote count unchanged. test_vote_with_token first requests /poll/1, reads the hidden input's value from the HTML, and posts it with the choice, expecting 200 after the redirect and one more vote; the test client keeps the session cookie between the two calls, which is what the browser does. The existing test_vote is rewritten to fetch the form first, and test_results and test_index are untouched because they only read. The agent runs pytest tests with filterwarnings = error still on, so a deprecated call in aiohttp-session against aiohttp 3.13 would fail here rather than in CI, and runs flake8 aiohttpdemo_polls as the Makefile does before opening the pull request.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add CSRF protection to the polls app in demos/polls of this repository. Read demos/polls/requirements-dev.txt, aiohttpdemo_polls/main.py, routes.py, views.py, middlewares.py, settings.py, utils.py, typedefs.py, db.py, templates/detail.html, templates/base.html, config/polls.yaml, config/polls_test.yaml, tests/conftest.py, tests/test_integration.py, pytest.ini and Makefile first. Add aiohttp-session[secure] and set up EncryptedCookieStorage in init_app with a session_secret read from the config and validated by the trafaret; add the key to both config files and document it. Add aiohttpdemo_polls/csrf.py with a token helper that stores secrets.token_urlsafe(32) in the session, a Jinja2 context processor that exposes it as csrf_token, and a middleware after the session middleware that rejects POST, PUT, PATCH and DELETE without a matching _csrf_token form field using hmac.compare_digest and HTTPForbidden. Add the hidden input to detail.html and a 403 template. Rewrite test_vote to fetch the form first and add tests for a POST without the token (403, no vote) and with it (vote recorded). Run pytest tests with the existing filterwarnings=error setting and flake8 aiohttpdemo_polls, then open a pull request that quotes 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 adds aiohttpdemo_polls/csrf.py and templates/403.html, and changes main.py (the session setup and context processor), middlewares.py (the appended middleware), utils.py (the new trafaret key), config/polls.yaml, config/polls_test.yaml, templates/detail.html (one hidden input), requirements-dev.txt, README.rst and tests/test_integration.py. Its description quotes the pytest output with the two new tests named, and shows a curl POST without the token answering 403 against the running app.

A reviewer checks the ordering, since a CSRF middleware that runs before the session middleware has no session to read; checks that the comparison is hmac.compare_digest and not ==; and checks that the secret in config/polls.yaml is a placeholder the README tells people to replace rather than a key anyone would deploy. They then decide whether the token should also be accepted from a header for JSON clients, which the middleware does not do yet because the app has only HTML forms, and whether the session cookie should carry secure and samesite attributes, which EncryptedCookieStorage takes as arguments.

A browser that loads a poll and votes sees the same pages; the hidden field travels with the form. A request that posts the vote without first loading the form, which is what a cross-site attacker's page would do, gets the 403 template.

Run it on every Linear issue labelled security

An automation on the Project with a linear trigger on linear.issue.labeled and the label security starts one run per issue that reports a form without a token. The trigger adds the issue after the prompt and fills in no placeholder, so the prompt tells the agent to read the form's route from the issue and to reuse csrf.py once it exists. An automation's run is read-only, so it posts its plan and the diff it would make as a comment, and a person starts the run that pushes.

For a workspace with several aiohttp apps, a handler on the reader's own server sends this body once per application directory to POST /o/{org}/sessions, with the directory in the prompt and a request_id that is a UUID v5 of that path, so a retried call returns the run it already started. Each run reads its own templates and finds the forms that post.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

CSRF protection is one middleware and one hidden input, and whether it works depends on cookie handling, middleware order and a constant-time compare, none of which a diff shows. The agent runs the real app against a real Postgres in its own sandbox, posts with and without the token, keeps the 403 and the passing suite with the pull request, and leaves filterwarnings = error on so a library that has drifted from aiohttp 3.13 fails in front of the reviewer rather than in production.

Teams that run several small aiohttp services tend to have the same gap in each, with a different template and a different config loader in each. One run per application gives each a pull request that fits its own forms.

Frequently asked questions

Why write the CSRF module instead of installing a package?

Because the current, maintained pieces for aiohttp are aiohttp-session for the session and a few lines for the token; the older CSRF packages on PyPI have not tracked recent aiohttp releases, and with filterwarnings = error an unmaintained dependency fails the suite. The module is short enough to read in one sitting.

Where does the session live?

In the cookie, encrypted with EncryptedCookieStorage and a Fernet key from the config. No table or Redis is needed. A deployment with several processes still works, since every process reads the same key, and aiohttp-session has a Redis storage if a shared, revocable session is wanted later.

Does the existing vote test still pass?

Not as written, because it posted without a token; the pull request rewrites it to load the poll page first and read the hidden field, which is what a browser does. The index and results tests are unchanged.

What about JSON or API clients?

The middleware reads the token from the form body only, because the app has only HTML forms. Accepting it from a header such as X-CSRF-Token is a few lines, and the pull request notes it for a later JSON endpoint.

Which methods are checked?

POST, PUT, PATCH and DELETE. GET, HEAD and OPTIONS pass through, which is why the poll and results pages need no token and why the app's own views must keep writes out of GET handlers.

More aiohttp jobs

The same job on other stacks

Keep reading