Add API tokens for scripts and CI (0.57.0)
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>
This commit is contained in:
@@ -231,7 +231,7 @@ def _ip(request: Request) -> str:
|
||||
@router.get("/users", response_model=list[UserRead])
|
||||
def list_users(
|
||||
session: Session = Depends(get_session),
|
||||
_admin: User = Depends(auth_mod.require_admin),
|
||||
_admin: User = Depends(auth_mod.require_admin_session),
|
||||
) -> list[User]:
|
||||
return session.exec(select(User).order_by(User.id)).all()
|
||||
|
||||
@@ -241,7 +241,7 @@ def create_user(
|
||||
body: UserCreate,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
admin: User = Depends(auth_mod.require_admin),
|
||||
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")
|
||||
@@ -269,7 +269,7 @@ def update_user(
|
||||
body: UserUpdate,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
admin: User = Depends(auth_mod.require_admin),
|
||||
admin: User = Depends(auth_mod.require_admin_session),
|
||||
) -> User:
|
||||
user = session.get(User, user_id)
|
||||
if not user:
|
||||
@@ -316,7 +316,7 @@ def delete_user(
|
||||
user_id: int,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
admin: User = Depends(auth_mod.require_admin),
|
||||
admin: User = Depends(auth_mod.require_admin_session),
|
||||
) -> dict:
|
||||
user = session.get(User, user_id)
|
||||
if not user:
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""API tokens for scripts and CI.
|
||||
|
||||
Managing tokens needs a signed-in session, never another API token: a leaked CI
|
||||
credential should be able to do the job it was issued for, not mint itself a
|
||||
second one that survives the first being revoked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from auth import require_admin_session
|
||||
from database import get_session
|
||||
from models.api_token import (
|
||||
SCOPES,
|
||||
ApiToken,
|
||||
ApiTokenCreate,
|
||||
ApiTokenCreated,
|
||||
ApiTokenRead,
|
||||
)
|
||||
from models.user import User
|
||||
from services import api_token_service, audit_service
|
||||
|
||||
router = APIRouter(prefix="/api/auth/tokens", tags=["auth"])
|
||||
|
||||
|
||||
def _ip(request: Request) -> str:
|
||||
return request.client.host if request.client else "unknown"
|
||||
|
||||
|
||||
def _to_read(row: ApiToken, session: Session) -> ApiTokenRead:
|
||||
owner = session.get(User, row.user_id)
|
||||
return ApiTokenRead(
|
||||
id=row.id,
|
||||
name=row.name,
|
||||
prefix=row.prefix,
|
||||
scope=row.scope,
|
||||
username=owner.username if owner else "(deleted)",
|
||||
expires_at=row.expires_at,
|
||||
last_used_at=row.last_used_at,
|
||||
created_at=row.created_at,
|
||||
expired=api_token_service.is_expired(row),
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=list[ApiTokenRead])
|
||||
def list_tokens(
|
||||
session: Session = Depends(get_session),
|
||||
_user: User = Depends(require_admin_session),
|
||||
) -> list[ApiTokenRead]:
|
||||
rows = session.exec(select(ApiToken).order_by(ApiToken.created_at.desc())).all()
|
||||
return [_to_read(r, session) for r in rows]
|
||||
|
||||
|
||||
@router.post("", response_model=ApiTokenCreated, status_code=201)
|
||||
def create_token(
|
||||
body: ApiTokenCreate,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
user: User = Depends(require_admin_session),
|
||||
) -> ApiTokenCreated:
|
||||
name = (body.name or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="A name is required")
|
||||
if body.scope not in SCOPES:
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"Scope must be one of {', '.join(SCOPES)}"
|
||||
)
|
||||
if body.expires_in_days is not None and body.expires_in_days < 1:
|
||||
raise HTTPException(status_code=400, detail="Expiry must be at least a day")
|
||||
|
||||
row, token = api_token_service.mint(
|
||||
session,
|
||||
name=name,
|
||||
user=user,
|
||||
scope=body.scope,
|
||||
expires_in_days=body.expires_in_days,
|
||||
)
|
||||
audit_service.record(
|
||||
session, user=user.username, action="token.create", target=row.prefix,
|
||||
detail=f"{name} ({row.scope})", ip=_ip(request),
|
||||
)
|
||||
# The only time the token itself is ever returned.
|
||||
return ApiTokenCreated(**_to_read(row, session).model_dump(), token=token)
|
||||
|
||||
|
||||
@router.delete("/{token_id}")
|
||||
def revoke_token(
|
||||
token_id: int,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
user: User = Depends(require_admin_session),
|
||||
) -> dict:
|
||||
row = session.get(ApiToken, token_id)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail=f"Token {token_id} not found")
|
||||
prefix = row.prefix
|
||||
session.delete(row)
|
||||
session.commit()
|
||||
audit_service.record(
|
||||
session, user=user.username, action="token.revoke", target=prefix,
|
||||
detail=row.name, ip=_ip(request),
|
||||
)
|
||||
return {"ok": True}
|
||||
Reference in New Issue
Block a user