Skip to content

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

fix(reading): enforce current learner grants on saved sources and tabs

Bingxi Zhao (Frank)21b9307031c3
diff --git a/deeptutor/capabilities/reading/capability.py b/deeptutor/capabilities/reading/capability.py
index 56cfa1d6f..9a95e8384 100644
--- a/deeptutor/capabilities/reading/capability.py
+++ b/deeptutor/capabilities/reading/capability.py
@@ -179,11 +179,14 @@ class ReadingCapability:
return ""
if workspace is None:
return ""
+ from deeptutor.multi_user.learning_access import learning_material_allowed
+
rows = [f"Reading workspace: {workspace.title}. Only one material is bound at a time."]
rows.extend(
f"- {tab.material.title} [{tab.material.source_kind.value}; "
f"{tab.material.status.value}; id={tab.material.material_id}]"
for tab in workspace.tabs
+ if learning_material_allowed(tab.material.material_id)
)
rows.append(
"For cross-material work, call reading_list_tabs, then reading_switch_tab "
@@ -193,6 +196,10 @@ class ReadingCapability:
def _material_facts(self, material_id: str, *, language: str) -> str:
"""Describe the open document: identity, size, unit word, viewport."""
+ from deeptutor.multi_user.learning_access import learning_material_allowed
+
+ if not learning_material_allowed(material_id):
+ return ""
try:
from deeptutor.reading import ReadingStore, material_summary
@@ -353,6 +360,10 @@ class ReadingCapability:
if not resolve_material_id(context):
return ""
material_id = resolve_material_id(context)
+ from deeptutor.multi_user.learning_access import learning_material_allowed
+
+ if not learning_material_allowed(material_id):
+ return ""
viewport = resolve_viewport(context)
locator = _as_int(viewport.get("locator"))
selection = str(viewport.get("selection") or "").strip()
@@ -423,8 +434,12 @@ class ReadingCapability:
@staticmethod
def _locate(material_id: str, question: str) -> list[str]:
+ from deeptutor.multi_user.learning_access import learning_material_allowed
from deeptutor.reading import ReadingStore, search_material
+ if not learning_material_allowed(material_id):
+ return []
+
store = ReadingStore()
manifest = store.manifest(material_id)
result = search_material(store, material_id, question, limit=LOCATE_HITS)
diff --git a/deeptutor/capabilities/reading/tools.py b/deeptutor/capabilities/reading/tools.py
index a35688c0f..d752f9a97 100644
--- a/deeptutor/capabilities/reading/tools.py
+++ b/deeptutor/capabilities/reading/tools.py
@@ -77,6 +77,9 @@ class _ReadingToolBase(BaseTool):
material_id = str(bound_id or kwargs.get(MATERIAL_KWARG) or "").strip()
if not material_id:
raise _NoMaterial()
+ from deeptutor.multi_user.learning_access import assert_learning_material
+
+ assert_learning_material(material_id)
return material_id
@staticmethod
@@ -115,6 +118,8 @@ def _guard(func):
return self._failure(
"No reading material is open. Ask the user to open a document in the reader."
)
+ except PermissionError as exc:
+ return self._failure(str(exc))
except ReadingError as exc:
return self._failure(str(exc))
except Exception: # pragma: no cover - defensive
@@ -148,9 +153,14 @@ class ReadingListTabsTool(_ReadingToolBase):
workspace = await asyncio.to_thread(self._catalog().get_workspace, workspace_id)
if workspace is None:
return self._failure("The reading workspace is unavailable.")
- lines = [f"Reading table “{workspace.title}” has {len(workspace.tabs)} material(s):"]
+ from deeptutor.multi_user.learning_access import learning_material_allowed
+
+ visible_tabs = [
+ tab for tab in workspace.tabs if learning_material_allowed(tab.material.material_id)
+ ]
+ lines = [f"Reading table “{workspace.title}” has {len(visible_tabs)} material(s):"]
tabs: list[dict[str, Any]] = []
- for tab in workspace.tabs:
+ for tab in visible_tabs:
material = tab.material
active = material.material_id == workspace.active_material_id
lines.append(
@@ -201,6 +211,9 @@ class ReadingSwitchTabTool(_ReadingToolBase):
return self._failure("No reading workspace is open.")
if not material_id:
return self._failure("reading_switch_tab needs a material id.")
+ from deeptutor.multi_user.learning_access import assert_learning_material
+
+ assert_learning_material(material_id)
workspace = await asyncio.to_thread(
self._catalog().set_active_material, workspace_id, material_id
)
@@ -421,7 +434,9 @@ class ReadMaterialTool(_ReadingToolBase):
for locator in rendered.locators
if locator in stamps
)
- media_note = await asyncio.to_thread(_media_note, store, material_id, manifest.unit, rendered.locators)
+ media_note = await asyncio.to_thread(
+ _media_note, store, material_id, manifest.unit, rendered.locators
+ )
followup = (
"\n\n→ Now call reader_goto with the verbatim sentence you are "
"about to cite, so the user sees it highlighted, and cite it in "
diff --git a/deeptutor/multi_user/learning_access.py b/deeptutor/multi_user/learning_access.py
index 2296d2a93..a46e5210b 100644
--- a/deeptutor/multi_user/learning_access.py
+++ b/deeptutor/multi_user/learning_access.py
@@ -86,6 +86,15 @@ def assert_learning_material(material_id: str, *, upload: bool = False) -> None:
raise PermissionError("This reading material is not assigned to this learning account.")
+def learning_material_allowed(material_id: str) -> bool:
+ """Check a material without exposing a revoked source in a prompt or list."""
+ try:
+ assert_learning_material(material_id)
+ except PermissionError:
+ return False
+ return True
+
+
def assert_learning_material_mutation(material_id: str) -> None:
"""Protect administrator-assigned material from learner-side deletion."""
policy = current_learning_policy()
@@ -114,5 +123,6 @@ __all__ = [
"assert_learning_material_mutation",
"assert_learning_surface",
"current_learning_policy",
+ "learning_material_allowed",
"learning_policy_for_user",
]
diff --git a/deeptutor/reading/references.py b/deeptutor/reading/references.py
index 8f91e67d8..3304a3f99 100644
--- a/deeptutor/reading/references.py
+++ b/deeptutor/reading/references.py
@@ -88,10 +88,16 @@ def resolve_reading_sources(
) -> list[ResolvedReadingSource]:
"""Resolve canonical references against the active user's reading store."""
+ from deeptutor.multi_user.learning_access import learning_material_allowed
+
active_store = store or ReadingStore()
resolved: list[ResolvedReadingSource] = []
for reference in normalize_reading_references(value):
material_id = reference["material_id"]
+ # A saved turn or historical source may outlive a learner's assignment.
+ # Check the current grant before even opening a stored revision.
+ if not learning_material_allowed(material_id):
+ continue
revision = reference["revision"]
try:
current_manifest = active_store.manifest(material_id)
diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.py
index a946e6f49..130e67fc1 100644
--- a/deeptutor/services/session/turns/executor.py
+++ b/deeptutor/services/session/turns/executor.py
@@ -230,6 +230,13 @@ class TurnExecutor:
)
)
try:
+ # A queued turn may start after a learner's material grant changes.
+ # Recheck before prompt construction and reading-tool execution.
+ material_id = _reading_material_id(payload.get("reading_material_id"))
+ if material_id:
+ from deeptutor.multi_user.learning_access import assert_learning_material
+
+ assert_learning_material(material_id)
from deeptutor.agents.notebook import NotebookAnalysisAgent
from deeptutor.book.context import build_book_context
from deeptutor.core.context import Attachment, TurnRuntimeContext, UnifiedContext
diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.py
index 617e452cd..b26d25fa4 100644
--- a/deeptutor/services/session/turns/request_preparer.py
+++ b/deeptutor/services/session/turns/request_preparer.py
@@ -309,6 +309,7 @@ class TurnRequestPreparer:
reading_material_revision = _reading_material_revision(
payload.get("reading_material_revision")
)
+ reading_catalog = None
if workspace_mode == WORKSPACE_MODE_READING and reading_workspace_id:
from deeptutor.reading import ReadingCatalogStore
@@ -323,6 +324,18 @@ class TurnRequestPreparer:
tab.material.material_id for tab in reading_workspace.tabs
}:
raise RuntimeError("The active material is not part of this reading workspace.")
+ # The workspace and saved session can still contain a material whose
+ # learner assignment has since been revoked. Authorize the resolved
+ # material, including a default chosen from the workspace, before
+ # attaching the session or admitting a replayed turn.
+ if reading_material_id:
+ from deeptutor.multi_user.learning_access import assert_learning_material
+
+ try:
+ assert_learning_material(reading_material_id)
+ except PermissionError as exc:
+ raise RuntimeError(str(exc)) from exc
+ if reading_catalog is not None:
reading_catalog.attach_session(
reading_workspace_id,
session["id"],
diff --git a/tests/multi_user/test_learning_reading_turns.py b/tests/multi_user/test_learning_reading_turns.py
new file mode 100644
index 000000000..8d6c637bf
--- /dev/null
+++ b/tests/multi_user/test_learning_reading_turns.py
@@ -0,0 +1,197 @@
+"""A saved reading source must obey the learner's current assignment."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from deeptutor.capabilities.reading.capability import ReadingCapability
+from deeptutor.capabilities.reading.tools import (
+ BINDING_KWARG,
+ WORKSPACE_KWARG,
+ ReadingListTabsTool,
+ ReadingSwitchTabTool,
+ ReadMaterialTool,
+)
+from deeptutor.multi_user.grants import save_grant
+from deeptutor.reading import ReadingCatalogStore, ReadingStore
+from deeptutor.reading.references import resolve_reading_sources
+from deeptutor.services.session.source_inventory import build_inventory, render_manifest
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+from deeptutor.services.session.turn_runtime import TurnRuntimeManager
+
+
+def _grant(user_id: str, material_ids: list[str]) -> None:
+ save_grant(
+ user_id,
+ {
+ "learning_policy": {
+ "age_band": "9-12",
+ "locked_persona": "teacher",
+ "allowed_capabilities": ["chat", "immersive_reading"],
+ "allowed_surfaces": ["chat", "reading"],
+ "reading": {
+ "allow_upload": False,
+ "material_ids": material_ids,
+ "extensions": [],
+ },
+ }
+ },
+ )
+
+
+def _materials():
+ store = ReadingStore()
+ catalog = ReadingCatalogStore()
+ allowed = store.ingest_units(
+ "1" * 16,
+ filename="allowed.md",
+ title="Allowed title",
+ units=["Allowed passage."],
+ )
+ revoked = store.ingest_units(
+ "2" * 16,
+ filename="revoked.md",
+ title="Revoked title",
+ units=["Revoked secret passage."],
+ )
+ catalog.register_manifest(allowed)
+ catalog.register_manifest(revoked)
+ workspace = catalog.create_workspace("Study table", [allowed.material_id, revoked.material_id])
+ return store, catalog, workspace, allowed, revoked
+
+
+def _reference(material) -> dict:
+ return {"material_id": material.material_id, "revision": material.revision, "locators": [1]}
+
+
+class _SavedReferenceStore:
+ def __init__(self, reference: dict) -> None:
+ self.reference = reference
+
+ async def get_messages(self, _session_id: str):
+ return [
+ {
+ "id": 1,
+ "role": "user",
+ "content": "What does this say?",
+ "parent_message_id": None,
+ "metadata": {"request_snapshot": {"readingReferences": [self.reference]}},
+ }
+ ]
+
+
+async def test_revoked_reference_disappears_from_fresh_and_historical_chat_sources(
+ mu_isolated_root, seed_user, as_user
+) -> None:
+ seed_user("admin", role="admin")
+ learner = seed_user("student")
+ with as_user(learner["id"], username="student"):
+ store, _, _, allowed, revoked = _materials()
+ _grant(learner["id"], [allowed.material_id, revoked.material_id])
+ assert (
+ "Revoked secret passage."
+ in resolve_reading_sources([_reference(revoked)], store=store)[0].full_text
+ )
+
+ # A historical request snapshot remains on disk after assignment is
+ # revoked. It and a fresh Resend reference must now resolve alike.
+ _grant(learner["id"], [allowed.material_id])
+ references = [_reference(allowed), _reference(revoked)]
+ assert [row.source_id for row in resolve_reading_sources(references, store=store)] == [
+ f"rd-{allowed.material_id}-r{allowed.revision}-1"
+ ]
+ inventory = await build_inventory(
+ _SavedReferenceStore(_reference(revoked)),
+ session_id="s1",
+ leaf_message_id=1,
+ current_turn_ordinal=2,
+ fresh_attachment_records=[],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ fresh_reading_references=references,
+ )
+ manifest, source_index = render_manifest(inventory)
+ assert "Allowed passage." in manifest
+ assert "Revoked title" not in manifest
+ assert "Revoked secret passage." not in str(source_index)
+ assert all(revoked.material_id not in source_id for source_id in source_index)
+ _grant(learner["id"], [allowed.material_id, revoked.material_id])
+ assert (
+ "Revoked secret passage."
+ in resolve_reading_sources([_reference(revoked)], store=store)[0].full_text
+ )
+
+
+async def test_turn_rejects_explicit_and_workspace_default_revoked_material(
+ mu_isolated_root, seed_user, as_user, monkeypatch
+) -> None:
+ seed_user("admin", role="admin")
+ learner = seed_user("student")
+ with as_user(learner["id"], username="student"):
+ _, catalog, workspace, allowed, revoked = _materials()
+ _grant(learner["id"], [allowed.material_id])
+ runtime = TurnRuntimeManager(SQLiteSessionStore(mu_isolated_root / "turns.sqlite3"))
+
+ async def _noop_run_turn(_execution) -> None:
+ return None
+
+ monkeypatch.setattr(runtime, "_run_turn", _noop_run_turn)
+ base = {
+ "capability": "immersive_reading",
+ "workspace_mode": "immersive_reading",
+ "reading_workspace_id": workspace.workspace_id,
+ "content": "Read this",
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [],
+ "language": "en",
+ "config": {},
+ }
+ with pytest.raises(RuntimeError, match="not assigned"):
+ await runtime.start_turn({**base, "reading_material_id": revoked.material_id})
+
+ catalog.set_active_material(workspace.workspace_id, revoked.material_id)
+ with pytest.raises(RuntimeError, match="not assigned"):
+ await runtime.start_turn(base)
+
+
+def test_reading_tools_hide_and_block_revoked_tabs(mu_isolated_root, seed_user, as_user) -> None:
+ seed_user("admin", role="admin")
+ learner = seed_user("student")
+ with as_user(learner["id"], username="student"):
+ _, _, workspace, allowed, revoked = _materials()
+ _grant(learner["id"], [allowed.material_id])
+ binding = {"material_id": allowed.material_id}
+ listed = asyncio.run(
+ ReadingListTabsTool().execute(**{WORKSPACE_KWARG: workspace.workspace_id})
+ )
+ assert listed.success
+ assert [row["material_id"] for row in listed.metadata["tabs"]] == [allowed.material_id]
+ assert "Revoked title" not in listed.content
+ assert "Revoked title" not in ReadingCapability._workspace_facts(workspace.workspace_id)
+
+ switched = asyncio.run(
+ ReadingSwitchTabTool().execute(
+ material_id=revoked.material_id,
+ **{WORKSPACE_KWARG: workspace.workspace_id, BINDING_KWARG: binding},
+ )
+ )
+ assert not switched.success
+ assert "not assigned" in switched.content
+ assert binding["material_id"] == allowed.material_id
+
+ read = asyncio.run(
+ ReadMaterialTool().execute(
+ locators="1", **{BINDING_KWARG: {"material_id": revoked.material_id}}
+ )
+ )
+ assert not read.success
+ assert "not assigned" in read.content
+ assert "Revoked secret passage." not in read.content