Files
stackpilot/backend/tests/test_token_revocation.py
T
menzeljandClaude Opus 5 41a21b5a25
CI / check (push) Successful in 7m7s
CI / build-and-push (push) Successful in 1m44s
Make tokens revocable and move the refresh token out of localStorage (0.46.0)
F5 — A token was valid until it expired, full stop. Resetting a compromised
account's password changed nothing for whoever held its tokens (up to 30 days
for a refresh token), demoting or disabling an account only took effect once
the same clock ran out, and logout was purely client-side.

Every account now has a token_version, every token is minted carrying it, and
every request compares the two. Bumping it is the revoke switch, pulled on the
three changes that alter what an account may do: password, role, active flag.
"Sign out everywhere" in the user menu bumps your own. Plain "Sign out" only
drops the cookie, because signing out on your phone should not kill your
desktop session.

The refresh token left localStorage for an httpOnly cookie (SameSite=Lax,
scoped to /api/auth), and the access token is now held in memory only. A
successful XSS can still act inside the open page but can no longer walk off
with 30 days of access. The cookie is marked Secure only when the request
arrived over HTTPS — request.url.scheme is trustworthy since the F4 fix — so a
plain-HTTP homelab keeps working. Any refresh token an older build left in
localStorage is deleted on first load. Scripted clients that cannot hold a
cookie can still ask for it in the body with ?in_body=true.

F9 comes with it, as predicted: the WebSocket helpers read the role off the
live user instead of the token's claim. /ws/exec is root-equivalent on the
host, and a token minted while the account was an admin stayed syntactically
valid after a demotion.

The sharp edge was the migration, not the feature. _ensure_model_columns emits
ADD COLUMN without a DEFAULT, so SQLite would have filled token_version with
NULL on every existing install, every version check would have failed against
it, and the upgrade would have locked out every user everywhere. The helper now
renders NOT NULL DEFAULT <literal> for scalar defaults; test_schema_migration
builds a genuinely old-shaped user table and asserts the backfill. The version
comparison also tolerates NULL as 1, so a database migrated by some other route
still works.

Writing that test surfaced an undocumented precondition: _ensure_model_columns
does nothing unless `models` has been imported, since SQLModel.metadata is
empty until then. It holds in production because init_db imports first; now it
says so.

The authorization matrix did its job — adding two auth routes failed the suite
until both were classified, which is exactly the review moment it exists for.

30 new tests (698 total). Upgrading signs everyone out once.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
2026-08-31 13:31:00 +02:00

280 lines
9.5 KiB
Python

