Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.
Python aecai-agentsautodeskautomationbimclaudeifcmcpmcp-servermodel-context-protocolnavisworksrevitrevit-addinrevit-apirhino
Reject unexpected Host, Origin and Content-Type on the panel shim (#93)
A. Sam Mohammad76568bee9555
diff --git a/docs/security.md b/docs/security.mdindex 762cbfb..845a2dc 100644--- a/docs/security.md+++ b/docs/security.md@@ -87,6 +87,17 @@ One hub serves every open Revit. Requests that act on Revit carry an `instance`What this does not do: it does not stop software running as the same user, and it does not change tool approval semantics; mutating tools remain gated by the approval flow.+### Panel HTTP shim (`panel_server.py`)+The panel hub (`aec-model-bridge-panel-server`, default port 8787) listens on `127.0.0.1` and serves `/execute`, `/agent/chat`, `/diagnostics`, `/reports`, `/agent/providers` and `/health`. Its only intended caller is the add-in's C# `HubClient`. Every request is checked:++- `Host` must be `127.0.0.1:<port>` or `localhost:<port>` (the port the hub is actually bound to), otherwise 403.+- Any request carrying an `Origin` header, including `Origin: null`, is refused with 403. `HubClient` sends no `Origin`.+- `POST` requires `Content-Type: application/json` (a `charset` parameter is accepted), otherwise 415.+- `OPTIONS` is not handled and no CORS headers are sent.+- `GET /health` returns only `{"status": "healthy"}`.++What this does not do: there is no authentication token yet, so it does not stop other software running as the same user from calling the port directly with a valid `Host` and no `Origin`. It does not change tool approval semantics; mutating tools remain gated by the approval flow. A token is planned separately.+---## 3. Workspace sandboxingdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py b/packages/mcp-server-revit/src/revit_mcp_server/panel_server.pyindex 2f72e2f..091fd7a 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py@@ -150,9 +150,35 @@ class PanelRequestHandler(BaseHTTPRequestHandler):self.end_headers()self.wfile.write(body)+ def _authorize(self, is_post: bool) -> bool:+ """Reject requests with an unexpected Host, any Origin, or a non-JSON POST.++ The only legitimate caller is the add-in's C# HttpClient, which sends a+ loopback Host and no Origin header. Sends the error response and returns+ False when the request must not proceed. No CORS headers are served and+ OPTIONS is not handled.+ """+ port = self.server.server_address[1]+ allowed_hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}+ host = (self.headers.get("Host") or "").strip().lower()+ if host not in allowed_hosts:+ self._send_json(403, {"ok": False, "error": "Forbidden host"})+ return False+ if self.headers.get("Origin") is not None:+ self._send_json(403, {"ok": False, "error": "Requests with an Origin header are not allowed"})+ return False+ if is_post:+ ctype = (self.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()+ if ctype != "application/json":+ self._send_json(415, {"ok": False, "error": "Content-Type must be application/json"})+ return False+ return True+def do_GET(self) -> None: # noqa: N802+ if not self._authorize(is_post=False):+ returnif self.path == "/health":- self._send_json(200, {"status": "healthy", "tools": len(self.registry.get_all_tools())})+ self._send_json(200, {"status": "healthy"})returnif self.path == "/diagnostics":self._send_json(200, collect_diagnostics(self.workspace.allowed_directories[0]))@@ -192,6 +218,8 @@ class PanelRequestHandler(BaseHTTPRequestHandler):self._send_json(200, {"ok": True, "reports": reports})def do_POST(self) -> None: # noqa: N802+ if not self._authorize(is_post=True):+ returnif self.path == "/agent/chat":self._handle_agent_chat()returndiff --git a/packages/mcp-server-revit/tests/test_panel_server.py b/packages/mcp-server-revit/tests/test_panel_server.pyindex e3ebe29..a2fc812 100644--- a/packages/mcp-server-revit/tests/test_panel_server.py+++ b/packages/mcp-server-revit/tests/test_panel_server.py@@ -56,11 +56,10 @@ def _post(port: int, path: str, body: dict):return e.code, json.loads(e.read())-def test_health_reports_tool_count(running_server):+def test_health_reports_status_only(running_server):status, body = _get(running_server, "/health")assert status == 200- assert body["status"] == "healthy"- assert body["tools"] > 100 # ~218 across all providers/modules+ assert body == {"status": "healthy"}def test_execute_runs_a_real_readonly_tool(running_server):@@ -340,3 +339,87 @@ def test_diagnostics_reports_missing_revit_bridge(running_server, monkeypatch):checks = {c["id"]: c for c in body["checks"]}assert checks["revit_bridge"]["ok"] is Falseassert "add-in" in checks["revit_bridge"]["next_step"]+++# --- Host / Origin / Content-Type checks ------------------------------------+++def _raw(port, method, path, headers=None, body=None):+ """Request with full header control (urllib would override Host)."""+ import http.client++ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)+ try:+ conn.putrequest(method, path, skip_host=True, skip_accept_encoding=True)+ hdrs = {"Host": f"127.0.0.1:{port}"}+ hdrs.update(headers or {})+ data = body.encode("utf-8") if body is not None else None+ if data is not None:+ hdrs["Content-Length"] = str(len(data))+ for k, v in hdrs.items():+ conn.putheader(k, v)+ conn.endheaders(data)+ resp = conn.getresponse()+ return resp.status, dict(resp.getheaders()), json.loads(resp.read() or b"{}")+ finally:+ conn.close()+++JSON_CT = {"Content-Type": "application/json"}+EXEC_BODY = json.dumps({"tool": "list_pending_plans", "arguments": {}})+++def test_post_requires_json_content_type(running_server):+ for ctype in ("text/plain", "application/x-www-form-urlencoded", "multipart/form-data"):+ status, _, _ = _raw(running_server, "POST", "/execute", {"Content-Type": ctype}, EXEC_BODY)+ assert status == 415, ctype+ status, _, _ = _raw(running_server, "POST", "/execute", None, EXEC_BODY) # no header+ assert status == 415+++def test_json_content_type_with_charset_is_accepted(running_server):+ status, _, body = _raw(+ running_server, "POST", "/execute", {"Content-Type": "application/json; charset=utf-8"}, EXEC_BODY+ )+ assert status == 200 and body["ok"] is True++[email protected]("host", ["evil.example", "evil.example:%d", "127.0.0.1", "localhost:1", "127.0.0.1.evil.example:%d"])+def test_bad_host_rejected(running_server, host):+ host = host.replace("%d", str(running_server))+ status, _, _ = _raw(running_server, "POST", "/execute", {**JSON_CT, "Host": host}, EXEC_BODY)+ assert status == 403+ status, _, _ = _raw(running_server, "GET", "/health", {"Host": host})+ assert status == 403+++def test_localhost_host_is_allowed(running_server):+ status, _, _ = _raw(running_server, "GET", "/health", {"Host": f"localhost:{running_server}"})+ assert status == 200++[email protected]("origin", ["https://evil.example", "null", "http://127.0.0.1", "http://localhost:8787"])+def test_any_origin_rejected(running_server, origin):+ status, _, _ = _raw(running_server, "POST", "/execute", {**JSON_CT, "Origin": origin}, EXEC_BODY)+ assert status == 403+ status, _, _ = _raw(running_server, "GET", "/diagnostics", {"Origin": origin})+ assert status == 403+ status, _, _ = _raw(running_server, "GET", "/health", {"Origin": origin})+ assert status == 403+++def test_no_cors_headers_and_options_not_served(running_server):+ status, headers, _ = _raw(running_server, "GET", "/health")+ assert status == 200+ assert not any(k.lower().startswith("access-control-") for k in headers)+ import http.client++ conn = http.client.HTTPConnection("127.0.0.1", running_server, timeout=5)+ try:+ conn.request("OPTIONS", "/execute", headers={"Origin": "https://evil.example"})+ resp = conn.getresponse()+ resp.read()+ assert resp.status >= 400+ assert not any(k.lower().startswith("access-control-") for k, _ in resp.getheaders())+ finally:+ conn.close()