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
+47 -15
View File
@@ -32,12 +32,20 @@ def verify_password(plain: str, hashed: str) -> bool:
# --- token helpers ---
def _create_token(sub: str, role: str, token_type: str, expires: timedelta) -> str:
def token_version_of(user: User) -> int:
"""A user's current token version, tolerating a NULL from an older schema."""
return int(user.token_version or 1)
def _create_token(user: User, token_type: str, expires: timedelta) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": sub,
"role": role,
"sub": user.username,
"role": user.role,
"type": token_type,
# Minted-at authority version. Checked on every request, so bumping it
# revokes every token this user already holds.
"ver": token_version_of(user),
"iat": now,
"exp": now + expires,
}
@@ -46,22 +54,26 @@ def _create_token(sub: str, role: str, token_type: str, expires: timedelta) -> s
def create_access_token(user: User) -> str:
return _create_token(
user.username,
user.role,
"access",
timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
user, "access", timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
)
def create_refresh_token(user: User) -> str:
return _create_token(
user.username,
user.role,
"refresh",
timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
user, "refresh", timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
)
def bump_token_version(user: User) -> None:
"""Invalidate every token this user currently holds.
Called whenever their authority changes — password, role, active flag — so
a compromised account is actually cut off instead of staying usable until
the tokens expire on their own. The caller commits.
"""
user.token_version = token_version_of(user) + 1
def decode_token(token: str, expected_type: str = "access") -> dict:
try:
payload = jwt.decode(
@@ -83,6 +95,21 @@ def decode_token(token: str, expected_type: str = "access") -> dict:
# --- user lookups ---
def resolve_token_user(session: Session, payload: dict) -> Optional[User]:
"""The live user a token payload refers to, or None if it is no longer valid.
Deliberately re-reads the database rather than trusting the token's claims:
the role in a token is a snapshot from when it was minted, and an account
can be disabled or have its password reset at any point afterwards.
"""
user = get_user(session, payload.get("sub", ""))
if not user or not user.is_active:
return None
if int(payload.get("ver", 0)) != token_version_of(user):
return None
return user
def get_user(session: Session, username: str) -> Optional[User]:
return session.exec(select(User).where(User.username == username)).first()
@@ -114,19 +141,24 @@ def get_current_user(
headers={"WWW-Authenticate": "Bearer"},
)
payload = decode_token(token, "access")
user = get_user(session, payload.get("sub", ""))
if not user or not user.is_active:
user = resolve_token_user(session, payload)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found or inactive",
detail="Session is no longer valid — sign in again",
)
return user
def require_admin(user: User = Depends(get_current_user)) -> User:
def require_admin_role(user: User) -> User:
"""Role check split out so the WebSocket routes can reuse it."""
if user.role != "admin":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin privileges required",
)
return user
def require_admin(user: User = Depends(get_current_user)) -> User:
return require_admin_role(user)