Skip to content

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

fix(auth): respect learner grants in learning navigation (#1987)

Bingxi Zhao (Frank)ab34b71d42c9
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 0b63eff22..b3cb5df46 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -649,6 +649,7 @@ def _learning_surface_for_path(
("/api/dashboard/learning-library/reading", "reading"),
("/api/books", "books"),
("/api/dashboard/learning-library/books", "books"),
+ ("/api/dashboard/learning-library/mastery", "chat"),
("/api/chat", "chat"),
("/api/question", "chat"),
("/api/question-notebook", "chat"),
@@ -704,14 +705,28 @@ async def require_learning_surface(
_: TokenPayload | None = Depends(require_auth),
) -> None:
"""Second-stage default-deny guard for configured learning accounts."""
- from deeptutor.multi_user.learning_access import assert_learning_surface
+ from deeptutor.multi_user.learning_access import (
+ assert_learning_surface,
+ learning_surface_allowed,
+ )
+
+ route_path = _resolved_route_path(request)
+ # The landing page combines independent learning surfaces (#1987). Admit
+ # any granted surface; the handler filters its readers with the same policy.
+ if (
+ request.method == "GET"
+ and request.url.path == "/api/dashboard/learning-index"
+ and route_path == "/api/dashboard/learning-index"
+ and any(learning_surface_allowed(surface) for surface in ("books", "chat", "reading"))
+ ):
+ return
try:
assert_learning_surface(
_learning_surface_for_path(
request.url.path,
request.method,
- route_path=_resolved_route_path(request),
+ route_path=route_path,
)
)
except PermissionError as exc:
diff --git a/deeptutor/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.py
index 36585c3a6..6769e3ae8 100644
--- a/deeptutor/api/routers/dashboard.py
+++ b/deeptutor/api/routers/dashboard.py
@@ -82,6 +82,7 @@ async def get_learning_index():
from deeptutor.api.routers.book import list_books
from deeptutor.api.routers.mastery_path import list_topics
from deeptutor.api.routers.reading import list_workspaces
+ from deeptutor.multi_user.learning_access import learning_surface_allowed
from deeptutor.services.workspace.navigation import read_workspace_indexes
async def books():
@@ -93,13 +94,6 @@ async def get_learning_index():
async def reading():
return (await list_workspaces(search=""))["workspaces"]
- result = {}
- failed = []
- for kind, reader in (("books", books), ("mastery", mastery), ("reading", reading)):
- result[kind], unavailable = await read_workspace_indexes(reader)
- if unavailable:
- failed.append(kind)
-
async def watching():
from deeptutor.services.session.organization import list_all_sessions_snapshot
@@ -111,9 +105,22 @@ async def get_learning_index():
or (row.get("preferences") or {}).get("capability") == "immersive_watching"
]
- result["watching"], unavailable = await read_workspace_indexes(watching)
- if unavailable:
- failed.append("watching")
+ result = {}
+ failed = []
+ for kind, surface, reader in (
+ ("books", "books", books),
+ ("mastery", "chat", mastery),
+ ("reading", "reading", reading),
+ ("watching", "reading", watching),
+ ):
+ # Calling a route function directly bypasses its HTTP dependencies.
+ # Never load a source that the learner could not open individually.
+ result[kind] = []
+ if not learning_surface_allowed(surface):
+ continue
+ result[kind], unavailable = await read_workspace_indexes(reader)
+ if unavailable:
+ failed.append(kind)
return {"sources": result, "failed": failed}
diff --git a/deeptutor/multi_user/learning_access.py b/deeptutor/multi_user/learning_access.py
index a46e5210b..02944f944 100644
--- a/deeptutor/multi_user/learning_access.py
+++ b/deeptutor/multi_user/learning_access.py
@@ -70,6 +70,15 @@ def assert_learning_surface(surface: str) -> None:
raise PermissionError(f"This learning account cannot use the {target}.")
+def learning_surface_allowed(surface: str) -> bool:
+ """Filter aggregate navigation with the same policy as individual routes."""
+ try:
+ assert_learning_surface(surface)
+ except PermissionError:
+ return False
+ return True
+
+
def assert_learning_material(material_id: str, *, upload: bool = False) -> None:
"""Enforce upload and assigned-material policy in the authenticated scope."""
policy = current_learning_policy()
@@ -125,4 +134,5 @@ __all__ = [
"current_learning_policy",
"learning_material_allowed",
"learning_policy_for_user",
+ "learning_surface_allowed",
]
diff --git a/tests/multi_user/test_learning_policy_http.py b/tests/multi_user/test_learning_policy_http.py
index 6dbe9ff78..7f8eaee95 100644
--- a/tests/multi_user/test_learning_policy_http.py
+++ b/tests/multi_user/test_learning_policy_http.py
@@ -222,3 +222,92 @@ def test_dashboard_learning_library_follows_the_policy(learner_client, as_user):
denied = client.get(f"/api/dashboard/learning-library/{kind}")
assert denied.status_code == 403
assert "reading surface" in denied.json()["detail"]
+
+
+ "surfaces", [["reading"], ["chat"], ["books"], ["books", "chat", "reading"]]
+)
+def test_learning_home_only_reads_granted_surfaces(learner_client, monkeypatch, surfaces):
+ """#1987: the aggregate page works without opening a denied source reader."""
+ from deeptutor.api.routers import book, mastery_path
+ from deeptutor.services.session import organization
+
+ client, learner, _current_user, _tmp_path = learner_client
+ _save_learner_grant(learner["id"], "assigned", allowed_surfaces=surfaces)
+ calls = []
+
+ async def books():
+ calls.append("books")
+ return {"books": [{"id": "book"}]}
+
+ async def mastery():
+ calls.append("chat")
+ return {"topics": [{"id": "topic"}]}
+
+ async def collections(**_kwargs):
+ calls.append("reading")
+ return {"workspaces": [{"id": "collection"}]}
+
+ async def watching(_store):
+ calls.append("reading")
+ return [{"id": "video", "preferences": {"workspace_mode": "immersive_watching"}}]
+
+ monkeypatch.setattr(book, "list_books", books)
+ monkeypatch.setattr(mastery_path, "list_topics", mastery)
+ monkeypatch.setattr(reading, "list_workspaces", collections)
+ monkeypatch.setattr(organization, "list_all_sessions_snapshot", watching)
+ monkeypatch.setattr(dashboard, "get_session_store", lambda: object())
+
+ response = client.get("/api/dashboard/learning-index")
+ assert response.status_code == 200, response.text
+ assert response.json()["failed"] == []
+ for kind, surface in {
+ "books": "books",
+ "mastery": "chat",
+ "reading": "reading",
+ "watching": "reading",
+ }.items():
+ assert bool(response.json()["sources"][kind]) == (surface in surfaces)
+ assert set(calls) == set(surfaces)
+ assert client.get("/api/dashboard/recent").status_code == 403
+ assert client.get("/api/dashboard/source-library/chats").status_code == 403
+ assert client.get("/api/dashboard/learning-index-private").status_code == 403
+
+
+def test_learning_home_retains_assigned_material_filtering(learner_client, as_user):
+ from deeptutor.reading.catalog_store import ReadingCatalogStore
+
+ client, learner, current_user, tmp_path = learner_client
+ with as_user(current_user.id, username="student"):
+ allowed = _seed_material(tmp_path, "home-allowed.txt", "Assigned passage.")
+ private = _seed_material(tmp_path, "home-private.txt", "Unassigned passage.")
+ catalog = ReadingCatalogStore()
+ catalog.register_manifest(allowed)
+ catalog.register_manifest(private)
+ workspace = catalog.create_workspace("Mixed", [allowed.material_id, private.material_id])
+ _save_learner_grant(learner["id"], allowed.material_id, allowed_surfaces=["reading"])
+
+ response = client.get("/api/dashboard/learning-index")
+ assert response.status_code == 200, response.text
+ rows = response.json()["sources"]["reading"]
+ assert [row["workspace_id"] for row in rows] == [workspace.workspace_id]
+ assert [tab["material"]["material_id"] for tab in rows[0]["tabs"]] == [allowed.material_id]
+ assert private.material_id not in response.text
+
+
[email protected]("surfaces,expected", [(["chat"], 200), (["reading"], 403)])
+def test_mastery_library_obeys_chat_surface(learner_client, monkeypatch, surfaces, expected):
+ from deeptutor.api.routers import mastery_path
+
+ client, learner, _current_user, _tmp_path = learner_client
+ _save_learner_grant(learner["id"], "assigned", allowed_surfaces=surfaces)
+ calls = []
+
+ async def topics():
+ calls.append(True)
+ return {"topics": [{"id": "topic"}]}
+
+ monkeypatch.setattr(mastery_path, "list_topics", topics)
+ response = client.get("/api/dashboard/learning-library/mastery")
+ assert response.status_code == expected, response.text
+ assert bool(calls) == (expected == 200)