Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: gate LLM features for users without an assigned model

Ilia Avdeevb67376c49939
diff --git a/deeptutor/multi_user/access_guards.py b/deeptutor/multi_user/access_guards.py
new file mode 100644
index 000000000..fe9b2bbbd
--- /dev/null
+++ b/deeptutor/multi_user/access_guards.py
@@ -0,0 +1,51 @@
+"""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")
diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.py
index 621501a6f..83508d0c4 100644
--- a/deeptutor/multi_user/model_access.py
+++ b/deeptutor/multi_user/model_access.py
@@ -96,6 +96,22 @@ def allowed_llm_options() -> dict[str, Any]:
return {"active": None, "options": options}
+def has_capability_access(capability: str, user_id: str | None = None) -> bool:
+ """Whether the user has at least one usable model for ``capability``.
+
+ Admins are never gated — they manage the catalog directly. For ordinary
+ users this mirrors exactly what ``redacted_model_access`` exposes to the
+ frontend, so the server-side gate and the UI lock always agree.
+ """
+ user = get_current_user()
+ if user.is_admin:
+ return True
+ if user_id is None:
+ user_id = user.id
+ items = redacted_model_access(user_id).get(capability, []) or []
+ return any(item.get("available") for item in items)
+
+
def apply_allowed_llm_selection(selection: dict[str, Any] | None) -> dict[str, Any] | None:
"""Allow only admin-granted LLM profile/model selections for ordinary users."""
user = get_current_user()
diff --git a/web/app/(utility)/layout.tsx b/web/app/(utility)/layout.tsx
index 1f55e111d..d0e6afe36 100644
--- a/web/app/(utility)/layout.tsx
+++ b/web/app/(utility)/layout.tsx
@@ -1,4 +1,6 @@
import UtilitySidebar from "@/components/sidebar/UtilitySidebar";
+import { CapabilityAccessProvider } from "@/components/access/CapabilityAccessContext";
+import CapabilityGate from "@/components/access/CapabilityGate";
export default function UtilityLayout({
children,
@@ -6,11 +8,13 @@ export default function UtilityLayout({
children: React.ReactNode;
}>) {
return (
- <div className="flex h-screen overflow-hidden">
- <UtilitySidebar />
- <main className="flex-1 overflow-hidden bg-[var(--background)]">
- {children}
- </main>
- </div>
+ <CapabilityAccessProvider>
+ <div className="flex h-screen overflow-hidden">
+ <UtilitySidebar />
+ <main className="flex-1 overflow-hidden bg-[var(--background)]">
+ <CapabilityGate>{children}</CapabilityGate>
+ </main>
+ </div>
+ </CapabilityAccessProvider>
);
}
diff --git a/web/app/(workspace)/layout.tsx b/web/app/(workspace)/layout.tsx
index 280af4533..b6e425799 100644
--- a/web/app/(workspace)/layout.tsx
+++ b/web/app/(workspace)/layout.tsx
@@ -1,4 +1,6 @@
import WorkspaceSidebar from "@/components/sidebar/WorkspaceSidebar";
+import { CapabilityAccessProvider } from "@/components/access/CapabilityAccessContext";
+import CapabilityGate from "@/components/access/CapabilityGate";
import { UnifiedChatProvider } from "@/context/UnifiedChatContext";
export default function WorkspaceLayout({
@@ -7,13 +9,15 @@ export default function WorkspaceLayout({
children: React.ReactNode;
}>) {
return (
- <UnifiedChatProvider>
- <div className="flex h-screen overflow-hidden">
- <WorkspaceSidebar />
- <main className="flex-1 overflow-hidden bg-[var(--background)]">
- {children}
- </main>
- </div>
- </UnifiedChatProvider>
+ <CapabilityAccessProvider>
+ <UnifiedChatProvider>
+ <div className="flex h-screen overflow-hidden">
+ <WorkspaceSidebar />
+ <main className="flex-1 overflow-hidden bg-[var(--background)]">
+ <CapabilityGate>{children}</CapabilityGate>
+ </main>
+ </div>
+ </UnifiedChatProvider>
+ </CapabilityAccessProvider>
);
}
diff --git a/web/components/access/CapabilityAccessContext.tsx b/web/components/access/CapabilityAccessContext.tsx
new file mode 100644
index 000000000..f21c57983
--- /dev/null
+++ b/web/components/access/CapabilityAccessContext.tsx
@@ -0,0 +1,117 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useState,
+ type ReactNode,
+} from "react";
+
+import type { Capability } from "@/lib/capability-routes";
+import { apiFetch, apiUrl } from "@/lib/api";
+import { listLLMOptions } from "@/lib/llm-options";
+
+type CapabilityAccessValue = {
+ /** True until the first access probe resolves. */
+ loading: boolean;
+ /** Admins manage the catalog directly and are never gated. */
+ isAdmin: boolean;
+ /** Whether the current user has at least one usable LLM model. */
+ hasLlm: boolean;
+ /** Whether the current user may use a gated capability. */
+ has: (capability: Capability) => boolean;
+ /** Re-probe access (used on tab focus to pick up mid-session grant changes). */
+ refresh: () => Promise<void>;
+};
+
+// Default value keeps the hook safe outside a provider (e.g. shared components
+// rendered in the admin tree): everything reads as available, and the backend
+// remains the real enforcement boundary.
+const DEFAULT_VALUE: CapabilityAccessValue = {
+ loading: false,
+ isAdmin: true,
+ hasLlm: true,
+ has: () => true,
+ refresh: async () => {},
+};
+
+const CapabilityAccessContext =
+ createContext<CapabilityAccessValue>(DEFAULT_VALUE);
+
+export function useCapabilityAccess(): CapabilityAccessValue {
+ return useContext(CapabilityAccessContext);
+}
+
+export function CapabilityAccessProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ // Optimistic until the first probe resolves so we never flash a locked UI
+ // (admins and users-with-access stay unlocked; the backend enforces anyway).
+ const [isAdmin, setIsAdmin] = useState(true);
+ const [hasLlm, setHasLlm] = useState(true);
+ const [loading, setLoading] = useState(true);
+
+ const refresh = useCallback(async () => {
+ try {
+ // The settings payload only exposes the catalog to admins, so its
+ // presence is our admin signal — admins are never gated.
+ const res = await apiFetch(apiUrl("/api/v1/settings"));
+ if (!res.ok) return;
+ const payload = (await res.json()) as { catalog?: unknown };
+ if (payload.catalog) {
+ setIsAdmin(true);
+ setHasLlm(true);
+ return;
+ }
+ setIsAdmin(false);
+ // Non-admins: their grant-filtered LLM options decide access.
+ const { options } = await listLLMOptions();
+ setHasLlm(options.length > 0);
+ } catch {
+ // Keep last known state; the backend still enforces access on every call.
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ // Re-check when the user returns to the tab. This is what surfaces a
+ // mid-session revocation (admin removed the grant while the tab was open)
+ // without any polling — the next focus re-reads access and locks the UI.
+ useEffect(() => {
+ const onFocus = () => void refresh();
+ const onVisible = () => {
+ if (document.visibilityState === "visible") void refresh();
+ };
+ window.addEventListener("focus", onFocus);
+ document.addEventListener("visibilitychange", onVisible);
+ return () => {
+ window.removeEventListener("focus", onFocus);
+ document.removeEventListener("visibilitychange", onVisible);
+ };
+ }, [refresh]);
+
+ const has = useCallback(
+ (_capability: Capability): boolean => {
+ // Only LLM is gated today. Admins and the pre-load window are never gated.
+ if (isAdmin || loading) return true;
+ return hasLlm;
+ },
+ [isAdmin, loading, hasLlm],
+ );
+
+ return (
+ <CapabilityAccessContext.Provider
+ value={{ loading, isAdmin, hasLlm, has, refresh }}
+ >
+ {children}
+ </CapabilityAccessContext.Provider>
+ );
+}
diff --git a/web/components/access/CapabilityGate.tsx b/web/components/access/CapabilityGate.tsx
new file mode 100644
index 000000000..9e4123da1
--- /dev/null
+++ b/web/components/access/CapabilityGate.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+
+import { capabilityForPath } from "@/lib/capability-routes";
+
+import { RequireCapability } from "./RequireCapability";
+
+/**
+ * Route-level gate: derives the required model capability from the current
+ * pathname and locks the page when the user lacks it. Mounted once per authed
+ * layout group, so direct-URL access to a gated feature is covered too.
+ */
+export default function CapabilityGate({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const pathname = usePathname() ?? "";
+ const capability = capabilityForPath(pathname);
+ return (
+ <RequireCapability capability={capability}>{children}</RequireCapability>
+ );
+}
diff --git a/web/components/access/RequireCapability.tsx b/web/components/access/RequireCapability.tsx
new file mode 100644
index 000000000..9bc906b1d
--- /dev/null
+++ b/web/components/access/RequireCapability.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { Lock } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { CAPABILITY_LABEL, type Capability } from "@/lib/capability-routes";
+
+import { useCapabilityAccess } from "./CapabilityAccessContext";
+
+/**
+ * Full-surface "this feature is locked" notice. Shown in place of a feature
+ * page when the current user lacks the required model capability. Never hides
+ * the feature — it explains why it is unavailable and what to do.
+ */
+export function LockedFeatureNotice({
+ capability,
+}: {
+ capability: Capability;
+}) {
+ const { t } = useTranslation();
+ const modelLabel = t(CAPABILITY_LABEL[capability]);
+
+ return (
+ <div className="flex h-full w-full items-center justify-center p-6">
+ <div className="flex max-w-md flex-col items-center gap-4 rounded-2xl border border-[var(--border)] bg-[var(--secondary)]/40 px-8 py-10 text-center">
+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--background)] text-[var(--muted-foreground)]">
+ <Lock size={20} strokeWidth={1.8} />
+ </div>
+ <h2 className="text-base font-semibold text-[var(--foreground)]">
+ {t("Feature locked")}
+ </h2>
+ <p className="text-sm leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Your account doesn't have {{model}} assigned yet. Please contact your administrator to get access.",
+ { model: modelLabel },
+ )}
+ </p>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Renders {children} only when the user has the required capability; otherwise
+ * renders the locked notice. Pass capability=null to never gate.
+ */
+export function RequireCapability({
+ capability,
+ children,
+}: {
+ capability: Capability | null;
+ children: React.ReactNode;
+}) {
+ const { has } = useCapabilityAccess();
+ if (capability && !has(capability)) {
+ return <LockedFeatureNotice capability={capability} />;
+ }
+ return <>{children}</>;
+}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 461ff9b99..517431b51 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -15,6 +15,7 @@ import {
HeartHandshake,
LayoutGrid,
Library,
+ Lock,
MessageSquare,
PanelLeftClose,
PanelLeftOpen,
@@ -27,12 +28,16 @@ import SessionList from "@/components/SessionList";
import { VersionBadge } from "@/components/sidebar/VersionBadge";
import type { SessionSummary } from "@/lib/session-api";
import { Tooltip } from "@/components/ui/Tooltip";
+import { useCapabilityAccess } from "@/components/access/CapabilityAccessContext";
+import type { Capability } from "@/lib/capability-routes";
interface NavEntry {
href: string;
label: string;
icon: LucideIcon;
tooltipKey?: string;
+ /** Model capability this feature needs; locked when the user lacks it. */
+ requires?: Capability;
}
const PRIMARY_NAV: NavEntry[] = [
@@ -41,21 +46,32 @@ const PRIMARY_NAV: NavEntry[] = [
label: "Chat",
icon: MessageSquare,
tooltipKey: "Chat tooltip",
+ requires: "llm",
},
{
href: "/partners",
label: "Partners",
icon: HeartHandshake,
tooltipKey: "Partners tooltip",
+ requires: "llm",
},
{
href: "/co-writer",
label: "Co-Writer",
icon: PenLine,
tooltipKey: "Co-Writer tooltip",
+ requires: "llm",
},
- { href: "/book", label: "Book", icon: Library, tooltipKey: "Book tooltip" },
{
+ href: "/book",
+ label: "Book",
+ icon: Library,
+ tooltipKey: "Book tooltip",
+ requires: "llm",
+ },
+ {
+ // Knowledge stays reachable even without an embedding model so users can
+ // see existing knowledge bases; the page itself renders them locked.
href: "/knowledge",
label: "Knowledge",
icon: BookOpen,
@@ -66,6 +82,7 @@ const PRIMARY_NAV: NavEntry[] = [
label: "Mastery Path",
icon: GraduationCap,
tooltipKey: "Mastery Path tooltip",
+ requires: "llm",
},
{
href: "/space",
@@ -115,8 +132,13 @@ export function SidebarShell({
const pathname = usePathname();
const router = useRouter();
const { t } = useTranslation();
+ const { has } = useCapabilityAccess();
const { sidebarCollapsed: collapsed, setSidebarCollapsed: setCollapsed } =
useAppShell();
+
+ const navLocked = (item: NavEntry) =>
+ item.requires ? !has(item.requires) : false;
+ const lockedTooltip = t("Locked — contact your administrator to get access.");
const [recentsCollapsed, setRecentsCollapsed] = useState(false);
// Hydrate Recents collapse from localStorage after first render to stay SSR-safe.
@@ -181,9 +203,35 @@ export function SidebarShell({
<nav className="mt-1 flex w-full flex-col items-center gap-1 px-1.5">
{PRIMARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
- const description = item.tooltipKey
- ? t(item.tooltipKey)
- : undefined;
+ const locked = navLocked(item);
+ const description = locked
+ ? lockedTooltip
+ : item.tooltipKey
+ ? t(item.tooltipKey)
+ : undefined;
+ if (locked) {
+ return (
+ <Tooltip
+ key={item.href}
+ label={t(item.label)}
+ description={description}
+ side="right"
+ >
+ <div
+ aria-label={`${t(item.label)} — ${lockedTooltip}`}
+ aria-disabled
+ className="relative flex h-9 w-9 cursor-not-allowed items-center justify-center rounded-xl text-[var(--muted-foreground)]/40"
+ >
+ <item.icon size={18} strokeWidth={1.6} />
+ <Lock
+ size={10}
+ strokeWidth={2}
+ className="absolute bottom-1 right-1 text-[var(--muted-foreground)]/70"
+ />
+ </div>
+ </Tooltip>
+ );
+ }
return (
<Tooltip
key={item.href}
@@ -299,6 +347,27 @@ export function SidebarShell({
<div className="space-y-px">
{PRIMARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
+ const locked = navLocked(item);
+ if (locked) {
+ return (
+ <Tooltip
+ key={item.href}
+ label={t(item.label)}
+ description={lockedTooltip}
+ side="right"
+ >
+ <div
+ aria-label={`${t(item.label)} — ${lockedTooltip}`}
+ aria-disabled
+ className="flex cursor-not-allowed items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] text-[var(--muted-foreground)]/40"
+ >
+ <item.icon size={16} strokeWidth={1.5} />
+ <span>{t(item.label)}</span>
+ <Lock size={13} strokeWidth={1.8} className="ml-auto" />
+ </div>
+ </Tooltip>
+ );
+ }
return (
<Link
key={item.href}
diff --git a/web/lib/capability-routes.ts b/web/lib/capability-routes.ts
new file mode 100644
index 000000000..e9c1bfc23
--- /dev/null
+++ b/web/lib/capability-routes.ts
@@ -0,0 +1,42 @@
+/**
+ * Model capability a feature depends on. As of the multi-user release, the only
+ * per-user-grantable model capability is the LLM — embedding/search are shared
+ * admin infrastructure and are never gated per user.
+ */
+export type Capability = "llm";
+
+/**
+ * Single source of truth mapping a workspace feature route to the model
+ * capability it needs in order to function. Features absent from this list
+ * require no per-user model and are always available (Knowledge, Space,
+ * Memory, Notebook, Settings, …).
+ *
+ * Both the sidebar (to lock nav items) and the route-level CapabilityGate
+ * (to lock the page itself) read from here, so a new gated feature only has
+ * to be declared once.
+ */
+export const ROUTE_CAPABILITIES: ReadonlyArray<{
+ prefix: string;
+ capability: Capability;
+}> = [
+ { prefix: "/chat", capability: "llm" },
+ { prefix: "/partners", capability: "llm" },
+ { prefix: "/co-writer", capability: "llm" },
+ { prefix: "/book", capability: "llm" },
+ { prefix: "/learning", capability: "llm" }, // Mastery Path
+ { prefix: "/playground", capability: "llm" },
+];
+
+/** Returns the capability required for a pathname, or null if none is needed. */
+export function capabilityForPath(pathname: string): Capability | null {
+ const match = ROUTE_CAPABILITIES.find((r) => pathname.startsWith(r.prefix));
+ return match ? match.capability : null;
+}
+
+/**
+ * Human-facing phrase for a capability, used in the "ask your admin" copy.
+ * Kept as plain English keys so react-i18next can translate them later.
+ */
+export const CAPABILITY_LABEL: Record<Capability, string> = {
+ llm: "an LLM model",
+};