DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
"""HTTP enforcement of learning-policy Reading boundaries."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers import dashboard, reading, reading_extensions
from deeptutor.api.routers.auth import require_auth, require_learning_surface
from deeptutor.multi_user.context import reset_current_user, set_current_user
from deeptutor.reading import ReadingStore
from deeptutor.reading.extensions import (
ReadingAction,
ReadingExtensionManifest,
ReadingExtensionRegistry,
ReadingExtensionResult,
)
def _extension(extension_id: str):
return SimpleNamespace(
manifest=ReadingExtensionManifest(
id=extension_id,
version="1.0.0",
name=extension_id.title(),
actions=[ReadingAction(id="open", label="Open")],
result_types=["card"],
),
run_action=lambda _action, _context: ReadingExtensionResult(type="card"),
)
@pytest.fixture
def learner_client(mu_isolated_root, seed_user, make_user, monkeypatch, tmp_path):
learner = _seed_learner(seed_user)
current_user = make_user(learner["id"], username="student")
async def install_user():
token = set_current_user(current_user)
try:
yield current_user
finally:
reset_current_user(token)
registry = ReadingExtensionRegistry([_extension("read_aloud"), _extension("quiz")])
monkeypatch.setattr(
reading_extensions,
"get_reading_extension_registry",
lambda: registry,
)
app = FastAPI()
dependencies = [Depends(install_user)]
app.include_router(
reading.router,
prefix="/api/reading",
dependencies=dependencies,
)
app.include_router(
reading_extensions.router,
prefix="/api/reading",
dependencies=dependencies,
)
app.dependency_overrides[require_auth] = lambda: None
app.include_router(
dashboard.router,
prefix="/api/dashboard",
dependencies=[*dependencies, Depends(require_learning_surface)],
)
return TestClient(app), learner, current_user, tmp_path
def _seed_material(root: Path, name: str, text: str):
source = root / name
source.write_text(text, encoding="utf-8")
return ReadingStore().ingest(source)
def _save_learner_grant(
user_id: str, material_id: str, *, allowed_surfaces: list[str] | None = None
):
from deeptutor.multi_user.grants import save_grant
save_grant(
user_id,
{
"enabled_tools": [],
"mcp_tools": [],
"cli_apps": [],
"exec_enabled": False,
"learning_policy": {
"age_band": "9-12",
"locked_persona": "teacher",
"allowed_capabilities": ["chat", "immersive_reading"],
"default_capability": "immersive_reading",
"allowed_surfaces": allowed_surfaces or ["chat", "reading"],
"reading": {
"allow_upload": False,
"material_ids": [material_id],
"extensions": ["read_aloud"],
},
},
},
)
def _seed_learner(seed_user):
seed_user("admin", role="admin")
return seed_user("student")
def test_reading_upload_material_and_listing_follow_the_policy(learner_client, as_user):
client, learner, current_user, tmp_path = learner_client
with as_user(current_user.id, username="student"):
from deeptutor.reading.catalog_store import ReadingCatalogStore
allowed = _seed_material(tmp_path, "allowed.txt", "Allowed passage.")
private = _seed_material(tmp_path, "private.txt", "Private passage.")
catalog = ReadingCatalogStore()
catalog.register_manifest(allowed)
catalog.register_manifest(private)
workspace = catalog.create_workspace(
"Mixed collection",
[allowed.material_id, private.material_id],
)
_save_learner_grant(learner["id"], allowed.material_id)
denied_upload = client.post(
"/api/reading/materials",
files={"file": ("new.txt", b"new material", "text/plain")},
)
assert denied_upload.status_code == 403
assert "cannot upload" in denied_upload.json()["detail"]
rows = client.get("/api/reading/materials").json()
assert [row["material_id"] for row in rows] == [allowed.material_id]
assert client.get(f"/api/reading/materials/{allowed.material_id}").status_code == 200
denied_material = client.get(f"/api/reading/materials/{private.material_id}")
assert denied_material.status_code == 403
assert "not assigned" in denied_material.json()["detail"]
library = client.get("/api/reading/library/materials").json()
assert [row["material_id"] for row in library["materials"]] == [allowed.material_id]
assert library["counts"]["all"] == 1
duplicate = client.post(
"/api/reading/library/duplicate-check",
json={"files": [{"filename": "private.txt"}]},
).json()
assert duplicate["matches"] == []
visible_workspace = client.get(f"/api/reading/workspaces/{workspace.workspace_id}").json()[
"workspace"
]
assert [tab["material"]["material_id"] for tab in visible_workspace["tabs"]] == [
allowed.material_id
]
denied_delete = client.delete(f"/api/reading/materials/{allowed.material_id}")
assert denied_delete.status_code == 403
assert "cannot modify" in denied_delete.json()["detail"]
assert client.get(f"/api/reading/materials/{allowed.material_id}").status_code == 200
def test_reading_extensions_and_actions_follow_the_policy(learner_client, as_user):
client, learner, current_user, tmp_path = learner_client
with as_user(current_user.id, username="student"):
material = _seed_material(tmp_path, "allowed.txt", "Allowed passage.")
_save_learner_grant(learner["id"], material.material_id)
rows = client.get("/api/reading/extensions").json()
assert [row["id"] for row in rows] == ["read_aloud"]
allowed = client.post(
f"/api/reading/materials/{material.material_id}/extensions/read_aloud/actions/open",
json={"locator": 1},
)
assert allowed.status_code == 200, allowed.text
denied = client.post(
f"/api/reading/materials/{material.material_id}/extensions/quiz/actions/open",
json={"locator": 1},
)
assert denied.status_code == 403
assert "not allowed" in denied.json()["detail"]
def test_dashboard_learning_library_follows_the_policy(learner_client, as_user):
client, learner, current_user, tmp_path = learner_client
with as_user(current_user.id, username="student"):
from deeptutor.reading.catalog_store import ReadingCatalogStore
allowed = _seed_material(tmp_path, "allowed.txt", "Allowed passage.")
private = _seed_material(tmp_path, "private.txt", "Private passage.")
catalog = ReadingCatalogStore()
catalog.register_manifest(allowed)
catalog.register_manifest(private)
workspace = catalog.create_workspace(
"Mixed collection",
[allowed.material_id, private.material_id],
)
_save_learner_grant(learner["id"], allowed.material_id)
materials = client.get("/api/dashboard/learning-library/materials")
assert materials.status_code == 200, materials.text
assert [row["material_id"] for row in materials.json()["items"]] == [allowed.material_id]
assert private.material_id not in materials.text
collections = client.get("/api/dashboard/learning-library/reading")
assert collections.status_code == 200, collections.text
assert [row["workspace_id"] for row in collections.json()["items"]] == [workspace.workspace_id]
assert [tab["material"]["material_id"] for tab in collections.json()["items"][0]["tabs"]] == [
allowed.material_id
]
_save_learner_grant(learner["id"], allowed.material_id, allowed_surfaces=["chat"])
for kind in ("materials", "reading"):
denied = client.get(f"/api/dashboard/learning-library/{kind}")
assert denied.status_code == 403
assert "reading surface" in denied.json()["detail"]
def test_learning_navigation_index_filters_sources_without_opening_dashboard(
learner_client, as_user
):
client, learner, current_user, tmp_path = learner_client
with as_user(current_user.id, username="student"):
material = _seed_material(tmp_path, "navigation.txt", "Assigned reading.")
_save_learner_grant(learner["id"], material.material_id, allowed_surfaces=["reading"])
response = client.get("/api/dashboard/learning-index")
assert response.status_code == 200, response.text
sources = response.json()["sources"]
assert sources["books"] == sources["mastery"] == sources["practice"] == []
assert client.get("/api/dashboard/overview").status_code == 403
@pytest.mark.parametrize(
"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
@pytest.mark.parametrize("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)