HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
An internal-only route answers a service and refuses a relayed bearer (#418)
github-actions[bot]28609ec65ed6
diff --git a/gateway/app.py b/gateway/app.pyindex e1f68e29..43a84be3 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -825,8 +825,18 @@ def _pool_token() -> str:# unset in prod it no-oped, leaving /v1/traces and the connection/policy writers OPEN. Every# route now authenticates via _principal (API key / internal trust + verified JWT) or# _internal_only — auth that fails closed.)-def _internal_only(x_harness_internal: str = Header(default="")) -> dict:- if not INTERNAL_KEY or x_harness_internal != INTERNAL_KEY:+def _internal_only(request: Request, x_harness_internal: str = Header(default="")) -> dict:+ # A service (a script, a scheduler, the operator's own console session on a self-hosted box)+ # calls these routes with the key and nothing else. A request that also carries a bearer is a+ # person's or an API key's, relayed: a console proxy that is not in self-hosted mode attaches+ # the key to every request that has a bearer, before anything verifies it, so with a junk bearer+ # anyone could reach these routes and rewrite any organization's connections and routing+ # (reported privately, GHSA-p6cq-54cg-8mpv; found live on the hosted service and closed there+ # the same way, 2026-10-06). Routes for a person or a key resolve the full principal+ # (_principal, _owned_org); these never take one.+ if request.headers.get("authorization"):+ raise HTTPException(401, "internal key required")+ if not INTERNAL_KEY or not hmac.compare_digest(x_harness_internal.encode(), INTERNAL_KEY.encode()):raise HTTPException(401, "internal key required")return {"internal": True}diff --git a/gateway/tests/test_internal_only.py b/gateway/tests/test_internal_only.pynew file mode 100644index 00000000..b1584984--- /dev/null+++ b/gateway/tests/test_internal_only.py@@ -0,0 +1,87 @@+"""An internal-only route answers a service and nobody else (GHSA-p6cq-54cg-8mpv).++A console proxy that is not in self-hosted mode attaches the internal key to every request that+carries a bearer, before anything verifies the bearer. The routes that take only the internal key (an+organization's connections and routing, the /internal/* routes) took it as enough, so a junk bearer+through such a console reached them and could rewrite any organization's connections. A service calls+them with the key and nothing else; a request that also carries a bearer is a person's or a key's,+relayed, and is refused. Found live on the hosted service and closed there the same way.+"""+import ast+import sys+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402++KEY = "internal-test-key"+THREE = {"put_connection", "get_connection_meta", "put_policy"}+++def client(monkeypatch):+ monkeypatch.setattr(gw, "INTERNAL_KEY", KEY)+ seen = []++ async def get_connection(org, name):+ seen.append(("read", org, name))+ return None, ""++ async def vault_put(org, key, value):+ seen.append(("write", org, key))+ monkeypatch.setattr(gw, "_get_connection", get_connection)+ monkeypatch.setattr(gw, "_vault_put", vault_put)+ monkeypatch.setattr(gw.control_store, "enabled", lambda: False)+ with TestClient(gw.app) as c:+ yield c, seen++[email protected]("auth", ["Bearer junk", "Bearer eyJhbGciOiJIUzI1NiJ9.e30.x", "Basic Zm9vOmJhcg==", "sk-hr-anything"])+def test_a_relayed_request_with_a_bearer_is_refused_before_the_route_runs(client, auth):+ c, seen = client+ h = {"x-harness-internal": KEY, "authorization": auth}+ assert c.get("/v1/orgs/org.victim/connections/default", headers=h).status_code == 401+ assert c.put("/v1/orgs/org.victim/connections/default", headers=h,+ json={"provider": "openai", "base_url": "https://attacker.example/v1", "api_key": "sk-x"}).status_code == 401+ assert c.put("/v1/orgs/org.victim/policy/codex", headers=h, json={"connections": ["default"]}).status_code == 401+ assert c.get("/internal/storage-usage", headers=h).status_code == 401+ assert seen == []+++def test_a_service_with_the_key_and_nothing_else_is_answered(client):+ c, seen = client+ assert c.get("/v1/orgs/org.acme/connections/default", headers={"x-harness-internal": KEY}).status_code == 404 # ran: not found+ assert c.put("/v1/orgs/org.acme/policy/codex", headers={"x-harness-internal": KEY}, json={"connections": ["default"]}).status_code == 200+ assert seen == [("read", "org.acme", "default"), ("write", "org.acme", "harness-policy-codex")]+ assert c.get("/v1/orgs/org.acme/connections/default").status_code == 401+ assert c.get("/v1/orgs/org.acme/connections/default", headers={"x-harness-internal": "wrong"}).status_code == 401+ assert c.get("/v1/orgs/org.acme/connections/default", headers={"x-harness-internal": KEY + "x"}).status_code == 401+++def test_every_internal_route_and_the_three_writers_go_through_the_one_guard():+ """No route trusts the key on its own terms: each takes _internal_only, which refuses a bearer."""+ src = (Path(__file__).resolve().parents[1] / "app.py").read_text()+ tree = ast.parse(src)+ guarded, internal_paths = set(), 0+ for fn in [n for n in tree.body if isinstance(n, (ast.AsyncFunctionDef, ast.FunctionDef))]:+ for d in fn.decorator_list:+ if isinstance(d, ast.Call) and isinstance(d.func, ast.Attribute) and getattr(d.func.value, "id", "") == "app":+ if "_internal_only" in ast.unparse(d):+ guarded.add(fn.name)+ path = d.args[0].value if d.args and isinstance(d.args[0], ast.Constant) else ""+ if str(path).startswith("/internal/"):+ internal_paths += 1+ assert "_internal_only" in ast.unparse(d), f"{path} ({fn.name}) is not guarded"+ assert internal_paths >= 5 and THREE <= guarded, (internal_paths, sorted(guarded))+ # the key is compared in two places and no third: this guard, and _principal's own internal branch+ assert src.count('== INTERNAL_KEY') + src.count("INTERNAL_KEY.encode())") == 2+++def test_the_console_proxy_does_not_forward_internal_routes_outside_a_self_hosted_box():+ route = (Path(__file__).resolve().parents[2] / "ui" / "src" / "app" / "api" / "harness" / "[...path]" / "route.ts").read_text()+ guard = route.index("if (!SELF_HOSTED && (path || [])[0] === 'internal')")+ assert guard < route.index("headers['x-harness-internal'] = INTERNAL_KEY")+ assert "if (lk === 'x-harness-internal') return;" in route # and a browser's own copy of the header is droppeddiff --git a/ui/src/app/api/harness/[...path]/route.ts b/ui/src/app/api/harness/[...path]/route.tsindex 605c2b43..6a54540c 100644--- a/ui/src/app/api/harness/[...path]/route.ts+++ b/ui/src/app/api/harness/[...path]/route.ts@@ -42,6 +42,13 @@ const upstream = new Agent({ headersTimeout: maxDuration * 1000, bodyTimeout: maasync function proxy(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {const { path } = await ctx.params;+ // The gateway's /internal/* routes are for services that hold the internal key themselves. A+ // browser has no business on them through a multi-tenant console, where this proxy attaches the+ // key beside any bearer: they are not forwarded there at all. (A self-hosted box is its owner's:+ // the signed-in operator may call them, and the gateway refuses any that arrives with a bearer.)+ if (!SELF_HOSTED && (path || [])[0] === 'internal') {+ return new Response(JSON.stringify({ detail: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });+ }const target = `${GATEWAY.replace(/\/$/, '')}/${(path || []).join('/')}${req.nextUrl.search}`;const headers: Record<string, string> = {};const ct = req.headers.get('content-type');