All jobs

Add Refresh Tokens to a FastAPI App on SQLModel

Yes. An agent adds a refresh token table and rotation route, shortens the access token, migrates with Alembic, proves it with pytest 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 token path end to end first. In an app made from fastapi/full-stack-fastapi-template, backend/app/core/config.py sets ACCESS_TOKEN_EXPIRE_MINUTES to 60 * 24 * 8, eight days, and core/security.py signs {"exp", "sub"} with SECRET_KEY and HS256 through pyjwt. api/routes/login.py answers POST /login/access-token with a Token holding only access_token, and api/deps.py builds OAuth2PasswordBearer on that URL and decodes the token in get_current_user, answering 403 on a bad one and loading User by its sub. models.py defines Token, TokenPayload, and a User with a UUID primary key; Item already uses ondelete="CASCADE" on its owner_id. Five revisions sit under app/alembic/versions. The frontend keeps the token in localStorage (frontend/src/hooks/useAuth.ts) and main.tsx clears it on any 401 or 403. tests/conftest.py opens a session-scoped db against the real database and scripts/test.sh runs pytest under coverage; .github/workflows/test-backend.yml brings up Postgres with Docker Compose and fails under 90% coverage. pyproject.toml wants Python 3.14, uv.lock pins everything, and ruff and strict mypy run in pre-commit.

An eight-day bearer in localStorage is the problem a refresh token solves, so the agent splits the pair. models.py gains a RefreshToken table: UUID id, user_id with foreign_key="user.id" and ondelete="CASCADE" like Item, token_hash, expires_at, revoked_at and created_at. security.py gets create_refresh_token(), which returns a random secrets.token_urlsafe value and its SHA-256, so the database holds the hash only. Settings gets REFRESH_TOKEN_EXPIRE_DAYS, and ACCESS_TOKEN_EXPIRE_MINUTES drops to the value the prompt names. Token gains refresh_token, and /login/access-token fills both fields.

Two routes join login.py. POST /login/refresh-token takes {"refresh_token"}, finds the row by hash, refuses an expired, revoked or unknown one with 401, checks is_active, and rotates: it marks the row revoked and returns a new pair. A revoked token presented again revokes every refresh token of that user, since reuse means a copy exists somewhere. POST /login/logout revokes the presented token. alembic revision --autogenerate -m "add refresh tokens" writes the migration beside the existing five, and crud.py gets the three helpers the routes use. On the frontend, useAuth.ts stores both tokens and main.tsx's error handler tries one refresh before clearing and redirecting; the generated client picks up the new routes through the generate-client script.

Tests follow the shape of tests/api/routes/test_login.py: the login answer carries both tokens, a refresh returns a new pair and the old token then answers 401, an expired row answers 401, logout revokes, and reuse of a revoked token revokes the rest. The sandbox has no Docker, so the agent installs Postgres with apt-get, writes a .env with the values Settings requires and none left at changethis, and runs uv sync, uv run bash scripts/prestart.sh (which applies alembic upgrade head and creates the first superuser) and uv run bash scripts/test.sh, then uv run ruff check and uv run mypy app. The coverage figure in the test output stays above the 90% the workflow requires.

Start it with one API call

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

{
  "agent": "claude",
  "input": "The access token lives eight days in localStorage and there is no refresh token. Add one: a RefreshToken SQLModel table with a hashed token, expiry, revoked_at and a user_id that cascades on delete; a REFRESH_TOKEN_EXPIRE_DAYS setting; shorten ACCESS_TOKEN_EXPIRE_MINUTES to 30. Return refresh_token beside access_token from /login/access-token. Add POST /login/refresh-token that rotates the token and revokes the old one, revoking all of a user's refresh tokens when a revoked one is reused, and POST /login/logout that revokes the presented token. Write the Alembic migration with autogenerate. In the frontend, store both tokens and try one refresh on a 401 before clearing. Write tests in the style of test_login.py for the pair, rotation, expiry, logout and reuse. Run them against a local Postgres through scripts/prestart.sh and scripts/test.sh, then ruff and mypy. Open a pull request quoting the test and coverage 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 touches backend/app/models.py, core/security.py, core/config.py, crud.py, api/routes/login.py, a new file under app/alembic/versions, tests/api/routes/test_login.py, and on the frontend src/hooks/useAuth.ts, src/main.tsx and the regenerated client. Its description quotes the pytest output with each new test, the coverage total, and the ruff and mypy results.

A reviewer reads the refresh route for the order of checks, confirms the database stores a hash and never the token, and checks the reuse rule revokes by user rather than by row. The migration is one new table, so it runs forward without touching user. The transcript at GET /o/{org}/sessions/{id}/messages has the Postgres setup, the migration and the test run; the session's changes read has every file's diff.

Existing sessions are unaffected until their eight-day tokens expire; after the deploy, every new login gets the pair. Nothing was run against your database.

Run it on every Linear issue labelled auth

Add an automation on the Project with a linear trigger on linear.issue.labeled and the label your auth work uses, with this prompt as its text. Each labelled issue starts one run with the issue as its context, on its own branch, and the pull request links back to the issue. The trigger adds the issue after the prompt and fills in no placeholder; a change made by an app integration never fires it, so the agent's own comment on the issue starts nothing.

The automation's max_runs_per_hour holds a burst of labels to that many runs an hour. From your own server, the same run starts with this body and the issue URL in resources, with a request_id that is a UUID v5 of the issue id so a retried start returns the run already begun.

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

Why run it on Rush?

Token rotation is easy to write and easy to get subtly wrong: a hash compared the wrong way, a reuse that does not revoke, a migration that drifts from the model. The proof is the test suite running against a real Postgres that alembic upgrade head built, with coverage above the number CI enforces, and that takes a database the template expects Docker to provide. The sandbox installs one for the run, and the output is in the transcript.

Several services on the same template are several runs on their own branches, each with its own test output, in parallel. The reviewer reads one diff per service, and each pull request carries the figures that CI will check again.

Frequently asked questions

Why store a hash of the refresh token?

A refresh token is a long-lived credential. If the table leaks, hashes cannot be presented to the refresh route, while raw tokens could. The route hashes what the client sends and looks up the hash, the same way passwords are checked.

Why revoke everything when a revoked token is reused?

After rotation, exactly one copy of the latest token should exist. If an older one turns up again, either the client retried a lost response or someone else holds a copy, and the safe answer for both is to end the family and make the user log in again.

Does the frontend need to change?

Yes, in two files. useAuth.ts stores both tokens on login, and main.tsx's error handler calls the refresh route once on a 401 before clearing storage and redirecting to /login. The client types for the new routes come from pnpm generate-client, which reads the backend's OpenAPI document.

How does this run without Docker Compose?

The template's tests expect docker compose up -d --wait db mailpit. The sandbox has no Docker, so the agent installs Postgres directly and points DATABASE_URL at it; prestart.sh and test.sh run unchanged. CI keeps using Compose.

More SQLModel jobs

The same job on other stacks

Keep reading