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
165 lines
4.9 KiB
Python
165 lines
4.9 KiB
Python
"""JWT auth + user management."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
from sqlmodel import Session, select
|
|
|
|
from config import settings
|
|
from database import get_session
|
|
from models.user import User
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
|
|
|
|
|
# --- password helpers ---
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
return pwd_context.verify(plain, hashed)
|
|
|
|
|
|
# --- token helpers ---
|
|
|
|
|
|
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": 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,
|
|
}
|
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
|
|
|
|
def create_access_token(user: User) -> str:
|
|
return _create_token(
|
|
user, "access", timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
)
|
|
|
|
|
|
def create_refresh_token(user: User) -> str:
|
|
return _create_token(
|
|
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(
|
|
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
|
)
|
|
except JWTError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token",
|
|
) from exc
|
|
if payload.get("type") != expected_type:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Wrong token type",
|
|
)
|
|
return payload
|
|
|
|
|
|
# --- 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()
|
|
|
|
|
|
def authenticate(session: Session, username: str, password: str) -> Optional[User]:
|
|
user = get_user(session, username)
|
|
if not user or not user.is_active:
|
|
return None
|
|
if not verify_password(password, user.hashed_password):
|
|
return None
|
|
return user
|
|
|
|
|
|
def users_exist(session: Session) -> bool:
|
|
return session.exec(select(User)).first() is not None
|
|
|
|
|
|
# --- FastAPI dependencies ---
|
|
|
|
|
|
def get_current_user(
|
|
token: Optional[str] = Depends(oauth2_scheme),
|
|
session: Session = Depends(get_session),
|
|
) -> User:
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Not authenticated",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
payload = decode_token(token, "access")
|
|
user = resolve_token_user(session, payload)
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Session is no longer valid — sign in again",
|
|
)
|
|
return 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)
|