feat(api): personal API tokens and the AI access page
First step of milestone 461 (MCP server). A token is the credential an MCP client presents as `Authorization: Bearer stw_…` to act as its user. - api_tokens table (0026): sha256 hash only, display prefix, role ceiling, expiry, revocation, throttled last_used_at. - steward/core/api_tokens.py: mint, list, revoke, resolve. Resolution re-reads the user's current role and acts with the lower of that and the token's ceiling, so demoting or disabling a user weakens or kills their tokens with nothing to revoke by hand. - /ai-access/ (sidebar → Automation → AI access): every user manages their own tokens, can't grant above their own role, sees the token once. Session-only: a share-link viewer is refused. Create and revoke are audited. - Integration tests drive the routes against real Postgres so their transactions run for real (#884 escaped CI behind a mocked session). Task #4965 "MCP-1 — Personal API tokens". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
"""AI access: personal API tokens for MCP clients.
|
||||
|
||||
Every logged-in user manages their own tokens here, whatever their role — a
|
||||
token acts as its user, capped at the role it was given. These routes are
|
||||
session-only: a share-link viewer has no user to mint tokens for, and no token
|
||||
can reach them (MCP tools never mint or revoke tokens).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from quart import Blueprint, abort, current_app, redirect, render_template, request
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.auth.middleware import current_user_id, require_role
|
||||
from steward.core import api_tokens
|
||||
from steward.core.audit import log_audit
|
||||
from steward.models.users import User, UserRole
|
||||
|
||||
ai_access_bp = Blueprint("ai_access", __name__, url_prefix="/ai-access")
|
||||
|
||||
_EXPIRY_CHOICES = [("", "Never"), ("30", "30 days"), ("90", "90 days"), ("365", "1 year")]
|
||||
|
||||
|
||||
async def _session_user(db) -> User:
|
||||
user_id = current_user_id()
|
||||
if not user_id:
|
||||
abort(403)
|
||||
user = (await db.execute(select(User).where(User.id == user_id))).scalar_one_or_none()
|
||||
if user is None or not user.is_active:
|
||||
abort(403)
|
||||
return user
|
||||
|
||||
|
||||
async def _render_index(db, user: User, *, error: str | None = None, status: int = 200):
|
||||
tokens = await api_tokens.list_tokens(db, user.id)
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = [{"token": t, "state": api_tokens.token_state(t, now)} for t in tokens]
|
||||
body = await render_template(
|
||||
"ai_access/index.html",
|
||||
rows=rows,
|
||||
user_role=user.role,
|
||||
grantable=api_tokens.grantable_roles(user.role),
|
||||
expiry_choices=_EXPIRY_CHOICES,
|
||||
error=error,
|
||||
)
|
||||
return body, status
|
||||
|
||||
|
||||
@ai_access_bp.get("/")
|
||||
@require_role(UserRole.viewer)
|
||||
async def index():
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
user = await _session_user(db)
|
||||
return await _render_index(db, user)
|
||||
|
||||
|
||||
@ai_access_bp.post("/tokens")
|
||||
@require_role(UserRole.viewer)
|
||||
async def create():
|
||||
form = await request.form
|
||||
name = form.get("name", "")
|
||||
expires = form.get("expires_in_days", "")
|
||||
try:
|
||||
role = UserRole(form.get("role", UserRole.viewer.value))
|
||||
except ValueError:
|
||||
role = None
|
||||
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
user = await _session_user(db)
|
||||
if role is None:
|
||||
return await _render_index(db, user, error="Pick a role for the token.", status=400)
|
||||
try:
|
||||
raw, token = await api_tokens.create_token(
|
||||
db, user_id=user.id, user_role=user.role, name=name, role=role,
|
||||
expires_in_days=int(expires) if expires.isdigit() and int(expires) > 0 else None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return await _render_index(db, user, error=str(exc), status=400)
|
||||
await db.commit()
|
||||
|
||||
await log_audit(current_app, user.id, user.username, "api_token.create",
|
||||
entity_type="api_token", entity_id=str(token.id),
|
||||
detail={"name": token.name, "role": token.role.value})
|
||||
return await render_template("ai_access/created.html", raw_token=raw, token=token)
|
||||
|
||||
|
||||
@ai_access_bp.post("/tokens/<int:token_id>/revoke")
|
||||
@require_role(UserRole.viewer)
|
||||
async def revoke(token_id: int):
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
user = await _session_user(db)
|
||||
token = await api_tokens.revoke_token(db, user_id=user.id, token_id=token_id)
|
||||
await db.commit()
|
||||
if token is None:
|
||||
abort(404)
|
||||
await log_audit(current_app, user.id, user.username, "api_token.revoke",
|
||||
entity_type="api_token", entity_id=str(token_id),
|
||||
detail={"name": token.name})
|
||||
return redirect("/ai-access/")
|
||||
Reference in New Issue
Block a user