Files
menzeljandClaude Opus 5 e650aa6833
CI / check (push) Successful in 12m31s
CI / build-and-push (push) Successful in 1m56s
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>
2026-09-18 00:53:58 +02:00

135 lines
4.5 KiB
Python

"""Long-lived API tokens for scripts and CI.
A session token is the wrong credential for automation: it expires in an hour,
it is minted by typing a password, and revoking it means signing every one of
that person's devices out. So a CI job gets its own credential, which can be
revoked on its own, is capped to read-only if that is all it needs, and shows up
in the audit log as itself.
**Only a hash is stored.** Unlike a registry password — which has to be handed
back to the registry, so it is encrypted and recoverable — a token is only ever
compared against. It is shown once at creation and cannot be recovered, which is
the difference between leaking the database and leaking everything it protects.
The hash is a plain SHA-256 and deliberately not bcrypt. Bcrypt is slow on
purpose, to make guessing low-entropy human passwords expensive; a token is 256
bits of ``secrets`` output, where guessing is not the threat and the cost would
instead land on every single API request.
"""
from __future__ import annotations
import hashlib
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
from sqlmodel import Session, select
from models.api_token import ApiToken
from models.user import User
#: Marks a StackPilot token at a glance — in a log, in a CI settings page, or to
#: a secret scanner. It is also how the auth dependency tells a token from a JWT
#: without trying to decode it.
PREFIX = "sp_"
#: How stale last_used_at may get before a request writes it again. Without a
#: floor this would be a database write on every single API call.
_TOUCH_INTERVAL = timedelta(minutes=5)
def looks_like_token(value: str) -> bool:
return (value or "").startswith(PREFIX)
def _hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _aware(value: Optional[datetime]) -> Optional[datetime]:
"""SQLite hands back naive datetimes; compare them as UTC."""
if value is None:
return None
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
def is_expired(row: ApiToken, now: Optional[datetime] = None) -> bool:
expires = _aware(row.expires_at)
if expires is None:
return False
return expires <= (now or datetime.now(timezone.utc))
def mint(
session: Session,
*,
name: str,
user: User,
scope: str = "read",
expires_in_days: Optional[int] = None,
) -> tuple[ApiToken, str]:
"""Create a token. Returns the row and the secret, which is shown once."""
token = PREFIX + secrets.token_urlsafe(32)
expires_at = (
datetime.now(timezone.utc) + timedelta(days=expires_in_days)
if expires_in_days
else None
)
row = ApiToken(
name=name,
prefix=token[: len(PREFIX) + 8],
token_hash=_hash(token),
scope=scope if scope in ("read", "admin") else "read",
user_id=user.id,
expires_at=expires_at,
)
session.add(row)
session.commit()
session.refresh(row)
return row, token
def resolve(session: Session, token: str) -> Optional[tuple[ApiToken, User]]:
"""The token row and its owner, or None if it cannot be used.
None covers every reason equally — unknown, expired, owner disabled — so a
caller cannot learn which by watching the responses.
"""
if not looks_like_token(token):
return None
prefix = token[: len(PREFIX) + 8]
row = session.exec(select(ApiToken).where(ApiToken.prefix == prefix)).first()
if not row:
return None
# Constant-time, so a wrong token cannot be narrowed down by timing.
if not secrets.compare_digest(row.token_hash, _hash(token)):
return None
if is_expired(row):
return None
user = session.get(User, row.user_id)
if not user or not user.is_active:
return None
return row, user
def effective_role(row: ApiToken, user: User) -> str:
"""What this token may do, which is never more than its owner may.
A token keeps working when its owner is demoted, but drops to read-only with
them — the alternative is an admin token outliving the admin.
"""
if row.scope == "admin" and user.role == "admin":
return "admin"
return "user"
def touch(session: Session, row: ApiToken) -> None:
"""Record that the token was used, at most once every few minutes."""
now = datetime.now(timezone.utc)
last = _aware(row.last_used_at)
if last and now - last < _TOUCH_INTERVAL:
return
row.last_used_at = now
session.add(row)
session.commit()