Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions LLM.txt
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,11 @@ def test_headers(request):
headers = request.headers # dictionary of header key:value
```

Note: pyRevit 7.0 never fills `request.headers` (it is always `{}`). This
extension therefore authenticates bridge calls with the `revit_mcp_auth` field
of the JSON body, which `authorize_request` removes before the route reads
`request.data`.

### Returning Results

The `routes.make_response` function can be used to prepare a `routes.Response` object:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ Once installed, test that the Routes API is working:

1. Choose **MCP > Bridge > Connect** in Revit, then run this authenticated
check from the exact candidate directory (a browser request has no pairing
header and is denied):
secret and is denied):
```bash
uv run --frozen python -c "import anyio; from main import revit_get; print(anyio.run(revit_get, '/status/'))"
```
Expand Down
14 changes: 10 additions & 4 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
The review candidate requires Windows-user pairing for every registered tool.
The MCP client and all Revit bridge routes authenticate requests with a random
256-bit bearer secret protected at rest by Windows DPAPI CurrentUser. Tokens are
sent in headers, never URL parameters. The built-in client rejects non-loopback
hosts and ignores environment HTTP proxies. Optional SSE/streamable HTTP modes
bind to loopback and require the same bearer header. Browser Origin headers are
rejected. The publication candidate uses `stdio`.
never sent in URL parameters. pyRevit Routes does not pass HTTP headers to route
handlers, so bridge calls carry the secret in the `revit_mcp_auth` field of an
`application/json` body (GET included); routes remove it before the payload is
used or shown for review. A browser cannot send such a body cross-origin without
a CORS preflight, which pyRevit does not grant. An `Authorization: Bearer` header
is still honored first if a pyRevit version exposes headers, and Origin headers
are then rejected; with pyRevit 7.0 the bridge cannot see Origin, so browser
protection rests on the secret and the preflight requirement. The built-in client rejects non-loopback hosts and
ignores environment HTTP proxies. Optional SSE/streamable HTTP modes bind to
loopback and require the bearer header. The publication candidate uses `stdio`.

The Revit-side request review runs in pyRevit's Revit API context. Every bridge
route requests a `request` argument and checks authorization before model access;
Expand Down
14 changes: 8 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from mcp.server.fastmcp import FastMCP, Image, Context
import base64
from typing import Optional, Dict, Any, Union
from revit_mcp.pairing import authorization_headers
from revit_mcp.pairing import authorization_body
from tools.http_security import PairingMiddleware

# Create a generic MCP server for interacting with Revit
Expand Down Expand Up @@ -45,8 +45,8 @@ async def revit_post(endpoint: str, data: Dict[str, Any], ctx: Context = None, *
async def revit_image(endpoint: str, ctx: Context = None) -> Union[Image, str]:
"""GET request that returns an Image object"""
try:
async with httpx.AsyncClient(timeout=60.0, trust_env=False, headers=authorization_headers()) as client:
response = await client.get(f"{BASE_URL}{endpoint}")
async with httpx.AsyncClient(timeout=60.0, trust_env=False) as client:
response = await client.request("GET", f"{BASE_URL}{endpoint}", json=authorization_body())

if response.status_code == 200:
data = response.json()
Expand All @@ -65,13 +65,15 @@ async def _revit_call(method: str, endpoint: str, data: Dict = None, ctx: Contex
timeout: float = 30.0, params: Dict = None) -> Union[Dict, str]:
"""Internal function handling all HTTP calls"""
try:
async with httpx.AsyncClient(timeout=timeout, trust_env=False, headers=authorization_headers()) as client:
async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
url = f"{BASE_URL}{endpoint}"

# pyRevit Routes hides headers from handlers, so the pairing secret
# travels in the JSON body of every call, GET included.
if method == "GET":
response = await client.get(url, params=params)
response = await client.request("GET", url, params=params, json=authorization_body())
else: # POST
response = await client.post(url, json=data, headers={"Content-Type": "application/json"})
response = await client.post(url, json=authorization_body(data))

return response.json() if response.status_code == 200 else f"Error: {response.status_code} - {response.text}"
except httpx.TimeoutException:
Expand Down
39 changes: 33 additions & 6 deletions revit_mcp/pairing.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,48 @@ def get_token():
raise PairingError("Use Revit's MCP > Bridge > Connect button to consent and pair this Windows user.")


# pyRevit Routes does not expose HTTP headers to route handlers, so bridge
# requests carry the secret in this JSON body field instead of Authorization.
AUTH_FIELD = "revit_mcp_auth"


def authorization_headers():
return {"Authorization": "Bearer " + get_token()}


def validate_request(headers):
"""Reject browser-originated requests and authenticate a paired client."""
import hmac
normalized = dict((str(k).lower(), str(v)) for k, v in headers.items())
def authorization_body(data=None):
"""Return a copy of a JSON object payload with the pairing secret added."""
body = dict(data or {})
body[AUTH_FIELD] = get_token()
return body


def validate_request(headers, body_token=None):
"""Reject browser-originated requests and authenticate a paired client.

The Authorization header wins when present; otherwise the secret popped from
the JSON body (see AUTH_FIELD) is checked.
"""
normalized = dict((str(k).lower(), str(v)) for k, v in (headers or {}).items())
if "origin" in normalized:
return False
try:
expected = "Bearer " + get_token()
token = get_token()
except PairingError:
return False
actual = normalized.get("authorization", "")
if "authorization" in normalized:
return _same_secret(normalized["authorization"], "Bearer " + token)
if body_token is None:
return False
try:
return _same_secret(str(body_token), token)
except UnicodeError:
return False


def _same_secret(actual, expected):
"""Compare secrets in constant time."""
import hmac
# IronPython 2 may not provide compare_digest.
if hasattr(hmac, "compare_digest"):
try:
Expand Down
20 changes: 18 additions & 2 deletions revit_mcp/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,33 @@
"""Authentication and in-Revit review for bridge requests."""
import json
from pyrevit import routes
from .pairing import validate_request
from .pairing import AUTH_FIELD, validate_request


def _pop_body_token(request):
"""Remove the pairing secret from the payload so routes and review never see it."""
data = request.data
if data and not isinstance(data, dict):
try:
parsed = json.loads(data)
except (ValueError, TypeError):
parsed = None
if isinstance(parsed, dict):
request.data = data = parsed
if isinstance(data, dict):
return data.pop(AUTH_FIELD, None)
return None


def authorize_request(request, action=None):
"""Return a denial response, or None when the request may proceed."""
body_token = _pop_body_token(request)
# pyRevit's dispatcher can post a route response to callbackUrl. Remove it
# before returning so even a denial cannot initiate an undeclared request.
if isinstance(request.data, dict) and "callbackUrl" in request.data:
request.data.pop("callbackUrl", None)
return routes.make_response(data={"error": "Callbacks are not supported."}, status=400)
if not validate_request(request.headers):
if not validate_request(request.headers, body_token):
return routes.make_response(data={"error": "Bridge is disconnected or pairing is invalid."}, status=401)
if action:
from pyrevit import forms
Expand Down
10 changes: 5 additions & 5 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import pytest
import httpx
from revit_mcp.pairing import authorization_headers, get_token
from revit_mcp.pairing import authorization_body, get_token

BASE_URL = "http://127.0.0.1:48884/revit_mcp"
TEST_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "test.rvt")
Expand All @@ -12,17 +12,17 @@
async def _revit_get(endpoint, ctx=None, **kwargs):
"""Real HTTP GET to pyRevit Routes."""
timeout = kwargs.pop("timeout", 30.0)
async with httpx.AsyncClient(timeout=timeout, trust_env=False, headers=authorization_headers()) as client:
response = await client.get(f"{BASE_URL}{endpoint}")
async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
response = await client.request("GET", f"{BASE_URL}{endpoint}", json=authorization_body())
if response.status_code == 200:
return response.json()
return f"Error: {response.status_code} - {response.text}"


async def _revit_post(endpoint, data, ctx=None, **kwargs):
"""Real HTTP POST to pyRevit Routes."""
async with httpx.AsyncClient(timeout=120.0, trust_env=False, headers=authorization_headers()) as client:
response = await client.post(f"{BASE_URL}{endpoint}", json=data)
async with httpx.AsyncClient(timeout=120.0, trust_env=False) as client:
response = await client.post(f"{BASE_URL}{endpoint}", json=authorization_body(data))
if response.status_code == 200:
return response.json()
return f"Error: {response.status_code} - {response.text}"
Expand Down
40 changes: 38 additions & 2 deletions tests/unit/test_publication_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ def test_dpapi_pairing_rotation_and_revocation(paired_user):
pairing.get_token()


def test_body_token_authenticates_when_headers_are_hidden(paired_user):
assert pairing.validate_request({}, paired_user)
assert pairing.validate_request(None, paired_user)
assert not pairing.validate_request({}, "wrong")
assert not pairing.validate_request({}, None)
assert not pairing.validate_request({"Origin": "null"}, paired_user)
# A header, when pyRevit exposes one, is authoritative over the body.
assert not pairing.validate_request({"Authorization": "Bearer wrong"}, paired_user)
assert pairing.authorization_body({"a": 1}) == {"a": 1, pairing.AUTH_FIELD: paired_user}


def test_corrupted_pairing_fails_closed(paired_user):
Path(pairing.pairing_path()).write_bytes(b"corrupted")
assert not pairing.validate_request({"Authorization": "Bearer " + paired_user})
Expand Down Expand Up @@ -96,6 +107,25 @@ def test_revit_review_decline_and_accept_show_request(route_security, paired_use
assert security.authorize_request(request, "Execute Python code").status == 400


@pytest.mark.parametrize("as_json_text", [False, True])
def test_route_accepts_body_token_and_strips_it_before_review(route_security, paired_user, as_json_text):
security, _, alert = route_security
payload = pairing.authorization_body({"code": "print('review me')"})
request = SimpleNamespace(data=json.dumps(payload) if as_json_text else payload, headers={})
alert.return_value = True
assert security.authorize_request(request, "Execute Python code") is None
assert request.data == {"code": "print('review me')"}
assert paired_user not in alert.call_args.kwargs["sub_msg"]


def test_route_rejects_wrong_body_token(route_security, paired_user):
security, _, alert = route_security
request = SimpleNamespace(data={pairing.AUTH_FIELD: "wrong"}, headers={})
assert security.authorize_request(request).status == 401
assert request.data == {}
alert.assert_not_called()


def _route_functions():
functions = []
for path in (ROOT / "revit_mcp").glob("*.py"):
Expand Down Expand Up @@ -154,8 +184,14 @@ def client(**kwargs):
return original(transport=httpx.MockTransport(handler), **kwargs)
monkeypatch.setattr(main.httpx, "AsyncClient", client)
assert await main.revit_get("/status/") == {"status": "active"}
assert observed[0].headers["authorization"] == "Bearer " + paired_user
assert observed[0].url.host in {"127.0.0.1", "localhost", "::1"}
assert await main.revit_post("/execute_code/", {"code": "1"}) == {"status": "active"}
# pyRevit Routes hides headers from handlers: the secret must be in the body.
assert json.loads(observed[0].content) == {pairing.AUTH_FIELD: paired_user}
assert json.loads(observed[1].content) == {"code": "1", pairing.AUTH_FIELD: paired_user}
for request in observed:
assert "authorization" not in request.headers
assert paired_user not in str(request.url)
assert request.url.host in {"127.0.0.1", "localhost", "::1"}


@pytest.mark.parametrize("transport_name", ["sse", "streamable-http", "combined"])
Expand Down