"""Token revocation.
Before 0.46.0 a token was valid until it expired, full stop. Resetting a
compromised account's password changed nothing for whoever held its tokens —
up to 30 days for a refresh token — and demoting or disabling an account only
took effect once the same clock ran out.
Every token now carries the ``token_version`` it was minted with, and every
request compares that against the live user. Bumping the version is therefore
the revoke switch, and it is pulled on the three changes that alter what an
account may do: password, role, active flag.
"""
from __future__ import annotations
import pytest
from sqlmodel import Session, select
@pytest.fixture
def victim(db):
"""A throwaway account whose tokens the tests revoke."""
import auth as auth_mod
from database import engine
from models.user import User
with Session(engine) as session:
existing = session.exec(select(User).where(User.username == "revoke-me")).first()
if existing:
session.delete(existing)
session.commit()
user = User(
username="revoke-me",
hashed_password=auth_mod.hash_password("original-password"),
role="user",
)
session.add(user)
session.commit()
session.refresh(user)
session.expunge(user)
return user
def _token_for(username: str) -> str:
import auth as auth_mod
from database import engine
from models.user import User
with Session(engine) as session:
user = session.exec(select(User).where(User.username == username)).one()
return auth_mod.create_access_token(user)
def _still_works(client, token: str) -> bool:
response = client.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"})
return response.status_code == 200
# --------------------------------------------------------------------------- #
# The claim itself
# --------------------------------------------------------------------------- #
def test_tokens_carry_the_version_they_were_minted_with(victim):
import auth as auth_mod
payload = auth_mod.decode_token(auth_mod.create_access_token(victim), "access")
assert payload["ver"] == 1
def test_a_null_version_from_an_older_schema_reads_as_one(victim):
"""Tolerated so a half-migrated database does not lock everyone out."""
import auth as auth_mod
victim.token_version = None
assert auth_mod.token_version_of(victim) == 1
# --------------------------------------------------------------------------- #
# What revokes
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"change",
[
pytest.param({"password": "brand-new-password"}, id="password-reset"),
pytest.param({"role": "admin"}, id="role-change"),
pytest.param({"is_active": False}, id="account-disabled"),
],
)
def test_changing_what_an_account_may_do_kills_its_tokens(
as_admin, client, victim, change
):
token = _token_for("revoke-me")
assert _still_works(client, token)
assert as_admin.request(
"PATCH", f"/api/auth/users/{victim.id}", json=change
).status_code == 200
assert not _still_works(client, token), f"{change} left the old token usable"
def test_a_cosmetic_update_does_not_sign_the_user_out(as_admin, client, victim):
"""Re-saving the same role must not invalidate a working session."""
token = _token_for("revoke-me")
assert as_admin.request(
"PATCH", f"/api/auth/users/{victim.id}", json={"role": victim.role}
).status_code == 200
assert _still_works(client, token)
def test_a_fresh_token_works_after_a_revoke(as_admin, client, victim):
old = _token_for("revoke-me")
as_admin.request(
"PATCH", f"/api/auth/users/{victim.id}", json={"password": "another-one"}
)
assert not _still_works(client, old)
assert _still_works(client, _token_for("revoke-me"))
def test_refresh_rejects_a_revoked_token(as_admin, client, victim):
"""The long-lived token is the one that mattered — 30 days of access."""
import auth as auth_mod
from database import engine
from models.user import User
with Session(engine) as session:
user = session.exec(select(User).where(User.username == "revoke-me")).one()
refresh = auth_mod.create_refresh_token(user)
as_admin.request(
"PATCH", f"/api/auth/users/{victim.id}", json={"password": "changed-again"}
)
response = client.post("/api/auth/refresh", json={"refresh_token": refresh})
assert response.status_code == 401
def test_logout_everywhere_revokes_the_callers_own_tokens(client, victim):
import auth as auth_mod
from database import engine
from models.user import User
with Session(engine) as session:
user = session.exec(select(User).where(User.username == "revoke-me")).one()
token = auth_mod.create_access_token(user)
assert client.post(
"/api/auth/logout-everywhere", headers={"Authorization": f"Bearer {token}"}
).status_code == 200
assert not _still_works(client, token)
# --------------------------------------------------------------------------- #
# The refresh cookie
# --------------------------------------------------------------------------- #
def test_login_puts_the_refresh_token_in_an_httponly_cookie(client, victim):
response = client.post(
"/api/auth/login", json={"username": "revoke-me", "password": "original-password"}
)
assert response.status_code == 200
# Not in the body — that is the whole point.
assert response.json().get("refresh_token") is None
assert response.json()["access_token"]
cookie = response.headers["set-cookie"]
assert "stackpilot_refresh=" in cookie
assert "HttpOnly" in cookie
assert "Path=/api/auth" in cookie
assert "SameSite=lax" in cookie.lower().replace("samesite=lax", "SameSite=lax")
def test_refresh_works_off_the_cookie_alone(client, victim):
client.post(
"/api/auth/login", json={"username": "revoke-me", "password": "original-password"}
)
# TestClient keeps the cookie jar, so no body is sent here.
response = client.post("/api/auth/refresh", json={})
assert response.status_code == 200
assert response.json()["access_token"]
def test_scripted_clients_can_still_ask_for_the_token_in_the_body(client, victim):
response = client.post(
"/api/auth/login?in_body=true",
json={"username": "revoke-me", "password": "original-password"},
)
assert response.json()["refresh_token"]
def test_logout_clears_the_cookie(client, victim):
client.post(
"/api/auth/login", json={"username": "revoke-me", "password": "original-password"}
)
response = client.post("/api/auth/logout")
assert response.status_code == 200
assert 'stackpilot_refresh=""' in response.headers["set-cookie"] or (
"stackpilot_refresh=;" in response.headers["set-cookie"]
)
def test_the_cookie_is_not_marked_secure_over_plain_http(client, victim):
"""A homelab on plain HTTP must still be able to stay signed in.
Marking the cookie Secure unconditionally would make the browser drop it and
nobody could hold a session. Over HTTPS the flag is set — see _issue().
"""
response = client.post(
"/api/auth/login", json={"username": "revoke-me", "password": "original-password"}
)
assert "secure" not in response.headers["set-cookie"].lower()
# --------------------------------------------------------------------------- #
# WebSockets go through the same check (F9)
# --------------------------------------------------------------------------- #
def test_websocket_auth_resolves_against_the_database(victim):
"""A socket must not trust the role baked into the token.
``/ws/exec`` is root-equivalent on the host, and a token minted while the
account was an admin stays syntactically valid after a demotion — so the
role has to come from the database, not the claim.
"""
import auth as auth_mod
from database import engine
from models.user import User
from routers.ws import _user_for
with Session(engine) as session:
user = session.exec(select(User).where(User.username == "revoke-me")).one()
user.role = "admin"
auth_mod.bump_token_version(user)
session.add(user)
session.commit()
session.refresh(user)
admin_token = auth_mod.create_access_token(user)
assert _user_for(admin_token).role == "admin"
# Demote. The token still decodes, but must no longer resolve.
with Session(engine) as session:
user = session.exec(select(User).where(User.username == "revoke-me")).one()
user.role = "user"
auth_mod.bump_token_version(user)
session.add(user)
session.commit()
assert auth_mod.decode_token(admin_token, "access")["role"] == "admin"
assert _user_for(admin_token) is None
def test_websocket_auth_rejects_a_disabled_account(victim):
import auth as auth_mod
from database import engine
from models.user import User
from routers.ws import _user_for
with Session(engine) as session:
user = session.exec(select(User).where(User.username == "revoke-me")).one()
token = auth_mod.create_access_token(user)
assert _user_for(token) is not None
user.is_active = False
session.add(user)
session.commit()
assert _user_for(token) is None
def test_websocket_auth_rejects_garbage(victim):
from routers.ws import _user_for
assert _user_for(None) is None
assert _user_for("") is None
assert _user_for("not-a-jwt") is None