unity-mcp/Server/tests/integration/test_multi_user_session_iso...

177 lines
6.7 KiB
Python
Raw Permalink Normal View History

Remote server auth (#644) * Disable the gloabl default to first session when hosting remotely * Remove calls to /plugin/sessions The newer /api/instances covers that data, and we want to remove these "expose all" endpoints * Disable CLI routes when running in remote hosted mode * Update server README * feat: add API key authentication support for remote-hosted HTTP transport - Add API key field to connection UI (visible only in HTTP Remote mode) - Add "Get API Key" and "Clear" buttons with login URL retrieval - Include X-API-Key header in WebSocket connections when configured - Add API key to CLI commands (mcp add, claude mcp add) when set - Update config.json generation to include headers with API key - Add API key validation service with caching and configurable endpoints - Add /api/auth/login-url endpoint * feat: add environment variable support for HTTP remote hosted mode - Add UNITY_MCP_HTTP_REMOTE_HOSTED environment variable as alternative to --http-remote-hosted flag - Accept "true", "1", or "yes" values (case-insensitive) - Update CLI help text to document environment variable option * feat: add user isolation enforcement for remote-hosted mode session listing - Raise ValueError when list_sessions() called without user_id in remote-hosted mode - Add comprehensive integration tests for multi-user session isolation - Add unit tests for PluginRegistry user-scoped session filtering - Verify cross-user isolation with same project hash - Test unity_instances resource and set_active_instance user filtering * feat: add comprehensive integration tests for API key authentication - Add ApiKeyService tests covering validation, caching, retries, and singleton lifecycle - Add startup config validation tests for remote-hosted mode requirements - Test cache hit/miss scenarios, TTL expiration, and manual invalidation - Test transient failure handling (5xx, timeouts, connection errors) with retry logic - Test service token header injection and empty key fast-path validation - Test startup validation requiring * test: add autouse fixture to restore config state after startup validation tests Ensures test isolation for config-dependent integration tests * feat: skip user_id resolution in non-remote-hosted mode Prevents unnecessary API key validation when not in remote-hosted mode * test: add missing mock attributes to instance routing tests - Add client_id to test context mock in set_active_instance test - Add get_state mock to context in global instance routing test * Fix broken telemetry test * Add comprehensive API key authentication documentation - Add user guide covering configuration, setup, and troubleshooting - Add architecture reference documenting internal design and request flows * Add remote-hosted mode and API key authentication documentation to server README * Update reference doc for Docker Hub * Specify exception being caught * Ensure caplog handler cleanup in telemetry queue worker test * Use NoUnitySessionError instead of RuntimeError in session isolation test * Remove unusued monkeypatch arg * Use more obviously fake API keys * Reject connections when ApiKeyService is not initialized in remote-hosted mode - Validate that user_id is present after successful key validation - Expand transient error detection to include timeout and service errors - Use consistent 1013 status code for retryable auth failures * Accept "on" for UNITY_MCP_HTTP_REMOTE_HOSTED env var Consistent with repo * Invalidate cached login URL when HTTP base URL changes * Pass API key as parameter instead of reading from EditorPrefs in RegisterWithCapturedValues * Cache API key in field instead of reading from EditorPrefs on each reconnection * Align markdown table formatting in remote server auth documentation * Minor fixes * security: Sanitize API key values in shell commands and fix minor issues Add SanitizeShellHeaderValue() method to escape special shell characters (", \, `, $, !) in API keys before including them in shell command arguments. Apply sanitization to all three locations where API keys are embedded in shell commands (two in RegisterWithCapturedValues, one in GetManualInstructions). Also fix deprecated passwordCharacter property (now maskChar) and improve exception logging in _resolve_user_id_from_request * Consolidate duplicate instance selection error messages into InstanceSelectionRequiredError class Add InstanceSelectionRequiredError exception class with centralized error messages (_SELECTION_REQUIRED and _MULTIPLE_INSTANCES). Replace 4 duplicate RuntimeError raises with new exception type. Update tests to catch InstanceSelectionRequiredError instead of RuntimeError. * Replace hardcoded "X-API-Key" strings with AuthConstants.ApiKeyHeader constant across C# and Python codebases Add AuthConstants class in C# and API_KEY_HEADER constant in Python to centralize the API key header name definition. Update all 8 locations where "X-API-Key" was hardcoded (4 in C#, 4 in Python) to use the new constants instead. * Fix imports * Filter session listing by user_id in all code paths to prevent cross-user session access Remove conditional logic that only filtered sessions by user_id in remote-hosted mode. Now all session listings are filtered by user_id regardless of hosting mode, ensuring users can only see and interact with their own sessions. * Consolidate get_session_id_by_hash methods into single method with optional user_id parameter Merge get_session_id_by_hash and get_session_id_by_user_hash into a single method that accepts an optional user_id parameter. Update all call sites to use the unified method signature with user_id as the second parameter. Update tests and documentation to reflect the simplified API. * Add environment variable support for project-scoped-tools flag [skip ci] Support UNITY_MCP_PROJECT_SCOPED_TOOLS environment variable as alternative to --project-scoped-tools command line flag. Accept "true", "1", "yes", or "on" as truthy values (case-insensitive). Update help text to document the environment variable option. * Fix Python tests * Update validation logic to only require API key validation URL when both http_remote_hosted is enabled AND transport mode is "http", preventing false validation errors in stdio mode. * Update Server/src/main.py Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Refactor HTTP transport configuration to support separate local and remote URLs Split HTTP transport into HttpLocal and HttpRemote modes with separate EditorPrefs storage (HttpBaseUrl and HttpRemoteBaseUrl). Add HttpEndpointUtility methods to get/save local and remote URLs independently, and introduce IsRemoteScope() and GetCurrentServerTransport() helpers to centralize 3-way transport determination (Stdio/Http/HttpRemote). Update all client configuration code to distinguish between local and remote HTTP * Only include API key headers in HTTP/WebSocket configuration when in remote-hosted mode Update all locations where API key headers are added to HTTP/WebSocket configurations to check HttpEndpointUtility.IsRemoteScope() or serverTransport == HttpRemote before including the API key. This prevents local HTTP mode from unnecessarily including API key headers in shell commands, config JSON, and WebSocket connections. * Hide Manual Server Launch foldout when not in HTTP Local mode * Fix failing test * Improve error messaging and API key validation for HTTP Remote transport Add detailed error messages to WebSocket connection failures that guide users to check server URL, server status, and API key validity. Store error state in TransportState for propagation to UI. Disable "Start Session" button when HTTP Remote mode is selected without an API key, with tooltip explaining requirement. Display error dialog on connection failure with specific error message from transport state. Update connection * Add missing .meta file * Store transport mode in ServerConfig instead of environment variable * Add autouse fixture to restore global config state between tests Add restore_global_config fixture in conftest.py that automatically saves and restores global config attributes and UNITY_MCP_TRANSPORT environment variable between tests. Update integration tests to use monkeypatch.setattr on config.transport_mode instead of monkeypatch.setenv to prevent test pollution and ensure clean state isolation. * Fix startup * Replace _current_transport() calls with direct config.transport_mode access * Minor cleanup * Add integration tests for HTTP transport authentication behavior Verify that HTTP local mode allows requests without user_id while HTTP remote-hosted mode rejects them with auth_required error. * Add smoke tests for transport routing paths across HTTP local, HTTP remote, and stdio modes Verify that HTTP local routes through PluginHub without user_id, HTTP remote routes through PluginHub with user_id, and stdio calls legacy send function with instance_id. Each test uses monkeypatch to configure transport mode and mock appropriate transport layer functions. --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-31 06:39:21 +08:00
"""Integration tests for multi-user session isolation in remote-hosted mode.
These tests compose PluginRegistry + PluginHub to verify that users
cannot see or interact with each other's Unity instances.
"""
import asyncio
from unittest.mock import AsyncMock
import pytest
from core.config import config
from transport.plugin_hub import NoUnitySessionError, PluginHub
from transport.plugin_registry import PluginRegistry
@pytest.fixture(autouse=True)
def _reset_plugin_hub():
old_registry = PluginHub._registry
old_connections = PluginHub._connections.copy()
old_pending = PluginHub._pending.copy()
old_lock = PluginHub._lock
old_loop = PluginHub._loop
yield
PluginHub._registry = old_registry
PluginHub._connections = old_connections
PluginHub._pending = old_pending
PluginHub._lock = old_lock
PluginHub._loop = old_loop
async def _setup_two_user_registry():
"""Set up a registry with two users, each having Unity instances.
Returns the configured registry. Also configures PluginHub to use it.
"""
registry = PluginRegistry()
loop = asyncio.get_running_loop()
PluginHub.configure(registry, loop)
await registry.register("sess-A1", "ProjectAlpha", "hashA1", "2022.3", user_id="userA")
await registry.register("sess-B1", "ProjectBeta", "hashB1", "2022.3", user_id="userB")
await registry.register("sess-A2", "ProjectGamma", "hashA2", "2022.3", user_id="userA")
return registry
class TestMultiUserSessionFiltering:
@pytest.mark.asyncio
async def test_get_sessions_filters_by_user(self):
"""PluginHub.get_sessions(user_id=X) returns only X's sessions."""
await _setup_two_user_registry()
sessions_a = await PluginHub.get_sessions(user_id="userA")
assert len(sessions_a.sessions) == 2
project_names = {s.project for s in sessions_a.sessions.values()}
assert project_names == {"ProjectAlpha", "ProjectGamma"}
sessions_b = await PluginHub.get_sessions(user_id="userB")
assert len(sessions_b.sessions) == 1
assert next(iter(sessions_b.sessions.values())
).project == "ProjectBeta"
@pytest.mark.asyncio
async def test_get_sessions_no_filter_returns_all_in_local_mode(self):
"""In local mode, PluginHub.get_sessions() without user_id returns everything."""
await _setup_two_user_registry()
all_sessions = await PluginHub.get_sessions()
assert len(all_sessions.sessions) == 3
@pytest.mark.asyncio
async def test_get_sessions_no_filter_raises_in_remote_hosted(self, monkeypatch):
"""In remote-hosted mode, PluginHub.get_sessions() without user_id raises."""
monkeypatch.setattr(config, "http_remote_hosted", True)
await _setup_two_user_registry()
with pytest.raises(ValueError, match="requires user_id"):
await PluginHub.get_sessions()
class TestResolveSessionIdIsolation:
@pytest.mark.asyncio
async def test_resolve_session_for_own_hash(self, monkeypatch):
"""User A can resolve their own project hash."""
monkeypatch.setattr(config, "http_remote_hosted", True)
await _setup_two_user_registry()
session_id = await PluginHub._resolve_session_id("hashA1", user_id="userA")
assert session_id == "sess-A1"
@pytest.mark.asyncio
async def test_cannot_resolve_other_users_hash(self, monkeypatch):
"""User A cannot resolve User B's project hash."""
monkeypatch.setattr(config, "http_remote_hosted", True)
monkeypatch.setenv("UNITY_MCP_SESSION_RESOLVE_MAX_WAIT_S", "0.1")
await _setup_two_user_registry()
# userA tries to resolve userB's hash -> should not find it
with pytest.raises(NoUnitySessionError):
await PluginHub._resolve_session_id("hashB1", user_id="userA")
class TestInstanceListResourceIsolation:
@pytest.mark.asyncio
async def test_unity_instances_resource_filters_by_user(self, monkeypatch):
"""The unity_instances resource should pass user_id and return filtered results."""
monkeypatch.setattr(config, "http_remote_hosted", True)
monkeypatch.setattr(config, "transport_mode", "http")
await _setup_two_user_registry()
from services.resources.unity_instances import unity_instances
from tests.integration.test_helpers import DummyContext
ctx = DummyContext()
ctx.set_state("user_id", "userA")
result = await unity_instances(ctx)
assert result["success"] is True
assert result["instance_count"] == 2
instance_names = {i["name"] for i in result["instances"]}
assert instance_names == {"ProjectAlpha", "ProjectGamma"}
assert "ProjectBeta" not in instance_names
class TestSetActiveInstanceIsolation:
@pytest.mark.asyncio
async def test_set_active_instance_only_sees_own_sessions(self, monkeypatch):
"""set_active_instance should only offer sessions belonging to the current user."""
monkeypatch.setattr(config, "http_remote_hosted", True)
monkeypatch.setattr(config, "transport_mode", "http")
await _setup_two_user_registry()
from services.tools.set_active_instance import set_active_instance
from transport.unity_instance_middleware import UnityInstanceMiddleware
from tests.integration.test_helpers import DummyContext
middleware = UnityInstanceMiddleware()
monkeypatch.setattr(
"services.tools.set_active_instance.get_unity_instance_middleware",
lambda: middleware,
)
ctx = DummyContext()
ctx.set_state("user_id", "userA")
result = await set_active_instance(ctx, "ProjectAlpha@hashA1")
assert result["success"] is True
assert middleware.get_active_instance(ctx) == "ProjectAlpha@hashA1"
@pytest.mark.asyncio
async def test_set_active_instance_rejects_other_users_instance(self, monkeypatch):
"""set_active_instance should not find another user's instance."""
monkeypatch.setattr(config, "http_remote_hosted", True)
monkeypatch.setattr(config, "transport_mode", "http")
await _setup_two_user_registry()
from services.tools.set_active_instance import set_active_instance
from transport.unity_instance_middleware import UnityInstanceMiddleware
from tests.integration.test_helpers import DummyContext
middleware = UnityInstanceMiddleware()
monkeypatch.setattr(
"services.tools.set_active_instance.get_unity_instance_middleware",
lambda: middleware,
)
ctx = DummyContext()
ctx.set_state("user_id", "userA")
# UserA tries to select UserB's instance -> should fail
result = await set_active_instance(ctx, "ProjectBeta@hashB1")
assert result["success"] is False