DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(marginnote4): close the device bridge's auth boundary
Bingxi Zhao (Frank)f58654e0bfeb
diff --git a/deeptutor/api/routers/marginnote4.py b/deeptutor/api/routers/marginnote4.pyindex 61d83d62e..d433dfc27 100644--- a/deeptutor/api/routers/marginnote4.py+++ b/deeptutor/api/routers/marginnote4.py@@ -18,6 +18,7 @@ Phase 1 scope: device pairing, incremental sync, heartbeat. Write-back to MN4from __future__ import annotationsimport logging+from pathlib import Pathfrom typing import Anyfrom fastapi import APIRouter, Depends, Header, HTTPException, Request@@ -25,36 +26,61 @@ from pydantic import BaseModel, Fieldfrom deeptutor.api.routers.auth import require_authfrom deeptutor.capabilities.marginnote4.models import MarginNoteObject, SyncBatch-from deeptutor.capabilities.marginnote4.store import MarginNoteStore+from deeptutor.capabilities.marginnote4.store import MarginNoteStore, default_db_path+from deeptutor.services.path_service import PathServicelogger = logging.getLogger(__name__)router = APIRouter()_auth = [Depends(require_auth)]+# Upper bound on objects (and tombstones) accepted from one sync request.+MAX_SYNC_BATCH = 2000-def _store_for(request: Request) -> MarginNoteStore:- """Resolve the MarginNote store from request context.- In Phase 1, a single default store serves all devices. When a KB name is- passed via the ``X-MN4-KB`` header, its dedicated database is used instead.+def _requested_kb(request: Request) -> str:+ """The MN4 library this request addresses.++ In Phase 1 a single default store serves all devices; ``X-MN4-KB`` selects+ a dedicated database instead. The header is only a *selector* — the device+ token is the credential, and it is checked against whichever store the+ header names, so naming another library grants nothing.+ """+ return request.headers.get("x-mn4-kb", "default")+++def _device_db_path(kb_name: str) -> Path:+ """The database the device-token endpoints address.++ Those endpoints carry no session, so ``get_path_service()`` would hand them+ whatever the ambient context happens to be — the default workspace in+ practice. Naming it explicitly keeps the sync path from drifting away from+ the store pairing wrote to, and gives :func:`pair_device` something to+ check itself against."""- kb_name = request.headers.get("x-mn4-kb", "default")- from deeptutor.capabilities.marginnote4.store import _default_db_path+ return default_db_path(kb_name, path_service=PathService.get_instance())- db_path = _default_db_path(kb_name)- return MarginNoteStore(db_path)++def _store_for(request: Request) -> MarginNoteStore:+ """Resolve (creating if absent) the store for a session-authenticated call."""+ return MarginNoteStore(default_db_path(_requested_kb(request)))def _auth_device(request: Request, authorization: str | None) -> tuple[str, MarginNoteStore]:- """Validate the device token and return ``(device_id, store)``."""+ """Validate the device token and return ``(device_id, store)``.++ Reached with no session, so nothing here may create state from+ caller-supplied input: ``open_existing`` keeps an unauthenticated request+ from materialising a directory and a schema'd database per distinct+ ``X-MN4-KB`` value.+ """if not authorization or not authorization.startswith("MarginNote "):raise HTTPException(401, "Missing or malformed Authorization header.")raw = authorization[len("MarginNote ") :]if ":" not in raw:raise HTTPException(401, "Invalid Authorization format.")device_id, token = raw.split(":", 1)- store = _store_for(request)- if not store.verify_token(device_id, token):+ store = MarginNoteStore.open_existing(_device_db_path(_requested_kb(request)))+ if store is None or not store.verify_token(device_id, token):raise HTTPException(403, "Invalid device credentials.")store.touch_device(device_id)return device_id, store@@ -64,8 +90,8 @@ def _auth_device(request: Request, authorization: str | None) -> tuple[str, Margclass PairRequest(BaseModel):- device_name: str = ""- device_kind: str = "macos"+ device_name: str = Field("", max_length=128)+ device_kind: str = Field("macos", max_length=32)class PairResponse(BaseModel):@@ -93,9 +119,12 @@ class SyncObjectIn(BaseModel):class SyncRequest(BaseModel):- cursor: str = ""- objects: list[SyncObjectIn] = Field(default_factory=list)- deleted_ids: list[str] = Field(default_factory=list)+ # One batch, not one library: the Add-on pages through its backlog, so an+ # unbounded list only ever meant a token holder could pin the event loop+ # and the database on a single request.+ cursor: str = Field("", max_length=256)+ objects: list[SyncObjectIn] = Field(default_factory=list, max_length=MAX_SYNC_BATCH)+ deleted_ids: list[str] = Field(default_factory=list, max_length=MAX_SYNC_BATCH)class SyncResponse(BaseModel):@@ -123,6 +152,17 @@ async def pair_device(body: PairRequest, request: Request) -> PairResponse:Returns a one-time token the Add-on stores and presents on every sync."""+ kb_name = _requested_kb(request)+ if default_db_path(kb_name) != _device_db_path(kb_name):+ # Pairing runs under a session and resolves the caller's own+ # workspace; /sync does not and resolves the default one. Where those+ # differ, pairing would hand out a token that 403s on every sync+ # forever, so refuse instead of issuing a dead credential.+ raise HTTPException(+ 501,+ "MN4 device sync is not available for this account yet: pairing and "+ "sync would resolve different workspaces.",+ )store = _store_for(request)device, token = store.pair_device(device_name=body.device_name, device_kind=body.device_kind)logger.info("Paired MN4 device %s (%s)", device.device_id, device.device_name)diff --git a/deeptutor/capabilities/marginnote4/binding.py b/deeptutor/capabilities/marginnote4/binding.pyindex fecfdad25..ee17c8cbb 100644--- a/deeptutor/capabilities/marginnote4/binding.py+++ b/deeptutor/capabilities/marginnote4/binding.py@@ -40,9 +40,9 @@ def _resolve(context: UnifiedContext) -> dict[str, str] | None:# one from the KB name so each connected library gets its own SQLite file.db_path = str(meta.get("db_path") or "").strip()if not db_path:- from deeptutor.capabilities.marginnote4.store import _default_db_path+ from deeptutor.capabilities.marginnote4.store import default_db_path- db_path = str(_default_db_path(ref))+ db_path = str(default_db_path(ref))return {"name": str(meta.get("name") or ref), "db_path": db_path}return Nonediff --git a/deeptutor/capabilities/marginnote4/store.py b/deeptutor/capabilities/marginnote4/store.pyindex 4784c3fd5..72b3f347c 100644--- a/deeptutor/capabilities/marginnote4/store.py+++ b/deeptutor/capabilities/marginnote4/store.py@@ -91,12 +91,20 @@ def _hash_token(token: str) -> str:return hashlib.sha256(token.encode()).hexdigest()-def _default_db_path(kb_name: str) -> Path:- """Default database location under DeepTutor's data directory."""+def default_db_path(kb_name: str, *, path_service: Any = None) -> Path:+ """Default database location under DeepTutor's data directory.++ ``path_service`` overrides whose workspace is used. The device-token+ endpoints carry no session, so they must name the workspace they mean+ rather than inherit whatever the ambient request context happens to be —+ see ``api/routers/marginnote4.py``.+ """safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in kb_name)- from deeptutor.services.path_service import get_path_service+ if path_service is None:+ from deeptutor.services.path_service import get_path_service- return get_path_service().user_data_dir / "marginnote4" / f"{safe}.db"+ path_service = get_path_service()+ return path_service.user_data_dir / "marginnote4" / f"{safe}.db"class MarginNoteStore:@@ -112,6 +120,21 @@ class MarginNoteStore:self.db_path.parent.mkdir(parents=True, exist_ok=True)self._init_schema()+ @classmethod+ def open_existing(cls, db_path: str | Path) -> "MarginNoteStore | None":+ """Open an already-paired store, or ``None`` when there is none.++ Constructing a store creates its directory and schema, so the+ device-token endpoints — which are reached *before* any credential has+ been checked — must not construct one from caller-supplied input. Use+ this instead: no file, no store, and nothing written to disk by an+ unauthenticated request.+ """+ path = Path(db_path)+ if not path.is_file():+ return None+ return cls(path)+# -- internal helpers ---------------------------------------------------def _connect(self) -> sqlite3.Connection:diff --git a/tests/api/test_marginnote4_router.py b/tests/api/test_marginnote4_router.pynew file mode 100644index 000000000..07d2a4bb1--- /dev/null+++ b/tests/api/test_marginnote4_router.py@@ -0,0 +1,163 @@+"""Auth boundary of the MarginNote 4 device bridge.++``/sync`` and ``/heartbeat`` are the only endpoints in the app reachable+without a DeepTutor session — a paired device presents+``Authorization: MarginNote <device_id>:<token>`` instead. Two properties of+that boundary are pinned here because both were wrong when the bridge landed:++* an unauthenticated request must not write anything to disk, and+* a token must not be issued into a workspace the sync path cannot read.++Mounted on a bare FastAPI app so the suite does not boot every other router.+"""++from __future__ import annotations++from pathlib import Path++from fastapi import FastAPI+from fastapi.testclient import TestClient+import pytest++from deeptutor.api.routers import marginnote4+from deeptutor.api.routers.auth import require_auth+from deeptutor.services.path_service import PathService+++def home(monkeypatch, tmp_path: Path) -> Path:+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ yield tmp_path+ PathService.reset_instance()+++def client(home: Path):+ app = FastAPI()+ app.include_router(marginnote4.router, prefix="/api/v1/marginnote4")+ # Session auth is the subject of its own tests; here it only needs to be+ # out of the way so the device boundary is what gets exercised.+ app.dependency_overrides[require_auth] = lambda: None+ with TestClient(app) as test_client:+ yield test_client+++def _mn4_dir() -> Path:+ return PathService.get_instance().user_data_dir / "marginnote4"+++def test_unauthenticated_sync_writes_nothing_to_disk(client) -> None:+ """A store is created by constructing it, so auth must come first.++ ``_store_for`` mkdir's and installs the schema. Reaching it before the+ token check turned ``POST /sync`` into an unauthenticated file-creation+ primitive: one database per distinct ``X-MN4-KB`` value, from a caller with+ no credentials at all.+ """+ for n in range(5):+ response = client.post(+ "/api/v1/marginnote4/sync",+ json={"cursor": "", "objects": [], "deleted_ids": []},+ headers={+ "Authorization": "MarginNote fake-device:fake-token",+ "X-MN4-KB": f"invented-{n}",+ },+ )+ assert response.status_code == 403++ assert not _mn4_dir().exists()+++def test_unauthenticated_heartbeat_writes_nothing_to_disk(client) -> None:+ response = client.post(+ "/api/v1/marginnote4/heartbeat",+ headers={+ "Authorization": "MarginNote fake-device:fake-token",+ "X-MN4-KB": "invented",+ },+ )+ assert response.status_code == 403+ assert not _mn4_dir().exists()+++ "header",+ [None, "Bearer abc", "MarginNote no-colon-here"],+)+def test_malformed_device_credentials_are_rejected(client, header) -> None:+ headers = {} if header is None else {"Authorization": header}+ response = client.post("/api/v1/marginnote4/heartbeat", headers=headers)+ assert response.status_code == 401+ assert not _mn4_dir().exists()+++def test_pair_then_sync_round_trip(client) -> None:+ paired = client.post("/api/v1/marginnote4/pair", json={"device_name": "iPad"})+ assert paired.status_code == 200, paired.text+ body = paired.json()++ auth = {"Authorization": f"MarginNote {body['device_id']}:{body['token']}"}+ synced = client.post(+ "/api/v1/marginnote4/sync",+ json={+ "cursor": "c1",+ "objects": [+ {"object_id": "o1", "object_type": "note", "title": "Attention"},+ ],+ "deleted_ids": [],+ },+ headers=auth,+ )+ assert synced.status_code == 200, synced.text+ assert synced.json()["stored"] == 1++ beat = client.post("/api/v1/marginnote4/heartbeat", headers=auth)+ assert beat.status_code == 200+ assert beat.json()["object_count"] == 1+++def test_revoked_device_cannot_sync(client) -> None:+ body = client.post("/api/v1/marginnote4/pair", json={}).json()+ assert client.delete(f"/api/v1/marginnote4/devices/{body['device_id']}").status_code == 200++ response = client.post(+ "/api/v1/marginnote4/heartbeat",+ headers={"Authorization": f"MarginNote {body['device_id']}:{body['token']}"},+ )+ assert response.status_code == 403+++def test_pair_refuses_when_sync_would_read_another_workspace(client, monkeypatch, tmp_path) -> None:+ """Pairing has a session, ``/sync`` does not — so they can resolve apart.++ ``/pair`` runs under ``require_auth`` and lands in the caller's own+ workspace; the device endpoints carry no session and resolve the default+ one. For any account where those differ, pairing used to succeed and then+ every sync 403'd forever. Refuse the credential instead of issuing a dead+ one.+ """+ monkeypatch.setattr(+ marginnote4,+ "_device_db_path",+ lambda kb_name: tmp_path / "some-other-workspace" / f"{kb_name}.db",+ )++ response = client.post("/api/v1/marginnote4/pair", json={})+ assert response.status_code == 501+ assert "different workspaces" in response.json()["detail"]+++def test_sync_batch_is_bounded(client) -> None:+ """An oversized batch is refused by validation, before any work starts."""+ body = client.post("/api/v1/marginnote4/pair", json={}).json()+ oversized = [+ {"object_id": f"o{i}", "object_type": "note"} for i in range(marginnote4.MAX_SYNC_BATCH + 1)+ ]++ response = client.post(+ "/api/v1/marginnote4/sync",+ json={"cursor": "", "objects": oversized, "deleted_ids": []},+ headers={"Authorization": f"MarginNote {body['device_id']}:{body['token']}"},+ )+ assert response.status_code == 422