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>
340 lines
12 KiB
Python
340 lines
12 KiB
Python
"""Authentication routes + first-launch setup wizard."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
|
from sqlmodel import Session, delete, select
|
|
|
|
import auth as auth_mod
|
|
from database import get_session
|
|
from models.runtime_state import LoginAttempt
|
|
from models.user import (
|
|
LoginRequest,
|
|
RefreshRequest,
|
|
TokenPair,
|
|
User,
|
|
UserCreate,
|
|
UserRead,
|
|
UserUpdate,
|
|
)
|
|
from config import settings
|
|
from services import audit_service
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
# Login rate limit: max 10 attempts per minute per client IP.
|
|
#
|
|
# Kept in the database rather than a module dict. In memory it reset on every
|
|
# restart — so an attacker could clear their own budget by getting the process
|
|
# to restart — and with more than one uvicorn worker each worker enforced its
|
|
# own limit, multiplying the real allowance by the worker count.
|
|
#
|
|
# The IP is only meaningful because uvicorn runs with --proxy-headers; without
|
|
# that every request looks like it comes from the frontend container and this
|
|
# would throttle all users together.
|
|
_RATE_LIMIT = 10
|
|
_RATE_WINDOW = timedelta(seconds=60)
|
|
#: Attempts older than this are deleted while we are in the table anyway.
|
|
_RATE_RETENTION = timedelta(hours=1)
|
|
|
|
|
|
def _check_rate_limit(session: Session, ip: str) -> None:
|
|
now = datetime.now(timezone.utc)
|
|
session.exec(delete(LoginAttempt).where(LoginAttempt.at < now - _RATE_RETENTION))
|
|
recent = session.exec(
|
|
select(LoginAttempt).where(
|
|
LoginAttempt.ip == ip, LoginAttempt.at >= now - _RATE_WINDOW
|
|
)
|
|
).all()
|
|
if len(recent) >= _RATE_LIMIT:
|
|
session.commit()
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="Too many login attempts, slow down.",
|
|
)
|
|
session.add(LoginAttempt(ip=ip, at=now))
|
|
session.commit()
|
|
|
|
|
|
#: The refresh cookie is scoped to the two endpoints that consume it, so it is
|
|
#: not attached to every API call the way a "/" cookie would be.
|
|
REFRESH_COOKIE = "stackpilot_refresh"
|
|
REFRESH_COOKIE_PATH = "/api/auth"
|
|
|
|
|
|
def _issue(
|
|
user: User, response: Response, request: Request, in_body: bool = False
|
|
) -> TokenPair:
|
|
"""Mint a token pair, putting the refresh token in an httpOnly cookie.
|
|
|
|
Keeping the long-lived token out of JavaScript's reach means a successful
|
|
XSS can no longer walk off with 30 days of access — it is limited to
|
|
whatever it can do in the live page. The short-lived access token still
|
|
goes to the client, which holds it in memory only.
|
|
|
|
``in_body`` returns it in the response as well, for scripted clients that
|
|
have no cookie jar.
|
|
"""
|
|
refresh = auth_mod.create_refresh_token(user)
|
|
response.set_cookie(
|
|
REFRESH_COOKIE,
|
|
refresh,
|
|
max_age=settings.REFRESH_TOKEN_EXPIRE_DAYS * 24 * 3600,
|
|
httponly=True,
|
|
# Lax rather than Strict so following a link into StackPilot keeps you
|
|
# signed in; the cookie is only ever read by same-site POSTs anyway.
|
|
samesite="lax",
|
|
# Only when the request actually arrived over TLS — marking it Secure on
|
|
# a plain-HTTP homelab deployment would make the browser drop it and
|
|
# nobody could stay signed in. request.url.scheme is trustworthy here
|
|
# because uvicorn runs with --proxy-headers.
|
|
secure=request.url.scheme == "https",
|
|
path=REFRESH_COOKIE_PATH,
|
|
)
|
|
return TokenPair(
|
|
access_token=auth_mod.create_access_token(user),
|
|
refresh_token=refresh if in_body else None,
|
|
)
|
|
|
|
|
|
@router.get("/needs-setup")
|
|
def needs_setup(session: Session = Depends(get_session)) -> dict:
|
|
"""First-launch wizard check: True if no users exist yet."""
|
|
return {"needs_setup": not auth_mod.users_exist(session)}
|
|
|
|
|
|
@router.post("/setup", response_model=TokenPair)
|
|
def setup(
|
|
body: UserCreate,
|
|
request: Request,
|
|
response: Response,
|
|
in_body: bool = False,
|
|
session: Session = Depends(get_session),
|
|
) -> TokenPair:
|
|
if auth_mod.users_exist(session):
|
|
raise HTTPException(status_code=400, detail="Setup already completed")
|
|
user = User(
|
|
username=body.username,
|
|
hashed_password=auth_mod.hash_password(body.password),
|
|
role="admin",
|
|
)
|
|
session.add(user)
|
|
session.commit()
|
|
session.refresh(user)
|
|
audit_service.record(
|
|
session, user=user.username, action="user.setup", target=user.username
|
|
)
|
|
return _issue(user, response, request, in_body)
|
|
|
|
|
|
@router.post("/login", response_model=TokenPair)
|
|
def login(
|
|
body: LoginRequest,
|
|
request: Request,
|
|
response: Response,
|
|
in_body: bool = False,
|
|
session: Session = Depends(get_session),
|
|
) -> TokenPair:
|
|
ip = request.client.host if request.client else "unknown"
|
|
_check_rate_limit(session, ip)
|
|
user = auth_mod.authenticate(session, body.username, body.password)
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect username or password",
|
|
)
|
|
audit_service.record(
|
|
session, user=user.username, action="auth.login", target=user.username, ip=ip
|
|
)
|
|
return _issue(user, response, request, in_body)
|
|
|
|
|
|
@router.post("/refresh", response_model=TokenPair)
|
|
def refresh(
|
|
request: Request,
|
|
response: Response,
|
|
body: RefreshRequest | None = None,
|
|
in_body: bool = False,
|
|
session: Session = Depends(get_session),
|
|
) -> TokenPair:
|
|
"""Exchange a refresh token for a fresh pair.
|
|
|
|
Reads the httpOnly cookie; a body is accepted as a fallback for clients
|
|
that cannot hold one. The token is re-validated against the live user, so a
|
|
password reset or a disabled account takes effect here too rather than at
|
|
the end of the token's 30-day life.
|
|
"""
|
|
token = request.cookies.get(REFRESH_COOKIE) or (body.refresh_token if body else None)
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="No refresh token"
|
|
)
|
|
payload = auth_mod.decode_token(token, "refresh")
|
|
user = auth_mod.resolve_token_user(session, payload)
|
|
if not user:
|
|
response.delete_cookie(REFRESH_COOKIE, path=REFRESH_COOKIE_PATH)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Session is no longer valid — sign in again",
|
|
)
|
|
return _issue(user, response, request, in_body)
|
|
|
|
|
|
@router.post("/logout")
|
|
def logout(request: Request, response: Response) -> dict:
|
|
"""End the session on this device by dropping the refresh cookie.
|
|
|
|
Deliberately does not bump ``token_version``: signing out on your phone
|
|
should not kill the session on your desktop. Use "sign out everywhere"
|
|
for that. The access token is held in memory by the client and dies with
|
|
the tab; it stays technically valid for the rest of its hour, which is why
|
|
it is short-lived.
|
|
"""
|
|
response.delete_cookie(REFRESH_COOKIE, path=REFRESH_COOKIE_PATH)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.post("/logout-everywhere")
|
|
def logout_everywhere(
|
|
request: Request,
|
|
response: Response,
|
|
session: Session = Depends(get_session),
|
|
user: User = Depends(auth_mod.get_current_user),
|
|
) -> dict:
|
|
"""Revoke every token this account holds, on every device."""
|
|
auth_mod.bump_token_version(user)
|
|
session.add(user)
|
|
session.commit()
|
|
response.delete_cookie(REFRESH_COOKIE, path=REFRESH_COOKIE_PATH)
|
|
audit_service.record(
|
|
session, user=user.username, action="auth.logout_everywhere",
|
|
target=user.username, ip=_ip(request),
|
|
)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/me", response_model=UserRead)
|
|
def me(user: User = Depends(auth_mod.get_current_user)) -> User:
|
|
return user
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# User management (admin only)
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
def _ip(request: Request) -> str:
|
|
return request.client.host if request.client else "unknown"
|
|
|
|
|
|
@router.get("/users", response_model=list[UserRead])
|
|
def list_users(
|
|
session: Session = Depends(get_session),
|
|
_admin: User = Depends(auth_mod.require_admin_session),
|
|
) -> list[User]:
|
|
return session.exec(select(User).order_by(User.id)).all()
|
|
|
|
|
|
@router.post("/users", response_model=UserRead, status_code=201)
|
|
def create_user(
|
|
body: UserCreate,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
admin: User = Depends(auth_mod.require_admin_session),
|
|
) -> User:
|
|
if not body.username.strip() or not body.password:
|
|
raise HTTPException(status_code=400, detail="Username and password required")
|
|
if auth_mod.get_user(session, body.username):
|
|
raise HTTPException(status_code=409, detail="Username already exists")
|
|
role = body.role if body.role in ("admin", "user") else "user"
|
|
user = User(
|
|
username=body.username,
|
|
hashed_password=auth_mod.hash_password(body.password),
|
|
role=role,
|
|
)
|
|
session.add(user)
|
|
session.commit()
|
|
session.refresh(user)
|
|
audit_service.record(
|
|
session, user=admin.username, action="user.create", target=user.username,
|
|
detail=f"role={role}", ip=_ip(request),
|
|
)
|
|
return user
|
|
|
|
|
|
@router.patch("/users/{user_id}", response_model=UserRead)
|
|
def update_user(
|
|
user_id: int,
|
|
body: UserUpdate,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
admin: User = Depends(auth_mod.require_admin_session),
|
|
) -> User:
|
|
user = session.get(User, user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
# Guard against locking yourself out / demoting the last admin.
|
|
demoting = (body.role is not None and body.role != "admin") or body.is_active is False
|
|
if user.role == "admin" and demoting:
|
|
other_admins = session.exec(
|
|
select(User).where(User.role == "admin", User.is_active == True, User.id != user_id) # noqa: E712
|
|
).first()
|
|
if not other_admins:
|
|
raise HTTPException(status_code=400, detail="Cannot demote or disable the last active admin")
|
|
# Any of these three changes what this account is allowed to do, so the
|
|
# tokens it already holds must stop working. Without the bump a password
|
|
# reset was cosmetic: whoever had the old tokens kept full access for up to
|
|
# 30 days, and a demotion or a disable only took effect once they expired.
|
|
authority_changed = (
|
|
bool(body.password)
|
|
or (body.role is not None and body.role != user.role)
|
|
or (body.is_active is not None and body.is_active != user.is_active)
|
|
)
|
|
if body.password:
|
|
user.hashed_password = auth_mod.hash_password(body.password)
|
|
if body.role is not None:
|
|
if body.role not in ("admin", "user"):
|
|
raise HTTPException(status_code=400, detail="Invalid role")
|
|
user.role = body.role
|
|
if body.is_active is not None:
|
|
user.is_active = body.is_active
|
|
if authority_changed:
|
|
auth_mod.bump_token_version(user)
|
|
session.add(user)
|
|
session.commit()
|
|
session.refresh(user)
|
|
audit_service.record(
|
|
session, user=admin.username, action="user.update", target=user.username,
|
|
ip=_ip(request),
|
|
)
|
|
return user
|
|
|
|
|
|
@router.delete("/users/{user_id}")
|
|
def delete_user(
|
|
user_id: int,
|
|
request: Request,
|
|
session: Session = Depends(get_session),
|
|
admin: User = Depends(auth_mod.require_admin_session),
|
|
) -> dict:
|
|
user = session.get(User, user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
if user.id == admin.id:
|
|
raise HTTPException(status_code=400, detail="You cannot delete your own account")
|
|
if user.role == "admin":
|
|
other_admins = session.exec(
|
|
select(User).where(User.role == "admin", User.is_active == True, User.id != user_id) # noqa: E712
|
|
).first()
|
|
if not other_admins:
|
|
raise HTTPException(status_code=400, detail="Cannot delete the last active admin")
|
|
username = user.username
|
|
session.delete(user)
|
|
session.commit()
|
|
audit_service.record(
|
|
session, user=admin.username, action="user.delete", target=username,
|
|
ip=_ip(request),
|
|
)
|
|
return {"ok": True}
|