Skip to content

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

fix(multi-user): restore prior grant if preset update fails

Bingxi Zhao (Frank)e750a8ddd035
diff --git a/deeptutor/api/routers/multi_user.py b/deeptutor/api/routers/multi_user.py
index 7d12576fb..aedb505be 100644
--- a/deeptutor/api/routers/multi_user.py
+++ b/deeptutor/api/routers/multi_user.py
@@ -26,6 +26,7 @@ from deeptutor.multi_user.device_credentials import revoke_device_credentials_fo
from deeptutor.multi_user.grants import (
LEARNING_AGE_BANDS,
LEARNING_SURFACES,
+ grant_path,
learner_grant,
load_grant,
normalize_grant,
@@ -58,6 +59,7 @@ from deeptutor.reading import ReadingStore
from deeptutor.reading.extensions import get_reading_extension_registry
from deeptutor.services.auth import POCKETBASE_ENABLED, hash_password
from deeptutor.services.config.model_catalog import ModelCatalogService
+from deeptutor.services.file_io import atomic_write_text
router = APIRouter()
@@ -687,6 +689,13 @@ async def put_guardian_restrictions(
policy["allowed_surfaces"] = payload.allowed_surfaces
reading["allow_upload"] = payload.allow_upload
reading["extensions"] = payload.extensions
+ needs_preset_update = learner_record.get("preset") != "learner"
+ previous_grant_path = grant_path(learner_user_id) if needs_preset_update else None
+ previous_grant_text = (
+ previous_grant_path.read_text(encoding="utf-8")
+ if previous_grant_path is not None and previous_grant_path.exists()
+ else None
+ )
try:
grant = normalize_grant(learner_user_id, grant)
validate_grant(grant)
@@ -694,8 +703,31 @@ 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")
+ if needs_preset_update:
+ preset_error: Exception | None = None
+ try:
+ preset_saved = set_preset(learner_username, "learner")
+ except Exception as exc:
+ preset_saved = False
+ preset_error = exc
+ if not preset_saved:
+ # The grant and account preset live in separate files. Restore the
+ # exact prior grant if the second write fails, including absence.
+ assert previous_grant_path is not None
+ try:
+ if previous_grant_text is None:
+ previous_grant_path.unlink(missing_ok=True)
+ else:
+ atomic_write_text(previous_grant_path, previous_grant_text)
+ except OSError as exc:
+ raise HTTPException(
+ status_code=500,
+ detail="Learner preset update failed and the prior grant could not be restored",
+ ) from exc
+ raise HTTPException(
+ status_code=500 if preset_error is not None else 409,
+ detail="Learner preset update failed; the prior grant was restored",
+ ) from preset_error
restrictions = _guardian_restrictions(grant)
_log_supervisor_action(
"guardian_restrictions_set",
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index c7a9b1a80..51d79c319 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -7,7 +7,9 @@ from pathlib import Path
from types import SimpleNamespace
import pytest
+from starlette.routing import Match
+from deeptutor.api.routers.auth import _learning_surface_for_path
from deeptutor.multi_user.context import (
get_current_user_or_none,
reset_current_user,
@@ -50,6 +52,52 @@ def _build_app() -> FastAPI:
return app
+ ("path", "route_path", "surface"),
+ [
+ ("/api/knowledge-bases", "/api/knowledge-bases", "reading"),
+ ("/api/knowledge-bases/demo", "/api/knowledge-bases/{kb_name}", "reading"),
+ ("/api/knowledge-bases/demo/files", "/api/knowledge-bases/{kb_name}/files", "reading"),
+ (
+ "/api/knowledge-bases/demo/files/a.pdf",
+ "/api/knowledge-bases/{kb_name}/files/{filename:path}",
+ "reading",
+ ),
+ (
+ "/api/knowledge-bases/demo/file-preview-text/a.pdf",
+ "/api/knowledge-bases/{kb_name}/file-preview-text/{filename:path}",
+ "reading",
+ ),
+ (
+ "/api/knowledge-bases/demo/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/rag-pipelines/lightrag/config",
+ "/api/knowledge-bases/rag-pipelines/lightrag/config",
+ "",
+ ),
+ ("/api/knowledge-bases/demo/config", "/api/knowledge-bases/{kb_name}/config", ""),
+ (
+ "/api/knowledge-bases/demo/github-sources",
+ "/api/knowledge-bases/{kb_name}/github-sources",
+ "",
+ ),
+ ],
+)
+def test_learner_surface_uses_actual_kb_route_template(
+ path: str, route_path: str, surface: str
+) -> None:
+ app = _build_app()
+ scope = {"type": "http", "method": "GET", "path": path, "root_path": ""}
+ matched = next(route for route in app.router.routes if route.matches(scope)[0] is Match.FULL)
+ assert matched.path == route_path
+ assert _learning_surface_for_path(path, "GET", route_path=matched.path) == surface
+
+
def test_knowledge_source_error_translation_is_consistent_and_sanitized() -> None:
translate = knowledge_router_module._knowledge_source_errors
diff --git a/tests/multi_user/test_learning_surface_map.py b/tests/multi_user/test_learning_surface_map.py
index d66588f59..1e8e16035 100644
--- a/tests/multi_user/test_learning_surface_map.py
+++ b/tests/multi_user/test_learning_surface_map.py
@@ -234,3 +234,64 @@ def test_failed_grant_save_does_not_change_standard_preset(
_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
+
+
+ ("preset_failure", "existing_grant", "status_code"),
+ [("returns_false", True, 409), ("raises", False, 500)],
+)
+def test_failed_preset_update_restores_previous_grant(
+ mu_isolated_root,
+ seed_user,
+ monkeypatch,
+ preset_failure: str,
+ existing_grant: bool,
+ status_code: int,
+) -> None:
+ import asyncio
+ from types import SimpleNamespace
+
+ from fastapi import HTTPException
+
+ from deeptutor.api.routers import multi_user
+ from deeptutor.multi_user.grants import grant_path, load_grant, save_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"]
+ if existing_grant:
+ save_grant(learner_user_id, {"enabled_tools": ["reason"]})
+ path = grant_path(learner_user_id)
+ previous_grant_text = path.read_text(encoding="utf-8") if path.exists() else None
+ payload = multi_user.GuardianRestrictionsPayload(
+ age_band="13-15",
+ allow_upload=True,
+ allowed_surfaces=["chat", "reading"],
+ extensions=[],
+ )
+
+ def fail_set_preset(_username: str, _preset: str) -> bool:
+ assert load_grant(learner_user_id)["learning_policy"]["age_band"] == "13-15"
+ if preset_failure == "raises":
+ raise OSError("users file is unavailable")
+ return False
+
+ monkeypatch.setattr(multi_user, "set_preset", fail_set_preset)
+ with pytest.raises(HTTPException) as error:
+ asyncio.run(
+ multi_user.put_guardian_restrictions(
+ learner_user_id,
+ payload,
+ SimpleNamespace(user_id="u_admin", role="admin"),
+ )
+ )
+
+ assert error.value.status_code == status_code
+ assert "prior grant was restored" in error.value.detail
+ _username, updated = get_user_by_id(learner_user_id)
+ assert updated["preset"] == "standard"
+ if previous_grant_text is None:
+ assert not path.exists()
+ else:
+ assert path.read_text(encoding="utf-8") == previous_grant_text