Skip to content

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

fix(partners): let a partner's presented file download for the person who asked

Bingxi Zhao (Frank)4afc7eccb67e
diff --git a/deeptutor/api/routers/workspace.py b/deeptutor/api/routers/workspace.py
index 937732c19..a91a8ac53 100644
--- a/deeptutor/api/routers/workspace.py
+++ b/deeptutor/api/routers/workspace.py
@@ -2,13 +2,22 @@
from __future__ import annotations
+from pathlib import Path
+
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import FileResponse
from pydantic import BaseModel
from deeptutor.api.routers.auth import require_auth
+from deeptutor.multi_user.partner_access import visible_partners
+from deeptutor.multi_user.paths import user_context
from deeptutor.services.auth import TokenPayload
-from deeptutor.services.workspace import WorkspaceError, get_content_workspace_service
+from deeptutor.services.partners.scope import partner_user
+from deeptutor.services.workspace import (
+ WorkspaceError,
+ WorkspaceItem,
+ get_content_workspace_service,
+)
settings_router = APIRouter()
files_router = APIRouter()
@@ -38,6 +47,38 @@ async def update_workspace(payload: WorkspacePathPayload) -> dict:
return service.describe_current()
+def _resolve_partner_item(
+ workspace_id: str, workspace_item_id: str
+) -> tuple[Path, WorkspaceItem] | None:
+ """Resolve a presentation one of the caller's partners published.
+
+ A partner web chat runs inside a synthetic workspace under
+ ``data/partners/<id>/workspace``, so ``workspace_present`` writes its
+ manifest to that scope's private presentation store. The human caller's own
+ bindings never name that workspace, ``binding_by_id`` refuses it, and the
+ attachment sitting in the transcript 404s on click (#1267).
+
+ ``/files/outputs`` grew the same reach in #1012 — see
+ ``_resolve_partner_output`` — and this is the other artifact URL shape. It
+ does not need that endpoint's unique-match rule: a workspace id is derived
+ from the owning user id together with the physical root and re-derived
+ before a stored row is trusted, so a hit inside a partner scope belongs to
+ that partner by construction, where a relative output path can collide.
+ """
+ for partner in visible_partners():
+ partner_id = str(partner.get("partner_id") or "").strip()
+ if not partner_id:
+ continue
+ with user_context(partner_user(partner_id)):
+ try:
+ return get_content_workspace_service().resolve_published_item(
+ workspace_id, workspace_item_id
+ )
+ except WorkspaceError:
+ continue
+ return None
+
+
@files_router.get("/{workspace_id}/{workspace_item_id}", operation_id="read_workspace_item_get")
@files_router.head("/{workspace_id}/{workspace_item_id}", operation_id="read_workspace_item_head")
async def read_workspace_item(
@@ -50,7 +91,12 @@ async def read_workspace_item(
workspace_id, workspace_item_id
)
except WorkspaceError as exc:
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="File not found") from exc
+ resolved = _resolve_partner_item(workspace_id, workspace_item_id)
+ if resolved is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="File not found"
+ ) from exc
+ path, item = resolved
return FileResponse(
path,
media_type=item.mime_type,
diff --git a/tests/api/test_workspace_router.py b/tests/api/test_workspace_router.py
index 67813285c..379ab49a9 100644
--- a/tests/api/test_workspace_router.py
+++ b/tests/api/test_workspace_router.py
@@ -70,3 +70,78 @@ def test_workspace_item_endpoint_serves_the_published_snapshot(workspace_api) ->
assert "inline" in response.headers["content-disposition"]
assert response.headers["x-content-type-options"] == "nosniff"
assert response.headers["content-security-policy"].startswith("sandbox;")
+
+
+def partner_workspace_api(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Two scopes behind one request: the human caller's, and a partner's.
+
+ ``get_path_service`` is what the multi-user layer re-points when a scope is
+ installed, so a scope-aware stand-in for it is what makes the partner
+ lookup real rather than mocked.
+ """
+ from deeptutor.multi_user.context import get_current_user_or_none
+ from deeptutor.services.partners.scope import partner_user_id
+
+ module = importlib.import_module("deeptutor.api.routers.workspace")
+ service_module = importlib.import_module("deeptutor.services.workspace.service")
+ human = PathService(workspace_root=tmp_path / "human")
+ partner = PathService(workspace_root=tmp_path / "partner")
+ for paths in (human, partner):
+ paths.ensure_all_directories()
+
+ def scoped_path_service() -> PathService:
+ current = get_current_user_or_none()
+ if current is not None and current.id == partner_user_id("math-bot"):
+ return partner
+ return human
+
+ monkeypatch.setattr(service_module, "get_path_service", scoped_path_service)
+ monkeypatch.setattr(module, "get_content_workspace_service", ContentWorkspaceService)
+ monkeypatch.setattr(module, "visible_partners", lambda: [{"partner_id": "math-bot"}])
+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("DEEPTUTOR_WORKSPACE_ROOT", raising=False)
+ monkeypatch.delenv("DEEPTUTOR_WORKSPACE_ALLOWED_ROOTS", raising=False)
+
+ app = FastAPI()
+ app.include_router(module.files_router, prefix="/files/workspace-items")
+ return TestClient(app), scoped_path_service
+
+
+def _publish_in_partner_scope(paths: PathService, filename: str, body: str):
+ from deeptutor.multi_user.paths import user_context
+ from deeptutor.services.partners.scope import partner_user
+
+ with user_context(partner_user("math-bot")):
+ service = ContentWorkspaceService()
+ binding = service.current_binding(ensure_output=True)
+ (binding.root / filename).write_text(body, encoding="utf-8")
+ return service.publish(binding, [{"path": filename}])[0]
+
+
+def test_a_partner_chats_generated_file_downloads_for_the_person_who_asked(
+ partner_workspace_api,
+) -> None:
+ """#1267: the attachment is published in the partner's scope, clicked in ours.
+
+ A partner web chat runs as a synthetic user, so ``workspace_present``
+ writes its manifest under ``data/partners/<id>/workspace``. Resolving the
+ download against the caller's own bindings alone 404s a file the
+ transcript is still offering them.
+ """
+ client, scoped = partner_workspace_api
+ item = _publish_in_partner_scope(scoped(), "architecture.md", "godot notes")
+
+ response = client.get(item.url)
+
+ assert response.status_code == 200
+ assert response.text == "godot notes"
+
+
+def test_an_unpublished_item_is_still_not_found(partner_workspace_api) -> None:
+ """The fallback widens the caller's reach, it does not open the store."""
+ client, _ = partner_workspace_api
+
+ response = client.get(f"/files/workspace-items/ws_{'0' * 32}/wsi_{'0' * 32}")
+
+ assert response.status_code == 404