All jobs

Add API Key Authentication to a Litestar App

Yes. An agent adds hashed API keys beside your Litestar app's JWT auth, with create, list and revoke routes, a middleware that reads X-API-Key, tests, and 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 starts with how the app authenticates today. In an app laid out like litestar-org/litestar-fullstack, src/py/app/domain/accounts/guards.py builds auth as an OAuth2PasswordBearerAuth with retrieve_user_handler=current_user_from_token, a 15-minute ACCESS_TOKEN_EXPIRATION, token_url of /api/access/login and an exclude list for the public paths. Refresh tokens are the model to copy: db/models/_refresh_token.py stores a SHA-256 token_hash, a family_id, expires_at and revoked_at on a UUIDv7AuditBase, and domain/accounts/services/_refresh_token.py mints them with secrets.token_urlsafe(32) and a hash_token static method. lib/settings.py already lists X-API-KEY among OBFUSCATE_HEADERS, so the logging config was written expecting such a header. Migrations live under db/migrations/versions/, models are re-exported from db/models/__init__.py, and pyproject.toml runs pytest with --cov-fail-under=65 and pytest-databases[postgres].

It adds db/models/_api_key.py: an ApiKey with user_id, a name, a unique key_hash, a prefix of the first eight characters for display, expires_at, last_used_at and revoked_at, exported from __init__.py, with an Alembic revision generated the way the initial one was. domain/accounts/services/_api_key.py is an SQLAlchemyAsyncRepositoryService whose create_api_key returns the raw key once and stores only its hash, and whose authenticate looks the hash up, refuses a revoked or expired row, and stamps last_used_at. The service is provided through create_service_provider in domain/accounts/deps.py like the others.

The routes go in domain/accounts/controllers/_api_keys.py under /api/access/api-keys: POST creates one for the signed-in user and returns the raw key in the response body, GET lists prefixes, names and dates, and DELETE /{key_id} sets revoked_at. Those sit behind the existing JWT auth on purpose, so a key is minted by a person and never by another key. For reading keys on requests, the agent subclasses the JWT middleware and passes it as authentication_middleware_class on the auth object in guards.py: when X-API-Key is present it hashes the value, resolves the user through the service and returns an AuthenticationResult with the key as auth; otherwise it defers to the bearer path, so every existing guard, requires_active_user included, keeps working unchanged.

Tests go in tests/integration/accounts/routes/test_api_keys.py, using the client fixture and the _login_user pattern from test_access.py: create a key with a JWT, read /api/me with only X-API-Key, see a revoked key and an expired key answer 401, and see a key whose user is inactive answer 401 too. The agent runs make test, which must stay over the coverage floor, and make lint, which runs ruff, mypy, pyright, slotscheck and codespell, and quotes both.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Do the work the Linear issue describes: add API key authentication to this Litestar app beside the existing JWT auth. Read src/py/app/domain/accounts/guards.py, deps.py, controllers/_access.py, services/_refresh_token.py, src/py/app/db/models/_refresh_token.py and __init__.py, src/py/app/lib/settings.py, src/py/app/db/migrations/env.py and the newest revision, pyproject.toml, Makefile and tests/integration/accounts/routes/test_access.py first. Add an ApiKey model with user_id, name, unique key_hash, prefix, expires_at, last_used_at and revoked_at, export it, and generate a migration. Add an ApiKeyService that mints keys with secrets.token_urlsafe and stores SHA-256 hashes, returning the raw key once. Add create, list and revoke routes under /api/access/api-keys behind the JWT auth, and a middleware subclass passed as authentication_middleware_class that resolves X-API-Key to the user and otherwise defers to the bearer path. Write integration tests covering a valid key, a revoked key, an expired key and an inactive user. Run make test and make lint, and open a pull request that links the issue and 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

What comes back is a pull request that adds the model, the migration, the service, the controller, the middleware and the test module, and changes guards.py, deps.py and the two __init__.py files that register models and services. The description shows the three routes with an example request and response each, with the raw key shown only in the create response, and quotes make test with the coverage figure and make lint with each tool's result.

The run's record keeps the migration being generated and applied against the test database and the full pytest output, so a reviewer can see the four refusal cases run rather than read that they exist.

Before merging, a reviewer settles the key's default lifetime, whether last_used_at should be written on every request or batched, since it is one UPDATE per authenticated call, and whether the SAQ job that already cleans up auth tokens should also drop keys past expires_at. Each is a small follow-up the pull request names.

Run it on every Linear issue labelled api-keys

This is the shape of work that arrives as a ticket. An automation in the Project with a linear trigger on linear.issue.labeled and api-keys in its config.labels starts a run with this prompt and the issue appended after it, so the run reads the ticket's own wording for which routes and lifetimes the team wants and opens the pull request linked to it. The trigger adds the issue; it fills in no placeholder in the prompt.

A team with several Litestar services starts one run per repository with one POST /o/{org}/sessions each, this prompt as input, the repository in resources and the issue's URL as a second resource, with a request_id that is a UUID v5 of the issue id so a retry returns the run it already started.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

Adding a second credential to an app that already has one is where security bugs come from: a key that is stored in plain text, a key route that another key can call, a middleware that short-circuits the guards. The agent reads how refresh tokens are already hashed and how the JWT middleware is wired, copies those decisions, and proves the four refusals with tests against a real PostgreSQL in its own sandbox.

The pull request carries the migration, the routes with example calls, and the lint and test output, so review is a diff and a set of refusals rather than a local database setup. Across several services the job runs in parallel, one sandbox and one pull request each, each fitted to that service's auth.

Frequently asked questions

Can a request use both a key and a bearer token?

The middleware reads X-API-Key first and, when it is present, decides on it alone; a bearer token on the same request is ignored. That keeps one credential responsible per request and makes the 401 reasons simple to read in the logs.

Why are the key routes behind the JWT auth?

So that a leaked key cannot mint more keys. Creating, listing and revoking need a person signed in with a short-lived access token, the way session management under /api/access/sessions already works.

Does the OpenAPI schema show the header?

The agent registers an apiKey security scheme in the header for the routes a key may call, so the generated schema at /schema documents X-API-Key beside the existing OAuth2 password flow. Which routes accept a key is a list in the pull request.

What does a key see of the user's roles?

Everything the user sees, since the middleware resolves the key to that User and the guards read connection.user as before. Narrower scopes per key are a second column and a guard, which the pull request leaves as a follow-up rather than guessing the scope names.

More Litestar jobs

The same job on other stacks

Keep reading