DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(knowledge): secure and reconcile web source sync
Bingxi Zhao (Frank)5684e6eab4d9
diff --git a/deeptutor/services/web_source/crawler.py b/deeptutor/services/web_source/crawler.pyindex 24b339142..12b8f4417 100644--- a/deeptutor/services/web_source/crawler.py+++ b/deeptutor/services/web_source/crawler.py@@ -21,7 +21,7 @@ import hashlibimport loggingfrom pathlib import Pathimport re-from urllib.parse import urldefrag, urljoin, urlparse+from urllib.parse import quote, unquote, urldefrag, urljoin, urlparseimport httpx@@ -43,6 +43,7 @@ DEFAULT_MAX_PAGES = 200MAX_CRAWL_DEPTH = 5MAX_CRAWL_PAGES = DEFAULT_MAX_PAGESDEFAULT_CONCURRENCY = 8+MAX_REDIRECTS = 5@dataclass(frozen=True)@@ -137,10 +138,45 @@ def _to_filename(url: str, base_path_prefix: str) -> str:parsed = urlparse(url)path = parsed.path.strip("/")if not path:- return "index.md"- # Preserve full path structure to avoid cross-source filename collisions- segments = [s for s in path.split("/") if s]- return "/".join(segments) + ".md"+ filename = "index"+ else:+ # Decode one URL component at a time, then quote it back into one+ # filesystem-safe component. Encoded slashes and dot segments must+ # never turn into traversal below the KB's ``raw/`` directory.+ segments: list[str] = []+ for raw_segment in path.split("/"):+ if not raw_segment:+ continue+ decoded = unquote(raw_segment)+ safe = quote(decoded, safe="-_.~")+ if decoded in {".", ".."} or safe in {".", ".."}:+ safe = f"segment-{hashlib.sha256(raw_segment.encode()).hexdigest()[:10]}"+ segments.append(safe or "segment")+ filename = "/".join(segments) or "index"++ # Query-backed documentation routes may share a path while rendering+ # different pages. Keep them distinct without exposing raw query data.+ if parsed.query:+ filename += f"-q-{hashlib.sha256(parsed.query.encode()).hexdigest()[:10]}"+ return filename + ".md"+++def _source_filename(source: dict, page_url: str, base_path_prefix: str) -> str:+ """Namespace a page so independent web sources cannot overwrite it."""+ identity = str(source.get("url") or source.get("id") or "")+ namespace = hashlib.sha256(identity.encode("utf-8")).hexdigest()[:16]+ return f"_web/{namespace}/{_to_filename(page_url, base_path_prefix)}"+++def _contained_path(root: Path, relative: str) -> Path | None:+ """Resolve *relative* below *root*, rejecting legacy traversal metadata."""+ root_resolved = root.resolve()+ candidate = (root_resolved / relative).resolve()+ try:+ candidate.relative_to(root_resolved)+ except ValueError:+ return None+ return candidate# Status codes worth retrying (transient server/infrastructure issues).@@ -158,22 +194,45 @@ async def _fetch_page(Retries up to ``_MAX_RETRIES`` times on transient status codes (429,5xx) and network errors, with exponential backoff."""- last_error = None- for attempt in range(_MAX_RETRIES + 1):+ current_url = url+ redirects = 0+ attempt = 0+ while True:+ parsed = urlparse(current_url)+ host = (parsed.hostname or "").strip()+ if parsed.scheme.lower() not in ("http", "https") or not host:+ logger.warning("Crawl: redirect to invalid URL %s blocked", current_url)+ return None+ # Validate every redirect hop before sending its request. Automatic+ # redirects followed by a final-host check have already contacted a+ # private target by the time they can be rejected.+ if _is_disallowed_host(host):+ logger.warning("Crawl: request to disallowed host %s blocked", host)+ return Nonetry:async with client.stream("GET",- url,+ current_url,headers={"User-Agent": DEFAULT_USER_AGENT,"Accept": "text/html,application/xhtml+xml,*/*;q=0.5",},- follow_redirects=True,+ follow_redirects=False,) as response:+ if response.status_code in {301, 302, 303, 307, 308}:+ location = response.headers.get("location", "").strip()+ if not location or redirects >= MAX_REDIRECTS:+ logger.warning("Crawl: invalid or excessive redirects for %s", url)+ return None+ current_url = urljoin(current_url, location)+ redirects += 1+ attempt = 0+ continue+final_url = str(response.url)final_host = (urlparse(final_url).hostname or "").strip()- if final_host and _is_disallowed_host(final_host):- logger.warning("Crawl: redirect to disallowed host %s blocked", final_host)+ if not final_host or _is_disallowed_host(final_host):+ logger.warning("Crawl: response from disallowed host %s blocked", final_host)return Noneif response.status_code in _RETRY_STATUS and attempt < _MAX_RETRIES:@@ -181,33 +240,35 @@ async def _fetch_page(logger.debug("Crawl: HTTP %d for %s, retrying in %.1fs",response.status_code,- url,+ current_url,backoff,)await asyncio.sleep(backoff)+ attempt += 1continueif response.status_code >= 400:- logger.debug("Crawl: HTTP %d for %s", response.status_code, url)+ logger.debug("Crawl: HTTP %d for %s", response.status_code, current_url)return Nonehtml = await _bounded_read(response, MAX_RESPONSE_BYTES)return html, final_urlexcept httpx.HTTPError as exc:- last_error = excif attempt < _MAX_RETRIES:backoff = 0.5 * (2**attempt)logger.debug(- "Crawl: network error for %s: %s, retrying in %.1fs", url, exc, backoff+ "Crawl: network error for %s: %s, retrying in %.1fs",+ current_url,+ exc,+ backoff,)await asyncio.sleep(backoff)+ attempt += 1continue- logger.debug("Crawl: network error for %s: %s (giving up)", url, exc)+ logger.debug("Crawl: network error for %s: %s (giving up)", current_url, exc)return None- return None-async def _process_page(url: str,@@ -479,7 +540,7 @@ async def crawl_and_diff(2. Build ``{filename: content_hash}`` for every page.3. Compare with ``source["page_hashes"]`` to compute added/updated/removed.4. Write new/changed pages to ``raw_dir``.- 5. Remove deleted pages from ``raw_dir``.+ 5. Report deleted pages for the caller to remove from raw storage and index.6. Build a navigation manifest.The caller is responsible for indexing and metadata persistence.@@ -512,7 +573,7 @@ async def crawl_and_diff(page_files: list[str] = []for page in result.pages:- fname = _to_filename(page.url, base_path_prefix)+ fname = _source_filename(source, page.url, base_path_prefix)current[fname] = page.content_hashpage_contents[fname] = page.markdownpage_urls[fname] = page.url@@ -531,7 +592,13 @@ async def crawl_and_diff(elif old != chash:updated.append(fname)else:- unchanged.append(fname)+ target = _contained_path(raw_dir, fname)+ if target is not None and target.is_file():+ unchanged.append(fname)+ else:+ # Metadata can outlive a manually removed/corrupt raw file.+ # Re-stage it even though the remote content hash is stable.+ updated.append(fname)for fname in old_hashes:if fname not in current:@@ -543,18 +610,15 @@ async def crawl_and_diff(content = page_contents.get(fname, "")page_url = page_urls.get(fname, "")full_content = f"<!-- source: {page_url} -->\n\n{content}"- dest = raw_dir / fname+ dest = _contained_path(raw_dir, fname)+ if dest is None:+ return CrawlDiff(ok=False, error=f"Unsafe page filename: {fname}", url=url)dest.parent.mkdir(parents=True, exist_ok=True)dest.write_text(full_content, encoding="utf-8")changed_paths.append(str(dest))- # 5. Remove deleted pages- for fname in removed:- target = raw_dir / fname- if target.exists():- target.unlink()-- # 6. Build navigation manifest+ # 5. Build navigation manifest. Deletions are deliberately left to the+ # caller, which must purge both the raw file and the retrieval index.nav_manifest = build_navigation_manifest(result.navigation_links,result.navigation_kind,diff --git a/deeptutor/services/web_source/sync.py b/deeptutor/services/web_source/sync.pyindex b2a986e87..0bcba2d7c 100644--- a/deeptutor/services/web_source/sync.py+++ b/deeptutor/services/web_source/sync.py@@ -18,7 +18,7 @@ from pathlib import Pathfrom typing import Anyfrom deeptutor.knowledge.add_documents import DEFAULT_BASE_DIR-from deeptutor.services.web_source.crawler import crawl_and_diff+from deeptutor.services.web_source.crawler import _contained_path, crawl_and_difflogger = logging.getLogger(__name__)@@ -73,6 +73,27 @@ def _record_sync_failure(logger.exception("Failed to persist web-source sync failure state")+async def _rebuild_index_after_removal(+ kb_name: str,+ raw_dir: Path,+ base_dir: str,+) -> int:+ """Rebuild the bound provider so removed pages cannot remain retrievable."""+ from deeptutor.services.rag.file_routing import FileTypeRouter+ from deeptutor.services.rag.service import RAGService++ files = FileTypeRouter.collect_supported_files(raw_dir, recursive=True)+ if not files:+ raise RuntimeError("No source files remain after removing deleted web pages")+ success = await RAGService(kb_base_dir=base_dir).initialize(+ kb_name=kb_name,+ file_paths=[str(path) for path in files],+ )+ if not success:+ raise RuntimeError("The knowledge-base index rebuild produced no documents")+ return len(files)++async def sync_source(kb_name: str,source: dict[str, Any],@@ -108,10 +129,35 @@ async def sync_source(_record_sync_failure(kb_name, source["id"], base_dir, diff.error)return WebSyncResult(ok=False, error=diff.error)- # Index changed files via the standard KB pipeline (legacy per-file).- indexed = 0- if diff.changed_paths:+ # Remove deleted raw pages and their file-hash records first. A full+ # provider rebuild below is required because most providers do not expose+ # a reliable per-document vector deletion operation.+ removed_count = 0+ removal_errors: list[str] = []+ for fname in diff.pages_removed:+ target = _contained_path(raw_dir, fname)+ if target is None:+ removal_errors.append(f"{fname}: path escapes the knowledge base")+ continuetry:+ from deeptutor.knowledge.add_documents import remove_raw_document++ remove_raw_document(kb_dir, target)+ removed_count += 1+ except Exception as exc:+ logger.warning("Failed to remove %s: %s", fname, exc)+ removal_errors.append(f"{fname}: {exc}")++ if removal_errors:+ error = "Failed to remove deleted pages: " + "; ".join(removal_errors)+ _record_sync_failure(kb_name, source["id"], base_dir, error)+ return WebSyncResult(ok=False, error=error)++ indexed = 0+ try:+ if diff.pages_removed:+ indexed = await _rebuild_index_after_removal(kb_name, raw_dir, base_dir)+ elif diff.changed_paths:from deeptutor.knowledge.add_documents import add_documentsindexed = await add_documents(@@ -120,29 +166,9 @@ async def sync_source(base_dir=base_dir,allow_duplicates=False,)- except Exception as exc:- logger.warning("Indexing failed for web source files: %s", exc)- error = f"Indexing failed: {exc}"- _record_sync_failure(kb_name, source["id"], base_dir, error)- return WebSyncResult(ok=False, error=error)-- # Remove deleted pages from index (legacy per-file removal).- removed_count = 0- removal_errors: list[str] = []- for fname in diff.pages_removed:- target = raw_dir / fname- if target.exists():- try:- from deeptutor.knowledge.add_documents import remove_raw_document-- remove_raw_document(kb_dir, target)- removed_count += 1- except Exception as exc:- logger.warning("Failed to remove %s: %s", fname, exc)- removal_errors.append(f"{fname}: {exc}")-- if removal_errors:- error = "Failed to remove deleted pages: " + "; ".join(removal_errors)+ except Exception as exc:+ logger.warning("Indexing failed for web source files: %s", exc)+ error = f"Indexing failed: {exc}"_record_sync_failure(kb_name, source["id"], base_dir, error)return WebSyncResult(ok=False, error=error)diff --git a/tests/services/test_web_source_sync.py b/tests/services/test_web_source_sync.pyindex 20b0ea5f1..1312c9716 100644--- a/tests/services/test_web_source_sync.py+++ b/tests/services/test_web_source_sync.py@@ -2,17 +2,22 @@from __future__ import annotations+import jsonfrom pathlib import Pathfrom unittest.mock import AsyncMock, patch+import httpximport pytestfrom deeptutor.services.web_source.crawler import (CrawledPage,CrawlResult,+ _fetch_page,_is_internal,_normalise_link,+ _source_filename,_to_filename,+ crawl_and_diff,)from deeptutor.services.web_source.sync import WebSyncResult, sync_source@@ -58,6 +63,33 @@ def test_to_filename_no_prefix_collision():assert en != zh+def test_to_filename_contains_traversal_and_distinguishes_queries():+ traversal = _to_filename("https://a.com/../../outside", "/")+ assert ".." not in Path(traversal).parts+ first = _to_filename("https://a.com/docs/search?q=alpha", "/docs")+ second = _to_filename("https://a.com/docs/search?q=beta", "/docs")+ assert first != second+++async def test_fetch_page_blocks_private_redirect_before_request():+ requested: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ requested.append(str(request.url))+ return httpx.Response(302, headers={"location": "http://127.0.0.1/private"})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with patch(+ "deeptutor.services.web_source.crawler._is_disallowed_host",+ side_effect=lambda host: host == "127.0.0.1",+ ):+ result = await _fetch_page("https://docs.example.com/start", client=client)++ assert result is None+ assert requested == ["https://docs.example.com/start"]++def _make_kb(tmp_path: Path, kb_name: str = "kb") -> tuple[str, Path]:from deeptutor.knowledge.manager import KnowledgeBaseManager@@ -109,8 +141,8 @@ async def test_sync_source_first_run(tmp_path: Path):# (no prefix stripping) so multiple web sources sharing one KB# never collide.raw = kb_dir / "raw"- assert (raw / "docs.md").exists()- assert (raw / "docs" / "intro.md").exists()+ assert len(list(raw.rglob("docs.md"))) == 1+ assert len(list(raw.rglob("intro.md"))) == 1@pytest.mark.asyncio@@ -121,7 +153,11 @@ async def test_sync_source_unchanged_pages(tmp_path: Path):mgr = KnowledgeBaseManager(base_dir=base_dir)source = mgr.add_web_source("kb", "https://example.com/docs/")# Pre-populate hashes to simulate prior sync- source["page_hashes"] = {"docs.md": "aaa"}+ filename = _source_filename(source, "https://example.com/docs/", "/docs/")+ source["page_hashes"] = {filename: "aaa"}+ unchanged_path = kb_dir / "raw" / filename+ unchanged_path.parent.mkdir(parents=True, exist_ok=True)+ unchanged_path.write_text("# Home", encoding="utf-8")mock_result = CrawlResult(pages=[@@ -173,7 +209,8 @@ async def test_sync_source_indexing_failure_keeps_previous_hashes(tmp_path: Pathmanager = KnowledgeBaseManager(base_dir=base_dir)source = manager.add_web_source("kb", "https://example.com/docs/")- source["page_hashes"] = {"docs.md": "old"}+ filename = _source_filename(source, "https://example.com/docs/", "/docs/")+ source["page_hashes"] = {filename: "old"}manager.update_web_source_state("kb", source["id"], page_hashes=source["page_hashes"])result = CrawlResult(pages=[@@ -201,7 +238,79 @@ async def test_sync_source_indexing_failure_keeps_previous_hashes(tmp_path: Pathstate = manager.get_web_sources("kb")[0]assert state["last_sync_status"] == "error"assert "index unavailable" in state["last_sync_error"]- assert state["page_hashes"] == {"docs.md": "old"}+ assert state["page_hashes"] == {filename: "old"}+++async def test_sources_with_same_page_path_use_distinct_raw_files(tmp_path: Path):+ raw_dir = tmp_path / "raw"+ source_a = {"id": "a", "url": "https://a.example/docs", "page_hashes": {}}+ source_b = {"id": "b", "url": "https://b.example/docs", "page_hashes": {}}+ crawls = [+ CrawlResult(pages=[CrawledPage("https://a.example/docs/intro", "A", "body A", "a")]),+ CrawlResult(pages=[CrawledPage("https://b.example/docs/intro", "B", "body B", "b")]),+ ]++ with patch(+ "deeptutor.services.web_source.crawler.crawl_docs_site",+ new_callable=AsyncMock,+ ) as mock_crawl:+ mock_crawl.side_effect = crawls+ first = await crawl_and_diff(source_a, raw_dir)+ second = await crawl_and_diff(source_b, raw_dir)++ assert first.changed_paths != second.changed_paths+ assert all(Path(path).exists() for path in first.changed_paths + second.changed_paths)+++async def test_removed_page_is_purged_before_full_index_rebuild(tmp_path: Path):+ base_dir, kb_dir = _make_kb(tmp_path)+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=base_dir)+ source = manager.add_web_source("kb", "https://example.com/docs/")+ old_name = _source_filename(source, "https://example.com/docs/old", "/docs/")+ source["page_hashes"] = {old_name: "old"}+ manager.update_web_source_state("kb", source["id"], page_hashes=source["page_hashes"])+ old_path = kb_dir / "raw" / old_name+ old_path.parent.mkdir(parents=True, exist_ok=True)+ old_path.write_text("old page", encoding="utf-8")+ metadata_path = kb_dir / "metadata.json"+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ metadata["file_hashes"] = {old_name: "old"}+ metadata_path.write_text(json.dumps(metadata), encoding="utf-8")++ crawl = CrawlResult(+ pages=[+ CrawledPage(+ "https://example.com/docs/current",+ "Current",+ "current page",+ "current",+ )+ ]+ )+ with patch(+ "deeptutor.services.web_source.crawler.crawl_docs_site",+ new_callable=AsyncMock,+ return_value=crawl,+ ):+ with patch(+ "deeptutor.services.rag.service.RAGService.initialize",+ new_callable=AsyncMock,+ return_value=True,+ ) as rebuild:+ outcome = await sync_source("kb", source, base_dir=base_dir)++ assert outcome.ok is True+ assert outcome.pages_removed == 1+ assert not old_path.exists()+ assert rebuild.await_count == 1+ rebuilt_paths = rebuild.await_args.kwargs["file_paths"]+ assert all(old_name not in path for path in rebuilt_paths)+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ assert old_name not in metadata.get("file_hashes", {})# ── Navigation extraction tests ──────────────────────────────────────