Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(mcp): apply api-key context checks (#4247)

Yu Zhang96ca75326ba0
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index d89068e2a..095bafe50 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -50,7 +50,12 @@ from openviking.retrieve.context_assembler import (
AssembleParams,
assemble_context,
)
-from openviking.server.auth import _extract_api_key, normalize_actor_peer_header, resolve_identity
+from openviking.server.auth import (
+ _build_request_context,
+ _extract_api_key,
+ normalize_actor_peer_header,
+ resolve_identity,
+)
from openviking.server.dependencies import get_server_config, get_service
from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import (
@@ -60,7 +65,6 @@ from openviking.server.local_input_guard import (
from openviking.server.resource_ingest import ingest_temp_upload
from openviking.server.temp_upload_store import TempUploadStore
from openviking.server.upload_token_store import upload_token_store
-from openviking.telemetry.span_models import update_root_span_identity
from openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter
from openviking_cli.exceptions import (
InvalidArgumentError,
@@ -69,7 +73,6 @@ from openviking_cli.exceptions import (
PermissionDeniedError,
UnauthenticatedError,
)
-from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -174,6 +177,12 @@ class _IdentityASGIMiddleware:
actor_peer_id = normalize_actor_peer_header(
request.headers.get("x-openviking-actor-peer")
)
+ ctx = _build_request_context(
+ request,
+ identity,
+ actor_peer_id=actor_peer_id,
+ api_key=_extract_api_key(x_api_key, authorization),
+ )
except (UnauthenticatedError, PermissionDeniedError, InvalidArgumentError) as exc:
status = (
401
@@ -198,30 +207,6 @@ class _IdentityASGIMiddleware:
)
return await resp(scope, receive, send)
- # Mirror the identity fallback RequestContext applies below, so the
- # observability stamp and the request context never disagree.
- effective_account_id = identity.account_id or "default"
- effective_user_id = identity.user_id or "default"
- # Stamp the resolved identity onto the outer request's root
- # observability context, mirroring what get_request_context does for
- # REST routes. MCP authentication bypasses FastAPI's REST context
- # dependency; request.state shares scope["state"] with the outer app,
- # where the observability middleware attached root_span_attrs.
- update_root_span_identity(
- request_state=request.state,
- account_id=effective_account_id,
- user_id=effective_user_id,
- )
- ctx = RequestContext(
- user=UserIdentifier(
- effective_account_id,
- effective_user_id,
- ),
- role=identity.role,
- actor_peer_id=actor_peer_id,
- from_oauth=identity.from_oauth,
- api_key=_extract_api_key(x_api_key, authorization),
- )
url_info = {
"x_forwarded_proto": request.headers.get("x-forwarded-proto"),
"x_forwarded_host": request.headers.get("x-forwarded-host"),
diff --git a/tests/server/oauth/test_mcp_www_authenticate.py b/tests/server/oauth/test_mcp_www_authenticate.py
index e2f012621..0a07b0a84 100644
--- a/tests/server/oauth/test_mcp_www_authenticate.py
+++ b/tests/server/oauth/test_mcp_www_authenticate.py
@@ -13,9 +13,11 @@ import pytest
from fastapi import FastAPI
from openviking.server.config import ServerConfig
-from openviking.server.mcp_endpoint import _IdentityASGIMiddleware
+from openviking.server.identity import ResolvedIdentity, Role
+from openviking.server.mcp_endpoint import _get_ctx, _IdentityASGIMiddleware
from openviking.server.oauth.provider import OpenVikingOAuthProvider
from openviking.server.oauth.storage import OAuthStore
+from openviking_cli.exceptions import UnauthenticatedError
async def _noop_app(scope, receive, send):
@@ -23,6 +25,26 @@ async def _noop_app(scope, receive, send):
raise AssertionError("Downstream app should not be called for unauthenticated requests")
+async def _ok_app(scope, receive, send):
+ ctx = _get_ctx()
+ response = httpx.Response(
+ 200,
+ json={
+ "role": str(ctx.role),
+ "account_id": ctx.user.account_id,
+ "user_id": ctx.user.user_id,
+ },
+ )
+ await send(
+ {
+ "type": "http.response.start",
+ "status": response.status_code,
+ "headers": [(b"content-type", b"application/json")],
+ }
+ )
+ await send({"type": "http.response.body", "body": response.content})
+
+
def _build_test_app(*, oauth_enabled: bool, tmp_path=None) -> FastAPI:
from openviking.server.auth.plugins import ApiKeyAuthPlugin
from openviking.server.auth.registry import get_registry
@@ -46,11 +68,33 @@ def _build_test_app(*, oauth_enabled: bool, tmp_path=None) -> FastAPI:
return app
-def _mount_mcp(app: FastAPI) -> None:
+class _RootOnlyKeyManager:
+ def resolve(self, api_key):
+ if api_key != "root-test-1234567890abcd":
+ raise UnauthenticatedError("Invalid API Key")
+ return ResolvedIdentity(
+ role=Role.ROOT,
+ account_id="default",
+ user_id="default",
+ )
+
+
+class _UserOnlyKeyManager:
+ def resolve(self, api_key):
+ if api_key != "user-test-1234567890abcd":
+ raise UnauthenticatedError("Invalid API Key")
+ return ResolvedIdentity(
+ role=Role.USER,
+ account_id="default",
+ user_id="alice",
+ )
+
+
+def _mount_mcp(app: FastAPI, downstream=_noop_app) -> None:
"""Mount a tiny ASGI route at /mcp wrapped in _IdentityASGIMiddleware."""
from starlette.routing import Route
- handler = _IdentityASGIMiddleware(_noop_app)
+ handler = _IdentityASGIMiddleware(downstream)
app.routes.append(Route("/mcp", endpoint=handler, methods=["GET", "POST"]))
@@ -84,6 +128,47 @@ async def test_unauthenticated_request_omits_header_when_oauth_disabled():
assert "www-authenticate" not in {k.lower() for k in resp.headers.keys()}
+async def test_root_api_key_is_rejected_on_mcp_data_plane_in_api_key_mode():
+ app = _build_test_app(oauth_enabled=False)
+ app.state.api_key_manager = _RootOnlyKeyManager()
+ _mount_mcp(app)
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ resp = await client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
+ headers={"Authorization": "Bearer root-test-1234567890abcd"},
+ )
+
+ assert resp.status_code == 403
+ assert resp.json()["error"]["code"] == -32001
+ assert "ROOT API keys cannot access tenant-scoped data APIs" in resp.text
+
+
+async def test_user_api_key_is_allowed_on_mcp_data_plane_in_api_key_mode():
+ app = _build_test_app(oauth_enabled=False)
+ app.state.api_key_manager = _UserOnlyKeyManager()
+ _mount_mcp(app, downstream=_ok_app)
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ resp = await client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
+ headers={"Authorization": "Bearer user-test-1234567890abcd"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json() == {
+ "role": "user",
+ "account_id": "default",
+ "user_id": "alice",
+ }
+
+
@pytest.mark.asyncio
async def test_www_authenticate_honors_x_forwarded_proto():
app = _build_test_app(oauth_enabled=True)