refactor: reuse single LLM gate in turn runtime; drop unwired guard

The turn path (chat/partners/mastery via turn_runtime) already enforces
LLM-grant access at its single enforcement point and surfaces a clear
terminal "no model assigned" rejection — so require_llm_access was never
wired to any endpoint and only duplicated that logic. Drop it (and its
guard-only tests) and have turn_runtime reuse has_capability_access, giving
the gate one source of truth shared with the frontend lock.

Frontend fixes kept from the original PR plus two corrections:
- capabilityForPath now matches on a path-segment boundary, so a sibling
  route like /booket can't be swallowed by the /book prefix (+ regression).
- fix the misleading Knowledge sidebar comment — Knowledge needs no
  per-user grant and is never gated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bingxi Zhao (Frank)
2026-06-14 14:56:14 +08:00
parent a40a525a1d
commit d5c6d6ba54
6 changed files with 36 additions and 110 deletions

View File

@@ -1,51 +0,0 @@
"""Reusable FastAPI dependency that gates endpoints on LLM-capability access.
A user with no granted LLM model cannot meaningfully use a feature that depends
on one. This guard turns that into an explicit, typed ``403``
(``code: "NO_MODEL_ACCESS"``) instead of a confusing downstream failure, and it
mirrors :func:`has_capability_access` so the server-side gate agrees with the
frontend lock.
Attach at the endpoint (or router) that actually consumes an LLM::
@router.post("/run", dependencies=[Depends(require_llm_access)])
Admins always pass (they manage the catalog directly).
Note: as of the multi-user release only the LLM capability is grantable per
user — embedding/search are shared admin infrastructure and are not gated.
"""
from __future__ import annotations
from fastapi import Depends, HTTPException, status
from deeptutor.api.routers.auth import require_auth
from deeptutor.services.auth import TokenPayload
from .model_access import has_capability_access
def _require(capability: str) -> None:
if has_capability_access(capability):
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
"code": "NO_MODEL_ACCESS",
"capability": capability,
"message": (
"Your account doesn't have an LLM model assigned. "
"Please contact your administrator."
),
},
)
async def require_llm_access(
_: TokenPayload | None = Depends(require_auth),
) -> None:
# ``Depends(require_auth)`` keeps the same ordering guarantees as
# ``require_admin``: the user ContextVar is installed before the guard reads
# it.
_require("llm")

View File

