M13: harden MCP trust boundary
This commit is contained in:
+25
-4
@@ -1,6 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import re
|
||||
from collections.abc import Generator
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -60,12 +63,30 @@ def require_operations_manager(
|
||||
return user
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class McpClientContext:
|
||||
client_id: str
|
||||
tenant: str
|
||||
|
||||
|
||||
_MCP_CLIENT_ID = re.compile(
|
||||
r"^itworx-mcp-hub:(?:readiness|mobilityops:[A-Za-z0-9][A-Za-z0-9._:-]{0,127})$"
|
||||
)
|
||||
|
||||
|
||||
def require_mcp_service_token(
|
||||
x_service_token: str = Header(..., alias="X-Service-Token"),
|
||||
x_client_id: str = Header(default="unknown-mcp-client", alias="X-Client-Id"),
|
||||
) -> str:
|
||||
if x_service_token != settings.mcp_hub_service_token:
|
||||
x_client_id: str = Header(..., alias="X-Client-Id", min_length=1, max_length=180),
|
||||
x_tenant_id: str | None = Header(default=None, alias="X-Tenant-Id", max_length=120),
|
||||
) -> McpClientContext:
|
||||
if not hmac.compare_digest(x_service_token, settings.mcp_hub_service_token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid service token"
|
||||
)
|
||||
return x_client_id
|
||||
if not _MCP_CLIENT_ID.fullmatch(x_client_id):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Untrusted MCP client identity"
|
||||
)
|
||||
if x_tenant_id is not None and x_tenant_id != settings.ragcore_tenant:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Tenant mismatch")
|
||||
return McpClientContext(client_id=x_client_id, tenant=settings.ragcore_tenant)
|
||||
|
||||
Reference in New Issue
Block a user