Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(server): serve only indexed files from /file-content (#1393) (#1397)

Raghav Chamadiyab9b393d23168
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 62312e528..af75c112e 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -1081,21 +1081,53 @@ async def export_wiki(
)
+async def _is_indexed_file(session: AsyncSession, repo_id: str, file_path: str) -> bool:
+ """True when the indexer recorded ``file_path`` for this repo.
+
+ Same three-table existence test ``GET /files/{path}`` uses: which of them
+ is populated depends on the index tier, so any one of them counts.
+ """
+ if await crud.get_graph_node(session, repo_id, file_path) is not None:
+ return True
+ if await crud.get_git_metadata(session, repo_id, file_path) is not None:
+ return True
+ return bool(await crud.get_health_metrics(session, repo_id, file_paths=[file_path]))
+
+
@router.get("/{repo_id}/file-content")
async def get_file_content(
repo_id: str,
file_path: str = Query(...),
session: AsyncSession = Depends(get_db_session),
) -> PlainTextResponse:
- """Return raw file content from the repository's local checkout."""
+ """Return raw file content from the repository's local checkout.
+
+ Only files the indexer actually recorded are servable. Containment in the
+ repo root is not a sufficient guard on its own: ``.repowise/.env`` (the
+ user's provider API keys) and ``.git/config`` live inside the root too, so
+ the endpoint was an exfiltration path for anything under the checkout.
+ """
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
+ # Belt and braces alongside the index membership test below. Only the two
+ # directories that hold credentials are named: the traverser walks other
+ # dot-paths, so `.github/workflows/ci.yml` and `.eslintrc.json` are indexed
+ # files a reader can legitimately open.
+ segments = file_path.replace("\\", "/").split("/")
+ if segments and segments[0] in (".git", ".repowise"):
+ raise HTTPException(status_code=400, detail="Invalid file path")
+
+ # Cheap containment first: an out-of-tree probe shouldn't cost three queries.
base = Path(repo.local_path).resolve()
target = (base / file_path).resolve()
if not target.is_relative_to(base):
raise HTTPException(status_code=400, detail="Invalid file path")
+
+ if not await _is_indexed_file(session, repo_id, file_path):
+ raise HTTPException(status_code=404, detail=f"File not indexed: {file_path}")
+
if not target.is_file():
raise HTTPException(status_code=404, detail="File not found")
diff --git a/tests/unit/server/test_file_content_guard.py b/tests/unit/server/test_file_content_guard.py
new file mode 100644
index 000000000..55ff99904
--- /dev/null
+++ b/tests/unit/server/test_file_content_guard.py
@@ -0,0 +1,119 @@
+"""Tests for GET /api/repos/{id}/file-content — what it will and won't serve.
+
+The endpoint used to serve anything under the repo root, which put
+``.repowise/.env`` (the user's provider API keys) and ``.git/config`` one
+query string away.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphNode
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _index_file(session_factory, repo_id: str, node_id: str) -> None:
+ async with get_session(session_factory) as session:
+ session.add(
+ GraphNode(
+ repository_id=repo_id,
+ node_type="file",
+ language="python",
+ node_id=node_id,
+ )
+ )
+
+
+async def test_serves_indexed_file(client: AsyncClient, app, tmp_path: Path) -> None:
+ repo = await create_test_repo(client, tmp_path)
+ root = Path(repo["local_path"])
+ (root / "src").mkdir()
+ (root / "src" / "main.py").write_text("print('hi')\n")
+ await _index_file(app.state.session_factory, repo["id"], "src/main.py")
+
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/file-content", params={"file_path": "src/main.py"}
+ )
+ assert resp.status_code == 200
+ assert resp.text == "print('hi')\n"
+
+
+async def test_serves_indexed_dot_paths(client: AsyncClient, app, tmp_path: Path) -> None:
+ """The traverser walks `.github` and friends, so those files stay readable.
+
+ Only `.git/` and `.repowise/` are refused; a blanket dot rule would 400
+ indexed, harmless files like workflows and `.eslintrc.json`.
+ """
+ repo = await create_test_repo(client, tmp_path)
+ root = Path(repo["local_path"])
+ (root / ".github" / "workflows").mkdir(parents=True)
+ (root / ".github" / "workflows" / "ci.yml").write_text("on: push\n")
+ await _index_file(app.state.session_factory, repo["id"], ".github/workflows/ci.yml")
+
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/file-content",
+ params={"file_path": ".github/workflows/ci.yml"},
+ )
+ assert resp.status_code == 200
+ assert resp.text == "on: push\n"
+
+
+async def test_refuses_dotfiles_holding_credentials(
+ client: AsyncClient, app, tmp_path: Path
+) -> None:
+ """The provider keys and the git remote config are both inside the root.
+
+ Indexed here on purpose: the deny must not depend on the traverser
+ continuing to skip those two directories.
+ """
+ repo = await create_test_repo(client, tmp_path)
+ root = Path(repo["local_path"])
+ (root / ".repowise").mkdir()
+ (root / ".repowise" / ".env").write_text("ANTHROPIC_API_KEY=sk-ant-secret\n")
+ (root / ".git" / "config").write_text("[remote]\n\turl = https://user:token@host/x\n")
+
+ for path in (".repowise/.env", ".git/config"):
+ await _index_file(app.state.session_factory, repo["id"], path)
+
+ for path in (".repowise/.env", ".git/config"):
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/file-content", params={"file_path": path}
+ )
+ assert resp.status_code == 400, path
+ assert "sk-ant-secret" not in resp.text
+ assert "token" not in resp.text
+
+
+async def test_refuses_unindexed_file(client: AsyncClient, app, tmp_path: Path) -> None:
+ """Present on disk and inside the root is not enough on its own."""
+ repo = await create_test_repo(client, tmp_path)
+ (Path(repo["local_path"]) / "secrets.txt").write_text("shh\n")
+
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/file-content", params={"file_path": "secrets.txt"}
+ )
+ assert resp.status_code == 404
+ assert "shh" not in resp.text
+
+
+async def test_refuses_traversal_outside_the_root(
+ client: AsyncClient, app, tmp_path: Path
+) -> None:
+ repo = await create_test_repo(client, tmp_path)
+ (tmp_path / "outside.txt").write_text("nope\n")
+
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/file-content", params={"file_path": "../outside.txt"}
+ )
+ assert resp.status_code == 400
+ assert "nope" not in resp.text