@@ -721,19 +721,26 @@ class TurnRuntimeManager:
# configured from admin runtime settings). Admin keeps the existing behavior
# (None llm_selection → default config from admin scope).
from deeptutor.multi_user.context import get_current_user
from deeptutor.multi_user.model_access import redacted_model_access
from deeptutor.multi_user.model_access import (
has_capability_access,
redacted_model_access,
)
current_user = get_current_user()
if not current_user.is_admin:
# Single gate, shared with the frontend lock and any HTTP
# surface: no usable LLM grant → a clear terminal error here
# instead of a silent fall-through to the global client.
if not has_capability_access("llm"):
raise RuntimeError(
"No LLM model is assigned to your account. Please contact an administrator."
)
# Pin the first granted-and-available model as the selection.
assigned_llms = [
item
for item in redacted_model_access(current_user.id).get("llm", [])
if item.get("available")
]
if not assigned_llms:
raise RuntimeError(
"No LLM model is assigned to your account. Please contact an administrator."
)
llm_selection = {
"profile_id": assigned_llms[0].get("profile_id"),
"model_id": assigned_llms[0].get("model_id"),

View File

@@ -1,15 +1,11 @@
"""Tests for capability-based access: has_capability_access + require_llm_access.
"""Tests for capability-based access: has_capability_access.
As of the multi-user release only the LLM capability is grantable per user, so
gating is LLM-only; embedding/search are shared admin infrastructure.
gating is LLM-only; embedding/search are shared admin infrastructure. The same
helper backs the turn-runtime gate and the frontend lock, so they always agree.
"""
import asyncio
from fastapi import HTTPException
import pytest
from deeptutor.multi_user import access_guards, model_access
from deeptutor.multi_user import model_access
from deeptutor.multi_user.context import reset_current_user, set_current_user
from deeptutor.multi_user.models import CurrentUser, UserScope
@@ -33,9 +29,6 @@ def _fake_access(llm=None):
return lambda _user_id=None: {"llm": list(llm or [])}
# ── has_capability_access ────────────────────────────────────────────────
def test_admin_always_has_access(tmp_path, monkeypatch):
# Admins are never gated and must not even consult the grant view.
def _boom(_user_id=None):
@@ -83,42 +76,3 @@ def test_user_with_empty_grant_has_no_access(tmp_path, monkeypatch):
assert model_access.has_capability_access("llm") is False
finally:
reset_current_user(token)
# ── require_llm_access guard ─────────────────────────────────────────────
def test_guard_raises_typed_403_when_missing(tmp_path, monkeypatch):
monkeypatch.setattr(model_access, "redacted_model_access", _fake_access())
token = set_current_user(make_user(tmp_path, role="user"))
try:
with pytest.raises(HTTPException) as exc:
asyncio.run(access_guards.require_llm_access(None))
assert exc.value.status_code == 403
assert exc.value.detail["code"] == "NO_MODEL_ACCESS"
assert exc.value.detail["capability"] == "llm"
finally:
reset_current_user(token)
def test_guard_passes_when_capability_available(tmp_path, monkeypatch):
monkeypatch.setattr(
model_access,
"redacted_model_access",
_fake_access(llm=[{"profile_id": "p", "model_id": "m", "available": True}]),
)
token = set_current_user(make_user(tmp_path, role="user"))
try:
# Should not raise.
assert asyncio.run(access_guards.require_llm_access(None)) is None
finally:
reset_current_user(token)
def test_guard_passes_for_admin(tmp_path, monkeypatch):
monkeypatch.setattr(model_access, "redacted_model_access", _fake_access())
token = set_current_user(make_user(tmp_path, role="admin"))
try:
assert asyncio.run(access_guards.require_llm_access(None)) is None
finally:
reset_current_user(token)

View File

@@ -70,8 +70,8 @@ const PRIMARY_NAV: NavEntry[] = [
requires: "llm",
},
{
// Knowledge stays reachable even without an embedding model so users can
// see existing knowledge bases; the page itself renders them locked.
// Knowledge needs no per-user model grant (embedding/search are shared
// admin infrastructure), so it stays reachable and is never gated.
href: "/knowledge",
label: "Knowledge",
icon: BookOpen,

View File

@@ -27,9 +27,15 @@ export const ROUTE_CAPABILITIES: ReadonlyArray<{
{ prefix: "/playground", capability: "llm" },
];
/** Returns the capability required for a pathname, or null if none is needed. */
/**
* Returns the capability required for a pathname, or null if none is needed.
* Matches on a path-segment boundary (exact, or prefix followed by "/") so a
* sibling route like "/booket" can never be swallowed by the "/book" prefix.
*/
export function capabilityForPath(pathname: string): Capability | null {
const match = ROUTE_CAPABILITIES.find((r) => pathname.startsWith(r.prefix));
const match = ROUTE_CAPABILITIES.find(
(r) => pathname === r.prefix || pathname.startsWith(`${r.prefix}/`),
);
return match ? match.capability : null;
}

View File

@@ -20,6 +20,16 @@ test("capabilityForPath matches nested routes by prefix", () => {
assert.equal(capabilityForPath("/learning/book-1"), "llm");
});
test("capabilityForPath matches on a segment boundary, not a bare prefix", () => {
// A sibling route must never be swallowed by a shorter gated prefix.
assert.equal(capabilityForPath("/booket"), null);
assert.equal(capabilityForPath("/chatter"), null);
assert.equal(capabilityForPath("/playgrounds-xyz"), null);
// The gated route itself and its children still match.
assert.equal(capabilityForPath("/book"), "llm");
assert.equal(capabilityForPath("/book/123"), "llm");
});
test("capabilityForPath returns null for ungated routes", () => {
// Knowledge is ungated: embedding is shared admin infra, not per-user.
assert.equal(capabilityForPath("/knowledge"), null);