Skip to content

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

fix(multi-user): scope learner KB reads and persist grants before preset

Bingxi Zhao (Frank)6ac8deed5115
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 45630dd47..9b6776e8f 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -469,7 +469,21 @@ async def require_admin(
return payload
-def _learning_surface_for_path(path: str, method: str = "GET") -> str:
+_LEARNER_KB_READ_ROUTES = frozenset(
+ {
+ "/api/knowledge-bases",
+ "/api/knowledge-bases/{kb_name}",
+ "/api/knowledge-bases/{kb_name}/files",
+ "/api/knowledge-bases/{kb_name}/files/{filename:path}",
+ "/api/knowledge-bases/{kb_name}/file-preview-text/{filename:path}",
+ "/api/knowledge-bases/{kb_name}/progress",
+ }
+)
+
+
+def _learning_surface_for_path(
+ path: str, method: str = "GET", *, route_path: str | None = None
+) -> str:
normalized = "/" + str(path or "").lstrip("/")
for root, surface in (
("/api/reading", "reading"),
@@ -485,11 +499,12 @@ def _learning_surface_for_path(path: str, method: str = "GET") -> str:
):
if normalized == root or normalized.startswith(f"{root}/"):
return surface
- # Knowledge-center browsing is a legitimate learner activity, but KB
- # mutations affect shared/admin-owned resources — read-only methods only.
- if method.upper() in ("GET", "HEAD", "OPTIONS") and (
- normalized == "/api/knowledge-bases"
- or normalized.startswith("/api/knowledge-bases/")
+ # Match the resolved route template, not just the URL prefix: this keeps
+ # admin diagnostics and engine configuration GETs out of the learner shell.
+ if (
+ method.upper() == "GET"
+ and (normalized == "/api/knowledge-bases" or normalized.startswith("/api/knowledge-bases/"))
+ and route_path in _LEARNER_KB_READ_ROUTES
):
return "reading"
return ""
@@ -503,7 +518,14 @@ async def require_learning_surface(
from deeptutor.multi_user.learning_access import assert_learning_surface
try:
- assert_learning_surface(_learning_surface_for_path(request.url.path, request.method))
+ route = request.scope.get("route")
+ assert_learning_surface(
+ _learning_surface_for_path(
+ request.url.path,
+ request.method,
+ route_path=getattr(route, "path", None),
+ )
+ )
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/deeptutor/api/routers/multi_user.py b/deeptutor/api/routers/multi_user.py
index 055ff80f6..7d12576fb 100644
--- a/deeptutor/api/routers/multi_user.py
+++ b/deeptutor/api/routers/multi_user.py
@@ -657,7 +657,7 @@ async def put_guardian_restrictions(
payload: GuardianRestrictionsPayload,
current: object = Depends(require_auth),
) -> dict[str, Any]:
- _learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(
+ learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(
current, learner_user_id, "manage_restrictions"
)
available_extensions = {
@@ -673,14 +673,10 @@ async def put_guardian_restrictions(
policy = grant.get("learning_policy")
if not isinstance(policy, dict):
# Assigning guardian restrictions is what makes an account a learning
- # account. Seed the default learning policy and flip the preset to
- # "learner" so the frontend renders the scoped learner shell instead
- # of the full app (a `standard` preset + `learning_policy` mix makes
- # the client load admin surfaces that all default-deny to 403, #1222).
+ # account. Seed the default learning policy; the preset is switched
+ # only after the updated grant has passed validation and been saved.
grant = deepcopy(learner_grant(learner_user_id))
policy = grant.get("learning_policy")
- if isinstance(policy, dict) and _learner_username:
- set_preset(_learner_username, "learner")
if not isinstance(policy, dict):
raise HTTPException(status_code=409, detail="Learner account has no learning policy")
reading = policy.get("reading")
@@ -698,6 +694,8 @@ async def put_guardian_restrictions(
grant = save_grant(learner_user_id, grant)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if learner_record.get("preset") != "learner" and not set_preset(learner_username, "learner"):
+ raise HTTPException(status_code=409, detail="Learner account is no longer available")
restrictions = _guardian_restrictions(grant)
_log_supervisor_action(
"guardian_restrictions_set",
diff --git a/tests/multi_user/test_learning_surface_map.py b/tests/multi_user/test_learning_surface_map.py
index b4c662554..d66588f59 100644
--- a/tests/multi_user/test_learning_surface_map.py
+++ b/tests/multi_user/test_learning_surface_map.py
@@ -1,10 +1,9 @@
-"""Regression tests for the learner surface map and restrictions preset flip (#1222).
+"""Regression tests for learner surfaces and restriction preset changes.
Two failure modes covered:
-1. ``_learning_surface_for_path`` used to map only five prefixes, so the
- learner shell's own Knowledge Center (`/api/knowledge-bases/*`) and Mastery
- Path (`/api/mastery-paths/*`) endpoints default-denied to 403.
+1. Knowledge Center browsing needs a precise GET allowlist. Admin diagnostics
+ and engine configuration endpoints share the same URL prefix.
2. Assigning guardian restrictions to a `standard`-preset account left the
account in a `standard` preset + `learning_policy` mix: the frontend then
rendered the full admin shell and every surface request 403'd. The PUT
@@ -14,6 +13,8 @@ Two failure modes covered:
from __future__ import annotations
+from fastapi import Depends, FastAPI, Request
+from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers.auth import _learning_surface_for_path
@@ -34,11 +35,7 @@ from deeptutor.api.routers.auth import _learning_surface_for_path
("/api/mastery-paths/progress/book-1", "GET", "chat"),
("/api/mastery-paths/progress/book-1", "PATCH", "chat"),
("/api/mastery-paths/progress/book-1/redo", "POST", "chat"),
- # Knowledge Center: read-only for learners.
- ("/api/knowledge-bases", "GET", "reading"),
- ("/api/knowledge-bases/kb1/files", "GET", "reading"),
- ("/api/knowledge-bases/kb1/files/a.pdf", "GET", "reading"),
- # KB mutations stay denied — they affect shared/admin resources.
+ # KB writes stay denied, even when the route is otherwise browsable.
("/api/knowledge-bases", "POST", ""),
("/api/knowledge-bases/kb1/upload", "POST", ""),
("/api/knowledge-bases/kb1/files/a.pdf", "DELETE", ""),
@@ -54,18 +51,122 @@ def test_learning_surface_map(path: str, method: str, expected: str) -> None:
assert _learning_surface_for_path(path, method) == expected
+ ("path", "route_path", "expected"),
+ [
+ ("/api/knowledge-bases", "/api/knowledge-bases", "reading"),
+ ("/api/knowledge-bases/kb1", "/api/knowledge-bases/{kb_name}", "reading"),
+ ("/api/knowledge-bases/kb1/files", "/api/knowledge-bases/{kb_name}/files", "reading"),
+ (
+ "/api/knowledge-bases/kb1/files/a.pdf",
+ "/api/knowledge-bases/{kb_name}/files/{filename:path}",
+ "reading",
+ ),
+ (
+ "/api/knowledge-bases/kb1/file-preview-text/a.pdf",
+ "/api/knowledge-bases/{kb_name}/file-preview-text/{filename:path}",
+ "reading",
+ ),
+ ("/api/knowledge-bases/kb1/progress", "/api/knowledge-bases/{kb_name}/progress", "reading"),
+ ("/api/knowledge-bases/health", "/api/knowledge-bases/health", ""),
+ ("/api/knowledge-bases/configs", "/api/knowledge-bases/configs", ""),
+ ("/api/knowledge-bases/default", "/api/knowledge-bases/default", ""),
+ (
+ "/api/knowledge-bases/rag-pipelines/lightrag/config",
+ "/api/knowledge-bases/rag-pipelines/lightrag/config",
+ "",
+ ),
+ ("/api/knowledge-bases/kb1/config", "/api/knowledge-bases/{kb_name}/config", ""),
+ (
+ "/api/knowledge-bases/kb1/reindex-config",
+ "/api/knowledge-bases/{kb_name}/reindex-config",
+ "",
+ ),
+ (
+ "/api/knowledge-bases/kb1/linked-folders",
+ "/api/knowledge-bases/{kb_name}/linked-folders",
+ "",
+ ),
+ (
+ "/api/knowledge-bases/kb1/github-sources",
+ "/api/knowledge-bases/{kb_name}/github-sources",
+ "",
+ ),
+ (
+ "/api/knowledge-bases/kb1/web-sources",
+ "/api/knowledge-bases/{kb_name}/web-sources",
+ "",
+ ),
+ ],
+)
+def test_learner_kb_get_allowlist(path: str, route_path: str, expected: str) -> None:
+ assert _learning_surface_for_path(path, "GET", route_path=route_path) == expected
+ if expected:
+ assert _learning_surface_for_path(path, "HEAD", route_path=route_path) == ""
+ assert _learning_surface_for_path(path, "OPTIONS", route_path=route_path) == ""
+ assert _learning_surface_for_path(path, "POST", route_path=route_path) == ""
+ assert _learning_surface_for_path(path, "GET") == ""
+
+
+def test_route_template_is_passed_to_surface_guard(monkeypatch) -> None:
+ import asyncio
+ from types import SimpleNamespace
+
+ from deeptutor.api.routers.auth import require_learning_surface
+ from deeptutor.multi_user import learning_access
+
+ observed = []
+ monkeypatch.setattr(learning_access, "assert_learning_surface", observed.append)
+ scope = {
+ "type": "http",
+ "method": "GET",
+ "path": "/api/knowledge-bases/health",
+ "headers": [],
+ "route": SimpleNamespace(path="/api/knowledge-bases/health"),
+ }
+ asyncio.run(require_learning_surface(Request(scope), None))
+ assert observed == [""]
+
+
+def test_fastapi_guard_denies_kb_diagnostics_but_allows_browsing(monkeypatch) -> None:
+ from deeptutor.api.routers.auth import require_auth, require_learning_surface
+ from deeptutor.multi_user import learning_access
+
+ def deny_unmapped(surface: str) -> None:
+ if not surface:
+ raise PermissionError("denied")
+
+ monkeypatch.setattr(learning_access, "assert_learning_surface", deny_unmapped)
+ app = FastAPI()
+ app.dependency_overrides[require_auth] = lambda: None
+
+ @app.get("/api/knowledge-bases/health", dependencies=[Depends(require_learning_surface)])
+ def health() -> dict[str, str]:
+ return {"status": "ok"}
+
+ @app.get("/api/knowledge-bases/{kb_name}", dependencies=[Depends(require_learning_surface)])
+ def details(kb_name: str) -> dict[str, str]:
+ return {"name": kb_name}
+
+ client = TestClient(app)
+ assert client.get("/api/knowledge-bases/health").status_code == 403
+ assert client.get("/api/knowledge-bases/kb1").json() == {"name": "kb1"}
+
+
def test_put_restrictions_flips_standard_preset_to_learner(
- mu_isolated_root, seed_user
+ mu_isolated_root, seed_user, monkeypatch
):
"""PUT restrictions on a standard-preset account seeds the policy and
flips the account preset to ``learner`` (#1222 preset/policy mix)."""
import asyncio
from types import SimpleNamespace
+ from deeptutor.api.routers import multi_user
from deeptutor.api.routers.multi_user import (
GuardianRestrictionsPayload,
put_guardian_restrictions,
)
+ from deeptutor.multi_user.grants import load_grant
from deeptutor.multi_user.identity import get_user_by_id
# The first account in an empty store is promoted to admin by save_user;
@@ -82,8 +183,54 @@ def test_put_restrictions_flips_standard_preset_to_learner(
extensions=[],
)
+ original_set_preset = multi_user.set_preset
+
+ def set_preset_after_grant(username: str, preset: str) -> bool:
+ assert load_grant(learner_user_id)["learning_policy"]["age_band"] == "13-15"
+ return original_set_preset(username, preset)
+
+ monkeypatch.setattr(multi_user, "set_preset", set_preset_after_grant)
+
result = asyncio.run(put_guardian_restrictions(learner_user_id, payload, admin))
assert result["restrictions"]["age_band"] == "13-15"
_username, updated = get_user_by_id(learner_user_id)
assert updated.get("preset") == "learner"
+
+
+def test_failed_grant_save_does_not_change_standard_preset(
+ mu_isolated_root, seed_user, monkeypatch
+) -> None:
+ import asyncio
+ from types import SimpleNamespace
+
+ from fastapi import HTTPException
+
+ from deeptutor.api.routers import multi_user
+ from deeptutor.multi_user.grants import load_grant
+ from deeptutor.multi_user.identity import get_user_by_id
+
+ seed_user("bootstrap-admin")
+ record = seed_user("student-standard")
+ learner_user_id = record["id"]
+ payload = multi_user.GuardianRestrictionsPayload(
+ age_band="13-15",
+ allow_upload=True,
+ allowed_surfaces=["chat", "reading"],
+ extensions=[],
+ )
+
+ def fail_save_grant(*_args, **_kwargs):
+ raise ValueError("Grant store unavailable")
+
+ monkeypatch.setattr(multi_user, "save_grant", fail_save_grant)
+ with pytest.raises(HTTPException, match="Grant store unavailable"):
+ asyncio.run(
+ multi_user.put_guardian_restrictions(
+ learner_user_id, payload, SimpleNamespace(user_id="u_admin", role="admin")
+ )
+ )
+
+ _username, updated = get_user_by_id(learner_user_id)
+ assert updated.get("preset") == "standard"
+ assert load_grant(learner_user_id).get("learning_policy") is None