All jobs

Add CORS to an aiohttp App

Yes. An agent adds aiohttp-cors to your aiohttp app with an origin allowlist from its config, enables it on the JSON route only, tests preflights and opens a PR.

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 how the app is assembled before it adds a cross-origin policy, because aiohttp has no CORS middleware of its own and the policy has to be attached to the routes that need it. In a service like the shortify demo in aio-libs/aiohttp-demos, shortify/main.py has an init() that loads config/config.yml through load_config, stores it under CONF_KEY, appends redis_ctx to app.cleanup_ctx, sets up Jinja2 and calls setup_routes(app, PROJ_ROOT); main() then runs web.run_app on the configured host and port, 127.0.0.1 and 9001. shortify/routes.py registers four routes: GET / named index, GET /{short_id} named short, POST /shortify named shortify and a static mount. shortify/views.py is where the API lives: shortify reads await request.json(), increments shortify:count in Redis, encodes the counter into a short path and answers web.json_response({"url": url}), while redirect looks the key up and raises HTTPFound.

The config is validated, not just loaded. shortify/utils.py declares CONFIG_TRAFARET as a t.Dict with a redis block of port, host, db, minsize and maxsize, plus host as t.IP and port as t.Int, so an unknown key in config.yml is refused at startup. The agent adds an optional cors key, a list of origin strings, to that schema and a commented example to config/config.yml, so the allowlist lives beside the Redis settings instead of in code. requirements.txt pins aiohttp==3.13.5, aiohttp-jinja2==1.6, redis==8.1.0, trafaret==2.1.1, pytest-aiohttp==1.1.1 and pytest-asyncio==1.4.0, and setup.py lists the runtime packages in install_requires; the agent adds aiohttp-cors to both. Its current release, 0.8.1, requires aiohttp>=3.9 and Python 3.9 or later, which the pinned aiohttp satisfies.

In init(), after setup_routes, the agent calls aiohttp_cors.setup(app, defaults={...}) with one ResourceOptions per configured origin, allowing the Content-Type header, the POST method and a max_age for preflight caching, and then cors.add(app.router['shortify']), using the route name the repository already gives it. Only that resource is CORS-enabled: GET / renders the page and GET /{short_id} is a redirect that a browser follows top-level, so neither needs cross-origin read access, and leaving them out is the safer default. With an empty list the setup call is skipped, so a deployment that never fills in cors behaves exactly as today, and the page's own jQuery call in shortify/templates/index.html, which posts JSON to /shortify from the same origin, is unaffected.

The tests in tests/test_shortify.py already build the app through the cli fixture from tests/conftest.py and flush Redis before each case, with pytest.ini setting asyncio_mode = auto and filterwarnings = error. The agent adds three cases: an OPTIONS /shortify preflight with Origin and Access-Control-Request-Method: POST from an allowed origin answers 200 with Access-Control-Allow-Origin echoing that origin and Access-Control-Allow-Headers naming Content-Type; a POST /shortify with an allowed Origin gets the allow header on the real response; and a preflight from an origin not in the list is refused with 403. It runs pytest demos/shortify and flake8 shortify setup.py from the demo's Makefile in its sandbox against a local Redis, and because filterwarnings = error turns any deprecation warning the new package raises under aiohttp 3.13 into a failure, it adds a targeted ignore for that one message rather than loosening the global rule.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Add CORS to this aiohttp app with aiohttp-cors. Read shortify/main.py, shortify/routes.py, shortify/views.py, shortify/utils.py, config/config.yml, requirements.txt, setup.py, pytest.ini, tests/conftest.py and tests/test_shortify.py first. Add an optional cors list of allowed origins to the trafaret config schema and a commented example to config.yml. After the routes are registered, set up aiohttp_cors with one ResourceOptions per configured origin that allows the Content-Type header and the POST method, and enable it on the shortify route only; leave the page and the redirect route same-origin. Skip the setup when the list is empty. Add tests for an allowed preflight, an allowed POST and a refused preflight. Run pytest and flake8, keep filterwarnings = error, 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 shortify/main.py, shortify/utils.py, config/config.yml, requirements.txt, setup.py, tests/test_shortify.py and, if a warning filter was needed, pytest.ini. Its description shows the preflight exchange as curl -i output, headers in and headers out, for an allowed origin and for a refused one, and pastes the pytest and flake8 results.

A reviewer sees that the allowlist is configuration validated by the same trafaret schema as the rest of config.yml, that only the JSON route is exposed, and that the three new tests sit beside test_create_short_url and use the same fixtures. The run's record keeps every command, including the Redis start and the test run against it.

Before merging, a reviewer fills in the real front-end origins, decides whether credentials should ever be allowed (the agent leaves allow_credentials off), and whether GET /{short_id} should also be readable cross-origin for a client that wants to resolve short links by script. The views and the Redis handling are unchanged.

Run it on every aiohttp service a browser front end needs to call

A team with several aiohttp services starts one run per repository from its own server: a POST /o/{org}/sessions each, with the repository in resources, the front-end origins written into input, 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 routes, so a service whose JSON lives under /api gets the policy on that resource tree, and one that already configures aiohttp_cors gets its allowlist extended rather than a second setup call.

Later, a Linear issue labelled cors in the Project can start a run through an automation with a linear trigger and the prompt "add the origin this issue names to the allowlist in config.yml, extend the preflight test to cover it, run pytest and open a pull request". The trigger adds the issue after the prompt, and the run reads it through the Linear connection, so a new front-end domain arrives as a reviewed one-line change with a test.

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

Why run it on Rush?

CORS mistakes are invisible from the server: the response looks fine in curl and the browser refuses it anyway. The agent runs the actual preflight and the actual POST with an Origin header in its sandbox, against a Redis it starts itself, and keeps the full header blocks, so the review is of a real exchange and not of a middleware line that looks correct.

Every command stays with the run, from the package install to the pytest run with filterwarnings = error still on, and the pull request quotes them. A team with many small aiohttp services gets the same change on each, in parallel, each with its own output and its own pull request.

Frequently asked questions

Why not allow every origin with a wildcard?

Because * cannot be combined with credentials and exposes the JSON endpoint to any page on the web. The agent reads the allowlist from config.yml, validated by the existing trafaret schema, so adding an origin is a config change reviewed like any other. A reader who really wants * can put it in the list; aiohttp-cors treats it as the special all-origins entry.

Why is CORS only on the POST route?

GET / is an HTML page and GET /{short_id} is a redirect a browser follows as a navigation; neither is read by script from another origin. aiohttp-cors enables CORS only on the resources added to its configuration, so leaving those two out means they keep today's behaviour. Adding them later is one more cors.add call.

What happens to the existing tests?

They keep passing untouched. The cli fixture builds the app through init(), which now also runs the CORS setup, and the three existing cases send no Origin header, so no CORS headers are added to their responses. The new cases use the same cli and clean_redis fixtures.

Does it work on an app that uses aiohttp middlewares?

Yes. aiohttp-cors attaches to resources and routes rather than to the middleware chain, so it coexists with an error middleware like the one in the polls demo. The order that matters is that aiohttp_cors.setup runs after the routes it will add are registered, which is why the agent places it after setup_routes.

More aiohttp jobs

The same job on other stacks

Keep reading