π OpenHands: AI-Driven Development
security: Require RUNNING status for session API key validation (#14002)
chuckbutkuscf7e88c8c359
diff --git a/openhands/app_server/sandbox/session_auth.py b/openhands/app_server/sandbox/session_auth.pyindex e327e03b3a..ceecfbfb36 100644--- a/openhands/app_server/sandbox/session_auth.py+++ b/openhands/app_server/sandbox/session_auth.py@@ -8,6 +8,11 @@ The ``InjectorState`` + ``ADMIN`` pattern used here is established in``webhook_router.py`` β the sandbox service requires an admin context tolook up sandboxes across all users by session key, but the session keyitself acts as the proof of access.++Security Note:+ Session API keys are only valid while the sandbox is RUNNING. This prevents+ leaked keys from being used to access secrets after a sandbox has been+ paused, stopped, or deleted. See validate_session_key() for enforcement."""from __future__ import annotations@@ -18,7 +23,7 @@ from typing import TYPE_CHECKINGfrom fastapi import HTTPException, statusfrom openhands.app_server.config import get_global_config, get_sandbox_service-from openhands.app_server.sandbox.sandbox_models import SandboxInfo+from openhands.app_server.sandbox.sandbox_models import SandboxInfo, SandboxStatusfrom openhands.app_server.services.injector import InjectorStatefrom openhands.app_server.user.specifiy_user_context import ADMIN, USER_CONTEXT_ATTRfrom openhands.server.types import AppMode@@ -32,8 +37,15 @@ _logger = logging.getLogger(__name__)async def validate_session_key(session_api_key: str | None) -> SandboxInfo:"""Validate an ``X-Session-API-Key`` and return the associated sandbox.+ Security:+ This function enforces that session API keys are only valid for RUNNING+ sandboxes. This is a critical security measure to prevent leaked keys+ from being used to access user secrets after a sandbox has been paused,+ stopped, or deleted.+Raises:HTTPException(401): if the key is missing or does not map to a sandbox.+ HTTPException(401): if the sandbox is not in RUNNING state.HTTPException(401): in SAAS mode if the sandbox has no owning user."""if not session_api_key:@@ -58,6 +70,22 @@ async def validate_session_key(session_api_key: str | None) -> SandboxInfo:status.HTTP_401_UNAUTHORIZED, detail='Invalid session API key')+ # Security: Reject session keys for non-running sandboxes.+ # This prevents leaked keys from being used to access secrets after+ # the sandbox has been paused, stopped, or deleted.+ if sandbox_info.status != SandboxStatus.RUNNING:+ _logger.warning(+ 'Session key rejected for non-running sandbox',+ extra={+ 'sandbox_id': sandbox_info.id,+ 'status': sandbox_info.status.value,+ },+ )+ raise HTTPException(+ status.HTTP_401_UNAUTHORIZED,+ detail='Sandbox is not running',+ )+if not sandbox_info.created_by_user_id:if get_global_config().app_mode == AppMode.SAAS:_logger.error(diff --git a/tests/unit/app_server/test_sandbox_secrets_router.py b/tests/unit/app_server/test_sandbox_secrets_router.pyindex 65ca901f21..7326584d36 100644--- a/tests/unit/app_server/test_sandbox_secrets_router.py+++ b/tests/unit/app_server/test_sandbox_secrets_router.py@@ -144,6 +144,105 @@ class TestValidateSessionKey:assert exc_info.value.status_code == 401assert 'no user' in exc_info.value.detail+ # -------------------------------------------------------------------------+ # Security: Status check tests (prevents leaked session keys from being+ # used after sandbox is paused/stopped/deleted)+ # -------------------------------------------------------------------------++ async def test_rejects_paused_sandbox(self):+ """Session key for PAUSED sandbox raises 401 - security mitigation."""+ sandbox = SandboxInfo(+ id=SANDBOX_ID,+ created_by_user_id=USER_ID,+ sandbox_spec_id='test-spec',+ status=SandboxStatus.PAUSED,+ session_api_key='session-key',+ )+ ctx, mock_svc = _patch_sandbox_service(sandbox)+ with ctx as mock_get:+ mock_get.return_value.__aenter__ = AsyncMock(return_value=mock_svc)+ mock_get.return_value.__aexit__ = AsyncMock(return_value=False)++ with pytest.raises(HTTPException) as exc_info:+ await validate_session_key('valid-key')+ assert exc_info.value.status_code == 401+ assert 'not running' in exc_info.value.detail++ async def test_rejects_missing_sandbox(self):+ """Session key for MISSING sandbox raises 401 - security mitigation."""+ sandbox = SandboxInfo(+ id=SANDBOX_ID,+ created_by_user_id=USER_ID,+ sandbox_spec_id='test-spec',+ status=SandboxStatus.MISSING,+ session_api_key='session-key',+ )+ ctx, mock_svc = _patch_sandbox_service(sandbox)+ with ctx as mock_get:+ mock_get.return_value.__aenter__ = AsyncMock(return_value=mock_svc)+ mock_get.return_value.__aexit__ = AsyncMock(return_value=False)++ with pytest.raises(HTTPException) as exc_info:+ await validate_session_key('valid-key')+ assert exc_info.value.status_code == 401+ assert 'not running' in exc_info.value.detail++ async def test_rejects_error_sandbox(self):+ """Session key for ERROR sandbox raises 401 - security mitigation."""+ sandbox = SandboxInfo(+ id=SANDBOX_ID,+ created_by_user_id=USER_ID,+ sandbox_spec_id='test-spec',+ status=SandboxStatus.ERROR,+ session_api_key='session-key',+ )+ ctx, mock_svc = _patch_sandbox_service(sandbox)+ with ctx as mock_get:+ mock_get.return_value.__aenter__ = AsyncMock(return_value=mock_svc)+ mock_get.return_value.__aexit__ = AsyncMock(return_value=False)++ with pytest.raises(HTTPException) as exc_info:+ await validate_session_key('valid-key')+ assert exc_info.value.status_code == 401+ assert 'not running' in exc_info.value.detail++ async def test_rejects_starting_sandbox(self):+ """Session key for STARTING sandbox raises 401 - must wait for RUNNING."""+ sandbox = SandboxInfo(+ id=SANDBOX_ID,+ created_by_user_id=USER_ID,+ sandbox_spec_id='test-spec',+ status=SandboxStatus.STARTING,+ session_api_key='session-key',+ )+ ctx, mock_svc = _patch_sandbox_service(sandbox)+ with ctx as mock_get:+ mock_get.return_value.__aenter__ = AsyncMock(return_value=mock_svc)+ mock_get.return_value.__aexit__ = AsyncMock(return_value=False)++ with pytest.raises(HTTPException) as exc_info:+ await validate_session_key('valid-key')+ assert exc_info.value.status_code == 401+ assert 'not running' in exc_info.value.detail++ async def test_accepts_running_sandbox(self):+ """Session key for RUNNING sandbox is accepted."""+ sandbox = SandboxInfo(+ id=SANDBOX_ID,+ created_by_user_id=USER_ID,+ sandbox_spec_id='test-spec',+ status=SandboxStatus.RUNNING,+ session_api_key='session-key',+ )+ ctx, mock_svc = _patch_sandbox_service(sandbox)+ with ctx as mock_get:+ mock_get.return_value.__aenter__ = AsyncMock(return_value=mock_svc)+ mock_get.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await validate_session_key('valid-key')+ assert result.id == SANDBOX_ID+ assert result.status == SandboxStatus.RUNNING+# ---------------------------------------------------------------------------# GET /users/me?expose_secrets=true