A session token is the wrong credential for automation. It expires in an hour, it is minted by typing a password, and revoking it signs every one of that person's devices out. So automation gets its own credential, revocable on its own, and showing up in the audit log as itself. Three decisions worth recording, because each one is a place this could have been built wrong. **Only a hash is stored.** This is the opposite call from registry passwords one release ago, and for a concrete reason: a registry password has to be handed back to the registry, so it must be recoverable and is encrypted. A token is only ever compared against, so it does not need to be — and not keeping it is the difference between leaking the database and leaking everything the database protects. It is shown once and cannot be recovered; a readable prefix is kept so rows are still identifiable in the UI and the audit log. The hash is SHA-256, deliberately not bcrypt: bcrypt is slow to make guessing low-entropy human passwords expensive, and a token is 256 bits of secrets output, so the cost would buy nothing and would land on every single API request. **The scope is not folded into the User object.** get_current_user returns a session-attached row; downgrading its role in place to represent a read-only token would be written back to the database the next time anything committed that user — logout-everywhere does exactly that. So the token row is stashed on request.state and require_admin consults it, leaving the User untouched. The same lookup caps a token at its owner's authority rather than trusting the scope alone, so a demoted admin's token drops to read-only with them and a disabled account's tokens stop working. **A token cannot make itself permanent.** Creating tokens and creating users now require a signed-in session, via a require_session dependency that rejects token-authenticated requests. Without it, a leaked CI credential could mint a second one and survive its own revocation — the failure mode where revoking the leak does nothing. This is the one behaviour change for existing installs: scripted user creation now needs a login. The WebSocket routes still take JWTs only. They carry logs, the terminal and the deploy console, which a CI job has no use for, and leaving them alone keeps the token surface to the REST API. 19 tests, covering what is stored, that a read token really is read-only while its owner is an admin, that demoting and disabling the owner both take effect, expiry, tampering, the throttle on last-used writes, and that a token can neither mint another nor create a user. Verified end to end against a running app: two tokens, both scopes, revocation, and no plaintext anywhere in the database or the list response. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
224 lines
7.1 KiB
Python
224 lines
7.1 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, Request, 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
|
|
from services import api_token_service
|
|
|
|
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(
|
|
request: Request,
|
|
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"},
|
|
)
|
|
# An API token is not a JWT and must not be fed to the decoder — it is
|
|
# recognised by its prefix and looked up instead.
|
|
if api_token_service.looks_like_token(token):
|
|
resolved = api_token_service.resolve(session, token)
|
|
if not resolved:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="This API token is not valid (unknown, expired or revoked)",
|
|
)
|
|
row, user = resolved
|
|
api_token_service.touch(session, row)
|
|
# Stashed rather than folded into the User: mutating the role on a
|
|
# session-attached row would be written back to the database the next
|
|
# time anything commits that user.
|
|
request.state.api_token = row
|
|
return user
|
|
|
|
request.state.api_token = None
|
|
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 current_api_token(request: Request):
|
|
"""The API token this request was authenticated with, if any."""
|
|
return getattr(request.state, "api_token", None)
|
|
|
|
|
|
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(
|
|
request: Request, user: User = Depends(get_current_user)
|
|
) -> User:
|
|
require_admin_role(user)
|
|
row = current_api_token(request)
|
|
if row and api_token_service.effective_role(row, user) != "admin":
|
|
# The owner is an admin but this token was issued read-only, which is
|
|
# the whole point of handing one to a monitoring script.
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="This API token is read-only",
|
|
)
|
|
return user
|
|
|
|
|
|
def require_session(
|
|
request: Request, user: User = Depends(get_current_user)
|
|
) -> User:
|
|
"""An interactive session, not an API token.
|
|
|
|
Guards the routes that mint or revoke credentials — API tokens and user
|
|
accounts. A leaked CI token should be able to do the job it was issued for,
|
|
not quietly grant itself permanent access that outlives its own revocation.
|
|
"""
|
|
if current_api_token(request) is not None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="This action requires a signed-in session, not an API token",
|
|
)
|
|
return user
|
|
|
|
|
|
def require_admin_session(
|
|
request: Request, user: User = Depends(require_admin)
|
|
) -> User:
|
|
return require_session(request, user)
|