Authorization Code with PKCE against any provider that publishes a discovery document, configured entirely from the UI — no environment variables, no restart to fix a typo in a client id, and a Test button that fetches the provider's metadata and says what it found. The best decision here was not writing any new session machinery. The callback sets the same httpOnly refresh cookie a password login sets and redirects to "/", and the SPA's existing boot-time restore() trades it for an access token. So an SSO session *is* a normal session — same revocation, same token_version checks, same everything — and no token is ever put in a URL fragment or query string where a proxy log or the browser history would keep it. The alternative everyone reaches for first, redirecting with #access_token=..., would have been a second code path and a worse one. What is actually verified, because "the provider said so" is worth nothing otherwise: the ID token's signature against the provider's published JWKS (re-fetched once if the kid is unknown, so key rotation heals itself), issuer, audience, expiry, and a nonce minted for that specific login. The state row is deleted when it is consumed, which is what makes a replayed callback fail, and it lives in the database rather than a dict so it survives the worker restart that can happen between the redirect out and the redirect back. Accounts match on sub, not username. It is the only identifier a provider promises is stable, so somebody renamed upstream stays the same account instead of silently acquiring a second one. An existing local account with that username is linked rather than duplicated, and keeps its role — linking must not quietly demote an admin. Claim-based admin mapping works in both directions: removed from the group upstream means read-only on the next sign-in. Two things this turned up that were already broken. verify_password raised passlib's UnknownHashError on a hash it could not parse, so a password attempt against an SSO account — which stores a deliberately unusable marker — would have been a 500 rather than a 401; it now returns false for any unparseable hash, which is the right answer for a corrupt row too. And the bundled nginx never forwarded X-Forwarded-Proto, so uvicorn saw plain HTTP behind TLS: the derived redirect URI came out as http:// and the refresh cookie lost its Secure flag. Both fixed. The password form stays on the login screen no matter what. A provider outage locking you out of the machine that runs your provider is a failure mode worth designing against. The authorization matrix made me write down why three routes are public, which is the right question to be asked: they are the path by which an unauthenticated person becomes an authenticated one. status deliberately returns only a boolean and a label — no issuer, no client id — so it tells a stranger nothing the button would not. 31 tests, with a throwaway RSA key standing in for a provider so verification is exercised for real rather than mocked: wrong key under the right kid, wrong audience, wrong issuer, expired, replayed nonce, reused state. Plus an end-to-end run of the whole flow — redirect, callback, cookie, session, group-mapped admin, replay refused, password login against the SSO account cleanly refused. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
236 lines
7.6 KiB
Python
236 lines
7.6 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 import exc
|
|
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:
|
|
"""Does this password match the stored hash?
|
|
|
|
A hash passlib cannot parse means "no", not an exception. Accounts that
|
|
sign in through the identity provider deliberately store an unusable
|
|
marker instead of a hash (see services/oidc_service.py), and a password
|
|
attempt against one of those has to be a clean rejection rather than a 500
|
|
— which is also what any other corrupt row deserves.
|
|
"""
|
|
try:
|
|
return pwd_context.verify(plain, hashed)
|
|
except (ValueError, TypeError, exc.PasslibSecurityError, exc.UnknownHashError):
|
|
return False
|
|
|
|
|
|
# --- 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)
|