π OpenHands: AI-Driven Development
feat: add secrets field to AppConversationStartRequest for direct API secret passing (#14009)
John-Mason P. Shackelforda8f62aa30c57
diff --git a/openhands/app_server/app_conversation/app_conversation_models.py b/openhands/app_server/app_conversation/app_conversation_models.pyindex 3a3b8c900d..1dc208c3d8 100644--- a/openhands/app_server/app_conversation/app_conversation_models.py+++ b/openhands/app_server/app_conversation/app_conversation_models.py@@ -3,7 +3,7 @@ from enum import Enumfrom typing import Any, Literalfrom uuid import UUID, uuid4-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, SecretStrfrom openhands.agent_server.models import OpenHandsModel, SendMessageRequestfrom openhands.agent_server.utils import OpenHandsUUID, utc_now@@ -175,6 +175,18 @@ class AppConversationStartRequest(OpenHandsModel):),)+ # Secrets passed directly via API at conversation start time+ secrets: dict[str, SecretStr] | None = Field(+ default=None,+ description=(+ 'Secrets to pass to the conversation. These are merged with any '+ 'existing secrets (from database or git providers), with API-provided '+ 'secrets taking precedence (overriding any existing secret with the same name). '+ 'Keys are secret names (e.g., "MY_API_KEY"), values are the secret values. '+ 'Warning: Providing a secret that already exists will silently override it.'+ ),+ )+class AppConversationUpdateRequest(BaseModel):"""Request model for updating conversation metadata.diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.pyindex f8bd2207bf..08b0777486 100644--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py@@ -5,6 +5,7 @@ import osimport tempfileimport zipfilefrom collections import defaultdict+from collections.abc import Mappingfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import Any, AsyncGenerator, Sequence, cast@@ -309,6 +310,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):remote_workspace=remote_workspace,selected_repository=request.selected_repository,plugins=request.plugins,+ api_secrets=request.secrets,))@@ -1216,6 +1218,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):remote_workspace: AsyncRemoteWorkspace | None = None,selected_repository: str | None = None,plugins: list[PluginSpec] | None = None,+ api_secrets: dict[str, SecretStr] | None = None,) -> StartConversationRequest:"""Build a complete StartConversationRequest for a user.@@ -1224,6 +1227,23 @@ class LiveStatusAppConversationService(AppConversationServiceBase):Server-only overrides (system prompts, LLM tracing metadata,skills, hooks) are applied to the agent after creation.Finally delegates to ``ConversationSettings.create_request()``.++ Args:+ sandbox: Sandbox information+ conversation_id: Unique conversation identifier+ initial_message: Optional initial message to send+ system_message_suffix: Optional suffix for system message+ git_provider: Optional git provider type+ working_dir: Working directory path+ agent_type: Type of agent (DEFAULT or PLAN)+ llm_model: Optional specific LLM model to use+ remote_workspace: Optional remote workspace instance+ selected_repository: Optional repository name+ plugins: Optional list of plugins to load+ api_secrets: Optional secrets passed directly via the API.+ These are merged with existing secrets (from database+ and git providers), with API-provided secrets taking+ precedence."""user = await self.user_context.get_user_info()@@ -1231,8 +1251,28 @@ class LiveStatusAppConversationService(AppConversationServiceBase):workspace = LocalWorkspace(working_dir=project_dir)# --- secrets --------------------------------------------------------+ # Start with secrets from git providers and databasesecrets = await self._setup_secrets_for_git_providers(user)+ # Merge API-provided secrets (they take precedence over existing ones)+ if api_secrets:+ from openhands.app_server.constants import (+ validate_secret_name,+ validate_secrets_dict,+ )++ # Validate overall dict size limits first+ # Cast to Mapping for mypy compatibility (Mapping is covariant in value type)+ validate_secrets_dict(cast('Mapping[str, object]', api_secrets))++ for name, value in api_secrets.items():+ validate_secret_name(name)+ if name in secrets:+ _logger.warning(+ 'API-provided secret %r overrides existing secret', name+ )+ secrets[name] = StaticSecret(value=value)+# --- LLM + MCP -----------------------------------------------------llm, mcp_config = await self._configure_llm_and_mcp(user, llm_model, conversation_iddiff --git a/openhands/app_server/constants.py b/openhands/app_server/constants.pynew file mode 100644index 0000000000..f716c70c23--- /dev/null+++ b/openhands/app_server/constants.py@@ -0,0 +1,169 @@+"""Constants for the OpenHands App Server.++This module contains constants that are used across the app server,+including security-related configurations for secret name validation.+"""++import os+from collections.abc import Mapping++# =============================================================================+# SECRET LIMITS (configurable via environment variables)+# =============================================================================++# Maximum number of secrets that can be passed via API in a single request.+# Prevents abuse by limiting the size of the secrets dictionary.+# Override with: OH_MAX_API_SECRETS_COUNT+MAX_API_SECRETS_COUNT: int = int(os.getenv('OH_MAX_API_SECRETS_COUNT', '50'))++# Maximum length of a secret name in characters.+# Environment variable names should be concise; this prevents excessively long names.+# Override with: OH_MAX_API_SECRET_NAME_LENGTH+MAX_API_SECRET_NAME_LENGTH: int = int(os.getenv('OH_MAX_API_SECRET_NAME_LENGTH', '256'))++# Maximum length of a secret value in bytes.+# 64KB is generous for API keys/tokens while preventing massive payloads.+# Override with: OH_MAX_API_SECRET_VALUE_LENGTH+MAX_API_SECRET_VALUE_LENGTH: int = int(+ os.getenv('OH_MAX_API_SECRET_VALUE_LENGTH', '65536')+)+++# =============================================================================+# SECRET NAME VALIDATION+# =============================================================================++# -----------------------------------------------------------------------------+# BLOCKED: These names CANNOT be used as user-provided secrets.+#+# These environment variables are injected into the agent-server container+# at startup. User-provided secrets with these names would override them+# when exported in bash commands, potentially breaking the sandbox or+# creating security vulnerabilities.+# -----------------------------------------------------------------------------+BLOCKED_SECRET_NAMES: frozenset[str] = frozenset(+ {+ # Agent-server container configuration (from initial_env)+ 'OPENVSCODE_SERVER_ROOT',+ 'OH_ENABLE_VNC',+ 'LOG_JSON',+ 'OH_CONVERSATIONS_PATH',+ 'OH_BASH_EVENTS_DIR',+ 'PYTHONUNBUFFERED',+ 'ENV_LOG_LEVEL',+ # Webhook and CORS - overriding could redirect callbacks to malicious endpoints+ 'OH_WEBHOOKS_0_BASE_URL',+ 'OH_ALLOW_CORS_ORIGINS_0',+ # Worker ports - could break web application functionality+ 'WORKER_1',+ 'WORKER_2',+ }+)++# -----------------------------------------------------------------------------+# BLOCKED PREFIXES: Secret names starting with these prefixes are blocked.+#+# LLM_* variables are auto-forwarded to the agent-server container to enforce+# LLM controls (timeouts, retries, model restrictions, etc.). Allowing users+# to override these would let them escape app-server LLM controls.+# -----------------------------------------------------------------------------+BLOCKED_SECRET_PREFIXES: tuple[str, ...] = ('LLM_',)++# -----------------------------------------------------------------------------+# OVERRIDABLE: These are system-provided but users MAY override them.+# Documented here for clarity - these are explicitly ALLOWED, not blocked.+#+# Use case: User wants to use their own credentials instead of the+# organization-level credentials provided by the system.+# -----------------------------------------------------------------------------+OVERRIDABLE_SYSTEM_SECRETS: frozenset[str] = frozenset(+ {+ # Git Provider Tokens - users may provide their own credentials+ # Note: Provider tokens are fetched via app-server API, not container env+ 'GITHUB_TOKEN',+ 'GITLAB_TOKEN',+ 'BITBUCKET_TOKEN',+ 'AZURE_DEVOPS_TOKEN',+ 'FORGEJO_TOKEN',+ # AWS Credentials - used for Bedrock LLM access+ # Users may want to use their own AWS account for Bedrock models+ 'AWS_ACCESS_KEY_ID',+ 'AWS_SECRET_ACCESS_KEY',+ 'AWS_REGION_NAME',+ }+)+++def validate_secret_name(name: str) -> None:+ """Validate that a secret name is allowed.++ Args:+ name: The secret name to validate++ Raises:+ ValueError: If the name is blocked (exact match or prefix match),+ or exceeds the maximum length+ """+ # Check name length+ if len(name) > MAX_API_SECRET_NAME_LENGTH:+ raise ValueError(+ f'Secret name exceeds maximum length of {MAX_API_SECRET_NAME_LENGTH} characters '+ f'(got {len(name)}). Configure via OH_MAX_API_SECRET_NAME_LENGTH.'+ )++ upper_name = name.upper()++ # Check exact matches+ if upper_name in BLOCKED_SECRET_NAMES:+ raise ValueError(+ f"Secret name '{name}' is reserved for internal use and cannot be overridden. "+ f'See openhands.app_server.constants for the list of blocked names.'+ )++ # Check prefix matches+ for prefix in BLOCKED_SECRET_PREFIXES:+ if upper_name.startswith(prefix):+ raise ValueError(+ f"Secret name '{name}' starts with reserved prefix '{prefix}' and cannot be used. "+ f'These variables are used for LLM configuration controls.'+ )++ # Note: OVERRIDABLE_SYSTEM_SECRETS are intentionally allowed+++def validate_secrets_dict(secrets: Mapping[str, object] | None) -> None:+ """Validate the entire secrets dictionary for size limits.++ This should be called before iterating over individual secrets.++ Args:+ secrets: The secrets dictionary to validate (can be None).+ Values can be str or SecretStr (uses get_secret_value()).++ Raises:+ ValueError: If the dictionary exceeds size limits+ """+ if secrets is None:+ return++ # Check number of secrets+ if len(secrets) > MAX_API_SECRETS_COUNT:+ raise ValueError(+ f'Too many secrets provided: {len(secrets)} exceeds maximum of '+ f'{MAX_API_SECRETS_COUNT}. Configure via OH_MAX_API_SECRETS_COUNT.'+ )++ # Check individual value lengths+ for name, value in secrets.items():+ # Handle both str and SecretStr (Pydantic's SecretStr has get_secret_value())+ if hasattr(value, 'get_secret_value'):+ value_str = value.get_secret_value() # type: ignore[union-attr]+ else:+ value_str = str(value)+ value_bytes = len(value_str.encode('utf-8'))+ if value_bytes > MAX_API_SECRET_VALUE_LENGTH:+ raise ValueError(+ f"Secret '{name}' value exceeds maximum length of "+ f'{MAX_API_SECRET_VALUE_LENGTH} bytes (got {value_bytes}). '+ f'Configure via OH_MAX_API_SECRET_VALUE_LENGTH.'+ )diff --git a/openhands/app_server/sandbox/sandbox_spec_service.py b/openhands/app_server/sandbox/sandbox_spec_service.pyindex 1d6cca1785..223f4b01fc 100644--- a/openhands/app_server/sandbox/sandbox_spec_service.py+++ b/openhands/app_server/sandbox/sandbox_spec_service.py@@ -13,7 +13,7 @@ from openhands.sdk.utils.models import DiscriminatedUnionMixin# The version of the agent server to use for deployments.# Typically this will be the same as the values from the pyproject.toml-AGENT_SERVER_IMAGE = 'ghcr.io/openhands/agent-server:1.17.0-python'+AGENT_SERVER_IMAGE = 'ghcr.io/openhands/agent-server:1.18.1-python'class SandboxSpecService(ABC):diff --git a/tests/unit/app_server/test_constants.py b/tests/unit/app_server/test_constants.pynew file mode 100644index 0000000000..b9fbdabced--- /dev/null+++ b/tests/unit/app_server/test_constants.py@@ -0,0 +1,163 @@+"""Tests for openhands.app_server.constants module."""++import os+from unittest.mock import patch++import pytest++from openhands.app_server.constants import (+ BLOCKED_SECRET_NAMES,+ BLOCKED_SECRET_PREFIXES,+ MAX_API_SECRET_NAME_LENGTH,+ MAX_API_SECRET_VALUE_LENGTH,+ MAX_API_SECRETS_COUNT,+ validate_secret_name,+ validate_secrets_dict,+)+++class TestValidateSecretName:+ """Tests for validate_secret_name function."""++ def test_valid_secret_name(self):+ """Valid secret names should not raise."""+ validate_secret_name('MY_API_KEY')+ validate_secret_name('github_token') # case-insensitive for overridable+ validate_secret_name('CUSTOM_SECRET')+ validate_secret_name('a') # short names are OK++ def test_blocked_exact_name(self):+ """Blocked names should raise ValueError."""+ for name in BLOCKED_SECRET_NAMES:+ with pytest.raises(ValueError, match='reserved for internal use'):+ validate_secret_name(name)++ def test_blocked_name_case_insensitive(self):+ """Blocked name check should be case-insensitive."""+ # Pick one from the set+ blocked_name = next(iter(BLOCKED_SECRET_NAMES))+ with pytest.raises(ValueError, match='reserved for internal use'):+ validate_secret_name(blocked_name.lower())++ def test_blocked_prefix(self):+ """Names starting with blocked prefixes should raise."""+ for prefix in BLOCKED_SECRET_PREFIXES:+ with pytest.raises(ValueError, match=f"reserved prefix '{prefix}'"):+ validate_secret_name(f'{prefix}SOME_VAR')++ def test_blocked_prefix_case_insensitive(self):+ """Blocked prefix check should be case-insensitive."""+ with pytest.raises(ValueError, match='reserved prefix'):+ validate_secret_name('llm_api_key')++ def test_name_too_long(self):+ """Names exceeding max length should raise."""+ long_name = 'A' * (MAX_API_SECRET_NAME_LENGTH + 1)+ with pytest.raises(ValueError, match='exceeds maximum length'):+ validate_secret_name(long_name)++ def test_name_at_max_length(self):+ """Names at exactly max length should be accepted."""+ max_name = 'A' * MAX_API_SECRET_NAME_LENGTH+ validate_secret_name(max_name) # Should not raise++ def test_overridable_secrets_allowed(self):+ """Overridable system secrets (like GITHUB_TOKEN) should be allowed."""+ validate_secret_name('GITHUB_TOKEN')+ validate_secret_name('GITLAB_TOKEN')+ validate_secret_name('AWS_ACCESS_KEY_ID')+++class TestValidateSecretsDict:+ """Tests for validate_secrets_dict function."""++ def test_none_secrets(self):+ """None should be accepted without error."""+ validate_secrets_dict(None)++ def test_empty_dict(self):+ """Empty dict should be accepted."""+ validate_secrets_dict({})++ def test_valid_secrets(self):+ """Valid secrets dict should not raise."""+ validate_secrets_dict(+ {+ 'KEY1': 'value1',+ 'KEY2': 'value2',+ }+ )++ def test_too_many_secrets(self):+ """Exceeding max count should raise."""+ secrets = {f'KEY_{i}': f'value_{i}' for i in range(MAX_API_SECRETS_COUNT + 1)}+ with pytest.raises(ValueError, match='Too many secrets'):+ validate_secrets_dict(secrets)++ def test_at_max_count(self):+ """Exactly max count should be accepted."""+ secrets = {f'KEY_{i}': f'value_{i}' for i in range(MAX_API_SECRETS_COUNT)}+ validate_secrets_dict(secrets) # Should not raise++ def test_value_too_long(self):+ """Secret value exceeding max length should raise."""+ long_value = 'x' * (MAX_API_SECRET_VALUE_LENGTH + 1)+ with pytest.raises(ValueError, match='value exceeds maximum length'):+ validate_secrets_dict({'KEY': long_value})++ def test_value_at_max_length(self):+ """Value at exactly max length should be accepted."""+ max_value = 'x' * MAX_API_SECRET_VALUE_LENGTH+ validate_secrets_dict({'KEY': max_value}) # Should not raise++ def test_unicode_value_bytes(self):+ """Value length should be checked in bytes, not characters."""+ # Each emoji is 4 bytes in UTF-8+ emoji_count = (MAX_API_SECRET_VALUE_LENGTH // 4) + 1+ unicode_value = 'π' * emoji_count+ with pytest.raises(ValueError, match='value exceeds maximum length'):+ validate_secrets_dict({'KEY': unicode_value})++ def test_secretstr_values(self):+ """Should handle Pydantic SecretStr values."""+ from pydantic import SecretStr++ validate_secrets_dict(+ {+ 'KEY1': SecretStr('value1'),+ 'KEY2': SecretStr('value2'),+ }+ )++ def test_secretstr_value_too_long(self):+ """Should check SecretStr value length correctly."""+ from pydantic import SecretStr++ long_value = SecretStr('x' * (MAX_API_SECRET_VALUE_LENGTH + 1))+ with pytest.raises(ValueError, match='value exceeds maximum length'):+ validate_secrets_dict({'KEY': long_value})+++class TestConfigurableLimits:+ """Tests for environment variable configuration of limits."""++ def test_default_values(self):+ """Default values should be sensible."""+ assert MAX_API_SECRETS_COUNT == 50+ assert MAX_API_SECRET_NAME_LENGTH == 256+ assert MAX_API_SECRET_VALUE_LENGTH == 65536++ def test_env_override_count(self):+ """OH_MAX_API_SECRETS_COUNT should override default."""+ # This tests that the pattern works; the actual module-level+ # value is set at import time, so we verify the env var is read+ with patch.dict(os.environ, {'OH_MAX_API_SECRETS_COUNT': '100'}):+ # Re-import to pick up new env+ import importlib++ import openhands.app_server.constants as constants++ importlib.reload(constants)+ assert constants.MAX_API_SECRETS_COUNT == 100+ # Reset for other tests+ importlib.reload(constants)diff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.pyindex 698c50913d..63bd1d0a13 100644--- a/tests/unit/app_server/test_live_status_app_conversation_service.py+++ b/tests/unit/app_server/test_live_status_app_conversation_service.py@@ -1110,6 +1110,155 @@ class TestLiveStatusAppConversationService:self.mock_user, 'gpt-4', test_conversation_id)+ @patch(+ 'openhands.app_server.app_conversation.live_status_app_conversation_service.get_default_tools',+ return_value=[],+ )+ @pytest.mark.asyncio+ async def test_build_start_conversation_request_with_api_secrets(self, _mock_tools):+ """Test _build_start_conversation_request_for_user with API-provided secrets."""+ self.mock_user_context.get_user_info.return_value = self.mock_user++ # Existing secrets from git providers+ existing_secrets = {+ 'GITHUB_TOKEN': StaticSecret(value=SecretStr('github_tok')),+ 'EXISTING_SECRET': StaticSecret(value=SecretStr('existing_value')),+ }+ real_llm = LLM(model='gpt-4', api_key=SecretStr('test-key'))+ mock_mcp_config = {'default': {'url': 'test'}}+ test_conversation_id = uuid4()++ self.service._setup_secrets_for_git_providers = AsyncMock(+ return_value=existing_secrets+ )+ self.service._configure_llm_and_mcp = AsyncMock(+ return_value=(real_llm, mock_mcp_config)+ )++ # API-provided secrets - should be merged with existing secrets+ api_secrets = {+ 'MY_API_KEY': SecretStr('my_api_key_value'),+ 'ANOTHER_SECRET': SecretStr('another_value'),+ }++ result = await self.service._build_start_conversation_request_for_user(+ sandbox=self.mock_sandbox,+ conversation_id=test_conversation_id,+ initial_message=None,+ system_message_suffix=None,+ git_provider=ProviderType.GITHUB,+ working_dir='/test/dir',+ agent_type=AgentType.DEFAULT,+ llm_model='gpt-4',+ remote_workspace=None,+ selected_repository='test/repo',+ api_secrets=api_secrets,+ )++ assert isinstance(result, StartConversationRequest)+ # All secrets should be present (existing + API-provided)+ secrets = result.agent.agent_context.secrets+ assert 'GITHUB_TOKEN' in secrets+ assert 'EXISTING_SECRET' in secrets+ assert 'MY_API_KEY' in secrets+ assert 'ANOTHER_SECRET' in secrets++ # API-provided secrets should be StaticSecret instances+ assert isinstance(secrets['MY_API_KEY'], StaticSecret)+ assert secrets['MY_API_KEY'].value.get_secret_value() == 'my_api_key_value'+ assert secrets['ANOTHER_SECRET'].value.get_secret_value() == 'another_value'++ @patch(+ 'openhands.app_server.app_conversation.live_status_app_conversation_service.get_default_tools',+ return_value=[],+ )+ @pytest.mark.asyncio+ async def test_build_start_conversation_request_api_secrets_override_existing(+ self, _mock_tools+ ):+ """Test that API-provided secrets override existing secrets with the same name."""+ self.mock_user_context.get_user_info.return_value = self.mock_user++ # Existing secrets+ existing_secrets = {+ 'SHARED_SECRET': StaticSecret(value=SecretStr('original_value')),+ }+ real_llm = LLM(model='gpt-4', api_key=SecretStr('test-key'))+ mock_mcp_config = None+ test_conversation_id = uuid4()++ self.service._setup_secrets_for_git_providers = AsyncMock(+ return_value=existing_secrets+ )+ self.service._configure_llm_and_mcp = AsyncMock(+ return_value=(real_llm, mock_mcp_config)+ )++ # API-provided secret with same name should override+ api_secrets = {+ 'SHARED_SECRET': SecretStr('overridden_value'),+ }++ result = await self.service._build_start_conversation_request_for_user(+ sandbox=self.mock_sandbox,+ conversation_id=test_conversation_id,+ initial_message=None,+ system_message_suffix=None,+ git_provider=None,+ working_dir='/test/dir',+ agent_type=AgentType.DEFAULT,+ llm_model='gpt-4',+ remote_workspace=None,+ selected_repository=None,+ api_secrets=api_secrets,+ )++ # API-provided secret should override the existing one+ secrets = result.agent.agent_context.secrets+ assert secrets['SHARED_SECRET'].value.get_secret_value() == 'overridden_value'++ @patch(+ 'openhands.app_server.app_conversation.live_status_app_conversation_service.get_default_tools',+ return_value=[],+ )+ @pytest.mark.asyncio+ async def test_build_start_conversation_request_no_api_secrets(self, _mock_tools):+ """Test _build_start_conversation_request_for_user without API-provided secrets."""+ self.mock_user_context.get_user_info.return_value = self.mock_user++ existing_secrets = {+ 'GITHUB_TOKEN': StaticSecret(value=SecretStr('tok')),+ }+ real_llm = LLM(model='gpt-4', api_key=SecretStr('test-key'))+ mock_mcp_config = None+ test_conversation_id = uuid4()++ self.service._setup_secrets_for_git_providers = AsyncMock(+ return_value=existing_secrets+ )+ self.service._configure_llm_and_mcp = AsyncMock(+ return_value=(real_llm, mock_mcp_config)+ )++ # No API secrets provided (None)+ result = await self.service._build_start_conversation_request_for_user(+ sandbox=self.mock_sandbox,+ conversation_id=test_conversation_id,+ initial_message=None,+ system_message_suffix=None,+ git_provider=None,+ working_dir='/test/dir',+ agent_type=AgentType.DEFAULT,+ llm_model='gpt-4',+ remote_workspace=None,+ selected_repository=None,+ api_secrets=None,+ )++ # Only existing secrets should be present+ secrets = result.agent.agent_context.secrets+ assert secrets == existing_secrets+@pytest.mark.asyncioasync def test_find_running_sandbox_for_user_found(self):"""Test _find_running_sandbox_for_user when a running sandbox is found."""