Files
stackpilot/backend/models/user.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

73 lines
1.9 KiB
Python

from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlmodel import Field, SQLModel
def _now() -> datetime:
return datetime.now(timezone.utc)
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
username: str = Field(index=True, unique=True)
hashed_password: str
role: str = Field(default="user") # "admin" | "user"
is_active: bool = Field(default=True)
created_at: datetime = Field(default_factory=_now)
#: Bumped whenever this account's authority changes — password, role or
#: active flag. Every token carries the value it was minted with, so a
#: bump makes all outstanding tokens for this user fail their next check.
#: Without it a password reset left the old tokens usable for their full
#: lifetime (up to 30 days for a refresh token).
token_version: int = Field(default=1)
# --- API schemas ---
class UserRead(SQLModel):
id: int
username: str
role: str
is_active: bool
class UserCreate(SQLModel):
username: str
password: str
role: str = "admin"
class UserUpdate(SQLModel):
password: Optional[str] = None
role: Optional[str] = None
is_active: Optional[bool] = None
class LoginRequest(SQLModel):
username: str
password: str
class TokenPair(SQLModel):
"""Login/refresh response.
``refresh_token`` is optional in the body: the API sets it as an httpOnly
cookie, and browsers never need (or should) see it. It is still returned
when the caller opts in with ``?in_body=true`` so scripted clients that
cannot hold a cookie jar keep working.
"""
access_token: str
token_type: str = "bearer"
refresh_token: Optional[str] = None
class RefreshRequest(SQLModel):
"""Body for ``/api/auth/refresh``. Optional — the cookie is preferred."""
refresh_token: Optional[str] = None