Harden auth scopes, SQL/WebCRT gates, and per-install JWT secrets.

Add capability RBAC, Alembic bootstrap, optional worker schedulers, and close public docs by default so lab installs stay usable without shared signing keys.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
oliver 2026-08-02 16:24:34 +08:00
parent cb8e0d23c5
commit 633a9d55bd
38 changed files with 1808 additions and 452 deletions

View file

@ -11,6 +11,7 @@ from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from .auth_deps import resolve_user_from_token
from .auth_scopes import has_scope, required_scope_for_request
from .auth_service import write_audit
from .config import settings
from .db import SessionLocal
@ -21,25 +22,31 @@ _PUBLIC_EXACT = frozenset(
{
"/",
"/health",
"/openapi.json",
"/docs",
"/docs/oauth2-redirect",
"/redoc",
"/health/live",
"/health/ready",
"/favicon.ico",
"/v1/auth/login",
}
)
_PUBLIC_PREFIXES = (
"/docs",
"/redoc",
"/assets",
)
def _docs_public() -> bool:
return bool(getattr(settings, "docs_enabled", False))
def _is_public(path: str) -> bool:
p = str(path or "")
if p in _PUBLIC_EXACT:
return True
if _docs_public() and (
p in ("/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc")
or p.startswith("/docs")
or p.startswith("/redoc")
):
return True
return any(p.startswith(pref) for pref in _PUBLIC_PREFIXES)
@ -82,7 +89,9 @@ class AuthAuditMiddleware(BaseHTTPMiddleware):
auth = str(request.headers.get("authorization") or "").strip()
if auth.lower().startswith("bearer "):
token = auth[7:].strip()
if not token:
# Query access_token: only allow for non-webcrt paths as deprecated fallback;
# WebCRT HTTP must use Authorization header (see webcrt_router).
if not token and not path.startswith("/v1/webcrt"):
token = str(request.query_params.get("access_token") or "").strip()
db = SessionLocal()
@ -100,9 +109,35 @@ class AuthAuditMiddleware(BaseHTTPMiddleware):
detail={},
)
return JSONResponse(status_code=401, content={"detail": "unauthorized"})
user, via = resolved
user, via, scopes, token_id = resolved
need = required_scope_for_request(request.method, path)
if need and not has_scope(scopes, need):
write_audit(
db,
action="auth.forbidden_scope",
actor_user_id=str(user.id),
actor_username=str(user.username),
method=request.method,
path=path,
status_code=403,
client_ip=_client_ip(request),
user_agent=str(request.headers.get("user-agent") or "")[:512],
detail={"required": need, "granted": sorted(scopes), "auth_via": via},
)
return JSONResponse(
status_code=403,
content={
"detail": {
"error": "insufficient_scope",
"required": [need],
"granted": sorted(scopes),
}
},
)
request.state.auth_user = user
request.state.auth_via = via
request.state.auth_scopes = scopes
request.state.auth_api_token_id = token_id
actor_id = str(user.id)
actor_name = str(user.username)
auth_via = via
@ -115,25 +150,22 @@ class AuthAuditMiddleware(BaseHTTPMiddleware):
started = time.perf_counter()
response = await call_next(request)
try:
db2 = SessionLocal()
try:
write_audit(
db2,
action=_action_for(request.method, path),
actor_user_id=actor_id,
actor_username=actor_name,
method=request.method,
path=path,
status_code=int(response.status_code),
client_ip=_client_ip(request),
user_agent=str(request.headers.get("user-agent") or "")[:512],
detail={
"auth_via": auth_via,
"elapsed_ms": int((time.perf_counter() - started) * 1000),
},
)
finally:
db2.close()
from .audit_async import enqueue_audit
enqueue_audit(
action=_action_for(request.method, path),
actor_user_id=actor_id,
actor_username=actor_name,
method=request.method,
path=path,
status_code=int(response.status_code),
client_ip=_client_ip(request),
user_agent=str(request.headers.get("user-agent") or "")[:512],
detail={
"auth_via": auth_via,
"elapsed_ms": int((time.perf_counter() - started) * 1000),
},
)
except Exception:
_log.exception("audit write after request failed path=%s", path)
_log.exception("audit enqueue after request failed path=%s", path)
return response