Make tokens revocable and move the refresh token out of localStorage (0.46.0)
CI / check (push) Successful in 7m7s
CI / build-and-push (push) Successful in 1m44s

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
This commit is contained in:
menzelj
2026-08-31 13:31:00 +02:00
co-authored by Claude Opus 5
parent 60a7ccff93
commit 41a21b5a25
15 changed files with 840 additions and 114 deletions
@@ -36,6 +36,9 @@ PUBLIC = {
"POST /api/auth/setup",
"POST /api/auth/login",
"POST /api/auth/refresh",
# Only drops the refresh cookie. Requiring a valid token would mean you
# cannot sign out once the session has already gone stale.
"POST /api/auth/logout",
}
#: Reachable by the read-only ``user`` role. Everything here has been checked
@@ -51,6 +54,9 @@ PUBLIC = {
#: in and hand YAML back, touching nothing on disk.
USER_READABLE = {
"GET /api/auth/me",
# Mutating, but only ever on the caller's own account: it bumps their own
# token_version to sign every one of their devices out.
"POST /api/auth/logout-everywhere",
"GET /api/dashboard/fleet",
# Stacks: status, logs and the compose file. Not the .env, not the export.
"GET /api/stacks",
+128
View File
@@ -0,0 +1,128 @@
"""Adding a column to a database that already exists.
There is no Alembic here: ``_ensure_model_columns`` diffs each model against
the live table and ``ADD COLUMN``s what is missing. That covers the only kind
of change made so far, but it has a sharp edge — SQLite fills an added column
with NULL unless the statement carries a DEFAULT.
``User.token_version`` is where that edge would have cut: existing rows would
have come back NULL, every token's version check would have failed against it,
and the upgrade would have signed out every user on every install. So the
helper now renders a DEFAULT for scalar defaults, and this file pins that
behaviour against a genuinely old-shaped table.
"""
from __future__ import annotations
import pytest
from sqlalchemy import create_engine, inspect, text
@pytest.fixture
def legacy_db(tmp_path, monkeypatch):
"""A database whose ``user`` table predates ``token_version``."""
import database
import models # noqa: F401 — populates SQLModel.metadata
db_file = tmp_path / "legacy.db"
engine = create_engine(f"sqlite:///{db_file}")
with engine.begin() as conn:
conn.execute(
text(
"""
CREATE TABLE user (
id INTEGER NOT NULL PRIMARY KEY,
username VARCHAR NOT NULL,
hashed_password VARCHAR NOT NULL,
role VARCHAR NOT NULL,
is_active BOOLEAN NOT NULL,
created_at DATETIME NOT NULL
)
"""
)
)
conn.execute(
text(
"INSERT INTO user (id, username, hashed_password, role, is_active,"
" created_at) VALUES (1, 'olduser', 'x', 'admin', 1, '2026-01-01')"
)
)
monkeypatch.setattr(database, "engine", engine)
return engine
def test_the_new_column_is_added_and_backfilled(legacy_db):
import database
assert "token_version" not in {c["name"] for c in inspect(legacy_db).get_columns("user")}
database._ensure_model_columns()
columns = {c["name"]: c for c in inspect(legacy_db).get_columns("user")}
assert "token_version" in columns
with legacy_db.begin() as conn:
value = conn.execute(text("SELECT token_version FROM user WHERE id = 1")).scalar()
assert value == 1, "existing rows must be backfilled, not left NULL"
def test_the_existing_row_survives_untouched(legacy_db):
import database
database._ensure_model_columns()
with legacy_db.begin() as conn:
row = conn.execute(text("SELECT username, role FROM user WHERE id = 1")).one()
assert row.username == "olduser"
assert row.role == "admin"
def test_running_it_twice_changes_nothing(legacy_db):
import database
database._ensure_model_columns()
database._ensure_model_columns() # must not raise "duplicate column name"
with legacy_db.begin() as conn:
assert conn.execute(text("SELECT token_version FROM user")).scalar() == 1
@pytest.mark.parametrize(
"value,expected",
[
(1, "1"),
(0, "0"),
(True, "1"),
(False, "0"),
("user", "'user'"),
("it's", "'it''s'"), # quotes escaped, not injected
],
)
def test_default_literals_are_rendered_and_escaped(value, expected):
from sqlalchemy import Column, Integer
import database
column = Column("c", Integer, default=value)
assert database._default_literal(column) == expected
def test_callable_defaults_have_no_literal():
"""``default_factory`` (a timestamp, say) has no fixed value to backfill —
such a column is added nullable, as before."""
from sqlalchemy import Column, DateTime
import database
from models.user import User
assert database._default_literal(Column("c", DateTime, default=lambda: 1)) is None
assert database._default_literal(User.__table__.columns["created_at"]) is None
def test_the_live_schema_matches_the_models(db):
"""Belt and braces on the real database the rest of the suite uses."""
from sqlmodel import SQLModel
import database
inspector = inspect(database.engine)
for table_name, table in SQLModel.metadata.tables.items():
live = {c["name"] for c in inspector.get_columns(table_name)}
missing = {c.name for c in table.columns} - live
assert not missing, f"{table_name} is missing {missing}"
+279
View File
@@ -0,0 +1,279 @@
"""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