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): decide keyless access from the peer address, not REPOWISE_HOST (#1391) (#1401)

Raghav Chamadiyafc1d10ea334a
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 687917775..d57ce579c 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -1,6 +1,13 @@
#!/bin/bash
set -e
+# Both servers bind 0.0.0.0 inside the container, so without a key the only
+# thing standing between the API and the network is the port publishing.
+if [ -z "${REPOWISE_API_KEY}" ]; then
+ echo "WARNING: REPOWISE_API_KEY is not set. Requests from outside the container" \
+ "will be refused; the API is only usable from inside it. Set REPOWISE_API_KEY."
+fi
+
# Start the FastAPI backend
echo "Starting repowise API server on port ${PORT_BACKEND}..."
uvicorn repowise.server.app:create_app \
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 8b47ead01..0d07f325a 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -647,7 +647,7 @@ The `.repowise/.env` file is gitignored automatically.
| `REPOWISE_PORT` | API server port (default: `7337`) |
| `REPOWISE_MCP_PORT` | MCP SSE server port (default: `7338`) |
| `REPOWISE_API_URL` | Frontend only; backend URL for the web UI (default: `http://localhost:7337`) |
-| `REPOWISE_API_KEY` | Bearer token required by clients calling the server API |
+| `REPOWISE_API_KEY` | Bearer token required by clients calling the server API. Without it the server answers local callers only, and refuses any request from another host with 403 |
| `REPOWISE_CONFIG_DIR` | Override where repowise looks for its config directory |
| `REPOWISE_GITHUB_WEBHOOK_SECRET` | Secret for verifying GitHub webhook signatures |
| `REPOWISE_GITLAB_WEBHOOK_TOKEN` | Token for verifying GitLab webhook requests |
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.py
index 6a88f8080..93879e7e9 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py
@@ -490,17 +490,23 @@ def _start_frontend(
backend_port: int,
frontend_port: int,
local_web: Path | None = None,
+ host: str = "127.0.0.1",
) -> subprocess.Popen | None:
"""Start the Next.js frontend server. Returns the process or None.
If ``local_web`` is provided, the local monorepo build is used as Option 1.
Pass ``None`` to skip the local build (e.g. when it's stale or refresh was
forced) and use only the cached tarball at ``~/.repowise/web``.
+
+ ``host`` is the API's bind address, and the UI takes the same one. The UI
+ rewrites ``/api/*`` to the API on loopback (packages/web/src/middleware.ts),
+ so a UI on the wildcard while the API is loopback-only handed the whole API
+ to the network through the proxy, with every request looking local.
"""
env = {
**os.environ,
"REPOWISE_API_URL": f"http://localhost:{backend_port}",
- "HOSTNAME": "0.0.0.0",
+ "HOSTNAME": host,
"PORT": str(frontend_port),
}
@@ -596,6 +602,18 @@ def serve_command(
os.environ["REPOWISE_DB_URL"] = f"sqlite+aiosqlite:///{local_db.as_posix()}"
console.print(f"[dim]Using local database: {local_db}[/dim]")
+ # The server reads REPOWISE_HOST to describe its own bind. Nothing used to
+ # set it from --host, so `serve --host 0.0.0.0` left the auth layer
+ # believing it was loopback-only. Set before the app is imported (uvicorn
+ # imports the factory below, and workers inherit the environment).
+ os.environ["REPOWISE_HOST"] = host
+ if not os.environ.get("REPOWISE_API_KEY") and host not in ("127.0.0.1", "localhost", "::1"):
+ console.print(
+ f"[yellow]Binding to {host} without REPOWISE_API_KEY: non-local requests "
+ f"will be refused.[/yellow]\n"
+ "[dim]Set REPOWISE_API_KEY to allow them, or bind to 127.0.0.1.[/dim]"
+ )
+
# Resolve a usable API port up front — uvicorn would otherwise crash later
# with a bare OSError, and the chosen port needs to flow into the frontend
# via REPOWISE_API_URL.
@@ -604,9 +622,9 @@ def serve_command(
frontend_proc: subprocess.Popen | None = None
if not no_ui:
- # The Next.js server binds to 0.0.0.0 (see HOSTNAME below), so probe
- # there — a port can be free on 127.0.0.1 but taken on the wildcard.
- ui_port = _find_free_port("0.0.0.0", ui_port, "web UI")
+ # The Next.js server takes the same bind as the API (see HOSTNAME
+ # below), so probe there.
+ ui_port = _find_free_port(host, ui_port, "web UI")
node = _node_available()
npm = _npm_available()
@@ -669,7 +687,9 @@ def serve_command(
ready = _download_web(__version__)
if ready:
- frontend_proc = _start_frontend(node, port, ui_port, local_web=local_web)
+ frontend_proc = _start_frontend(
+ node, port, ui_port, local_web=local_web, host=host
+ )
if frontend_proc:
console.print(f"[green]Web UI starting on http://localhost:{ui_port}[/green]")
else:
diff --git a/packages/server/src/repowise/server/deps.py b/packages/server/src/repowise/server/deps.py
index 55cde6309..24111b808 100644
--- a/packages/server/src/repowise/server/deps.py
+++ b/packages/server/src/repowise/server/deps.py
@@ -10,6 +10,7 @@ Provides Depends() callables for:
from __future__ import annotations
import hmac
+import ipaddress
import logging
import os
from collections.abc import AsyncGenerator
@@ -26,12 +27,14 @@ _API_KEY = os.environ.get("REPOWISE_API_KEY")
_REPOWISE_HOST = os.environ.get("REPOWISE_HOST", "127.0.0.1")
_header_scheme = APIKeyHeader(name="Authorization", auto_error=False)
-# Warn at import time if server is network-exposed without authentication
+# Warn at import time if the server is network-exposed without a key. Only an
+# advisory: what a request is actually allowed to do is decided per request
+# from the peer address, since REPOWISE_HOST is not always set.
if _API_KEY is None and _REPOWISE_HOST in ("0.0.0.0", "::"):
logger.warning(
"SECURITY WARNING: Server is binding to %s without REPOWISE_API_KEY set. "
- "All endpoints are unauthenticated and network-accessible. "
- "Set REPOWISE_API_KEY or bind to 127.0.0.1.",
+ "Requests from other hosts will be refused. "
+ "Set REPOWISE_API_KEY to serve them, or bind to 127.0.0.1.",
_REPOWISE_HOST,
)
@@ -96,9 +99,33 @@ async def get_cross_repo_enricher(request: Request):
return getattr(request.app.state, "cross_repo_enricher", None)
-def auth_is_open() -> bool:
- """True when no key is required (no ``REPOWISE_API_KEY`` on a loopback bind)."""
- return _API_KEY is None and _REPOWISE_HOST not in ("0.0.0.0", "::")
+def client_is_local(request: Request) -> bool:
+ """True when the request's peer address is a loopback address.
+
+ The keyless-access decision is taken from the peer, not from
+ ``REPOWISE_HOST``: that env var describes what an operator intended, and
+ nothing on the CLI path sets it, so ``repowise serve --host 0.0.0.0``
+ used to bind the world while the auth logic still read "127.0.0.1" and
+ let every request through. An unknown peer counts as remote.
+
+ Known limitation: behind a reverse proxy on the same host every peer is
+ loopback, so those deployments still need ``REPOWISE_API_KEY``. Forwarded
+ headers are deliberately not trusted, since any client can send them.
+ """
+ client = request.client
+ if client is None or not client.host:
+ return False
+ try:
+ return ipaddress.ip_address(client.host).is_loopback
+ except ValueError:
+ # A non-address peer (a UNIX socket, an ASGI test transport that
+ # names itself) is not something we can vouch for.
+ return False
+
+
+def auth_is_open(request: Request) -> bool:
+ """True when no key is required (no ``REPOWISE_API_KEY``, local caller)."""
+ return _API_KEY is None and client_is_local(request)
def bearer_is_valid(auth: str | None) -> bool:
@@ -116,21 +143,22 @@ def bearer_is_valid(auth: str | None) -> bool:
async def verify_api_key(
+ request: Request,
auth: str | None = Security(_header_scheme),
) -> None:
"""API key verification.
- When REPOWISE_API_KEY is not set and server binds to loopback, this is a
- no-op (local-only access). When binding to a non-loopback address without
- a key, requests are rejected (fail-closed for network-exposed deployments).
- When set, requests must include ``Authorization: Bearer <key>``.
+ When REPOWISE_API_KEY is not set, only local callers are served; a request
+ from anywhere else is rejected (fail-closed for network-exposed
+ deployments, however the server was started). When set, requests must
+ include ``Authorization: Bearer <key>``.
"""
if _API_KEY is None:
- if _REPOWISE_HOST in ("0.0.0.0", "::"):
+ if not client_is_local(request):
raise HTTPException(
status_code=403,
- detail="Server is network-exposed but REPOWISE_API_KEY is not set. "
- "Set REPOWISE_API_KEY or bind to 127.0.0.1.",
+ detail="Server is reachable from the network but REPOWISE_API_KEY "
+ "is not set. Set REPOWISE_API_KEY or bind to 127.0.0.1.",
)
return
if not auth or not auth.startswith("Bearer "):
diff --git a/packages/server/src/repowise/server/routers/jobs.py b/packages/server/src/repowise/server/routers/jobs.py
index a79b5b873..f168b95d2 100644
--- a/packages/server/src/repowise/server/routers/jobs.py
+++ b/packages/server/src/repowise/server/routers/jobs.py
@@ -31,6 +31,7 @@ router = APIRouter(prefix="/api/jobs", tags=["jobs"])
async def authorize_job_stream(
+ request: Request,
job_id: str,
token: str | None = Query(None),
auth: str | None = Security(_header_scheme),
@@ -41,7 +42,7 @@ async def authorize_job_stream(
embeds and is signed over that id), so it can't be replayed against another
job. A bearer key still works, so non-browser clients are unaffected.
"""
- if auth_is_open():
+ if auth_is_open(request):
return
if bearer_is_valid(auth):
return
diff --git a/tests/unit/cli/test_serve_host_env.py b/tests/unit/cli/test_serve_host_env.py
new file mode 100644
index 000000000..9bdc9d27b
--- /dev/null
+++ b/tests/unit/cli/test_serve_host_env.py
@@ -0,0 +1,76 @@
+"""`repowise serve --host` must reach the server's view of its own bind (#1391).
+
+The auth layer reads ``REPOWISE_HOST`` to describe the bind. Nothing set it
+from ``--host``, so ``serve --host 0.0.0.0`` exposed the API to the network
+while the server still believed it was loopback-only.
+"""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands import serve_cmd
+
+
+def stub_serve(monkeypatch) -> dict:
+ """Run `serve` up to the uvicorn call and capture what it would bind."""
+ captured: dict = {}
+
+ def fake_run(_app: str, **kwargs) -> None:
+ captured["host"] = kwargs.get("host")
+ captured["repowise_host_env"] = os.environ.get("REPOWISE_HOST")
+
+ monkeypatch.setattr("uvicorn.run", fake_run)
+ monkeypatch.setattr(serve_cmd, "_load_local_provider_config", lambda: None)
+ monkeypatch.setattr(serve_cmd, "_setup_embedder", lambda: None)
+ monkeypatch.setattr(serve_cmd, "_serve_lock_path", lambda: None)
+ # No real sockets: the port probe is not what these tests are about.
+ monkeypatch.setattr(serve_cmd, "_find_free_port", lambda _host, port, _label: port)
+ monkeypatch.delenv("REPOWISE_API_KEY", raising=False)
+ # setenv, not delenv: the command assigns REPOWISE_HOST, and only a
+ # monkeypatch that recorded the variable will unset it again afterwards.
+ monkeypatch.setenv("REPOWISE_HOST", "127.0.0.1")
+ return captured
+
+
+def test_host_flag_propagates_to_repowise_host(stub_serve: dict) -> None:
+ result = CliRunner().invoke(serve_cmd.serve_command, ["--no-ui", "--host", "0.0.0.0"])
+ assert result.exit_code == 0, result.output
+ assert stub_serve["host"] == "0.0.0.0"
+ assert stub_serve["repowise_host_env"] == "0.0.0.0"
+
+
+def test_exposed_bind_without_key_warns(stub_serve: dict) -> None:
+ result = CliRunner().invoke(serve_cmd.serve_command, ["--no-ui", "--host", "0.0.0.0"])
+ assert "REPOWISE_API_KEY" in result.output
+
+
+def test_loopback_bind_is_quiet(stub_serve: dict) -> None:
+ result = CliRunner().invoke(serve_cmd.serve_command, ["--no-ui", "--host", "127.0.0.1"])
+ assert result.exit_code == 0, result.output
+ assert stub_serve["repowise_host_env"] == "127.0.0.1"
+ assert "REPOWISE_API_KEY" not in result.output
+
+
+def test_web_ui_takes_the_api_bind(monkeypatch, tmp_path) -> None:
+ """The UI proxies `/api/*` to the API, so a wider bind widens the API.
+
+ With the UI on the wildcard and the API on loopback, every proxied request
+ reached the API from 127.0.0.1 and passed the local-caller check, which
+ handed the whole API to the network on the UI's port.
+ """
+ captured: dict = {}
+
+ def fake_popen(_cmd, **kwargs):
+ captured["hostname"] = kwargs["env"]["HOSTNAME"]
+ return None
+
+ (tmp_path / "server.js").write_text("")
+ monkeypatch.setattr(serve_cmd.subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(serve_cmd, "_WEB_CACHE_DIR", tmp_path)
+ serve_cmd._start_frontend("node", 7337, 3000, local_web=None, host="127.0.0.1")
+ assert captured["hostname"] == "127.0.0.1"
diff --git a/tests/unit/server/test_auth.py b/tests/unit/server/test_auth.py
index f809372dc..69036c864 100644
--- a/tests/unit/server/test_auth.py
+++ b/tests/unit/server/test_auth.py
@@ -3,12 +3,20 @@
from __future__ import annotations
import pytest
-from httpx import AsyncClient
+from httpx import ASGITransport, AsyncClient
+
+
+async def remote_client(app) -> AsyncClient:
+ """A client whose peer address is off-host, as a LAN caller would be."""
+ transport = ASGITransport(app=app, client=("203.0.113.7", 4242))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ yield c
@pytest.mark.asyncio
-async def test_no_auth_configured_allows_access(client: AsyncClient) -> None:
- """When REPOWISE_API_KEY is not set, all endpoints are open."""
+async def test_no_auth_configured_allows_local_access(client: AsyncClient) -> None:
+ """When REPOWISE_API_KEY is not set, local callers are served."""
resp = await client.get("/api/repos")
assert resp.status_code == 200
@@ -63,6 +71,43 @@ async def test_auth_accepts_correct_key(client: AsyncClient) -> None:
deps_mod._API_KEY = original
+async def test_keyless_server_refuses_remote_caller(remote_client: AsyncClient) -> None:
+ """Fail closed on the peer address, not on what REPOWISE_HOST claims.
+
+ `repowise serve --host 0.0.0.0` never set REPOWISE_HOST, so the guard that
+ was supposed to catch a network-exposed bind never fired and every
+ endpoint was open to the LAN.
+ """
+ resp = await remote_client.get("/api/repos")
+ assert resp.status_code == 403
+ assert "REPOWISE_API_KEY" in resp.json()["detail"]
+
+
+async def test_remote_caller_with_key_is_served(remote_client: AsyncClient) -> None:
+ """The key is what makes a network-exposed server usable."""
+ import repowise.server.deps as deps_mod
+
+ original = deps_mod._API_KEY
+ deps_mod._API_KEY = "test-secret-key"
+ try:
+ resp = await remote_client.get(
+ "/api/repos",
+ headers={"Authorization": "Bearer test-secret-key"},
+ )
+ assert resp.status_code == 200
+ finally:
+ deps_mod._API_KEY = original
+
+
+async def test_job_stream_is_closed_to_remote_callers(remote_client: AsyncClient) -> None:
+ """The SSE route authorizes separately, so it needs the same peer test."""
+ resp = await remote_client.get("/api/jobs/does-not-exist/stream")
+ assert resp.status_code == 401
+
+
@pytest.mark.asyncio
async def test_health_bypasses_auth(client: AsyncClient) -> None:
"""The /health endpoint should always be accessible, even with auth enabled."""
diff --git a/website/self-hosting.md b/website/self-hosting.md
index 57e7575e1..5fb084f8d 100644
--- a/website/self-hosting.md
+++ b/website/self-hosting.md
@@ -100,6 +100,7 @@ ANTHROPIC_API_KEY=sk-ant-... docker compose up
| `REPOWISE_PROVIDER` | auto | Override provider detection |
| `REPOWISE_DB_URL` | SQLite (`.repowise/wiki.db`) | PostgreSQL connection string |
| `REPOWISE_HOST` | `127.0.0.1` | API server bind host |
+| `REPOWISE_API_KEY` | — | Bearer token for the API. Required to serve callers on other hosts; without it requests from off-host are refused |
| `REPOWISE_PORT` | `7337` | API server port |
| `REPOWISE_MCP_PORT` | `7338` | MCP SSE server port |