Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Validate selected branch names before checkout (#13667)

Engel Nystdbd199e77cdf
diff --git a/openhands/app_server/app_conversation/app_conversation_service_base.py b/openhands/app_server/app_conversation/app_conversation_service_base.py
index 1a87d0eb0b..4f415dad53 100644
--- a/openhands/app_server/app_conversation/app_conversation_service_base.py
+++ b/openhands/app_server/app_conversation/app_conversation_service_base.py
@@ -1,5 +1,6 @@
import logging
import os
+import shlex
import tempfile
from abc import ABC
from dataclasses import dataclass
@@ -41,6 +42,7 @@ from openhands.sdk.security.confirmation_policy import (
)
from openhands.sdk.security.llm_analyzer import LLMSecurityAnalyzer
from openhands.sdk.workspace.remote.async_remote_workspace import AsyncRemoteWorkspace
+from openhands.utils.git import ensure_valid_git_branch_name
_logger = logging.getLogger(__name__)
PRE_COMMIT_HOOK = '.git/hooks/pre-commit'
@@ -352,9 +354,11 @@ class AppConversationServiceBase(AppConversationService, ABC):
raise ValueError('Missing either Git token or valid repository')
dir_name = request.selected_repository.split('/')[-1]
+ quoted_remote_repo_url = shlex.quote(remote_repo_url)
+ quoted_dir_name = shlex.quote(dir_name)
# Clone the repo - this is the slow part!
- clone_command = f'git clone {remote_repo_url} {dir_name}'
+ clone_command = f'git clone {quoted_remote_repo_url} {quoted_dir_name}'
result = await workspace.execute_command(
clone_command, workspace.working_dir, 120
)
@@ -363,12 +367,15 @@ class AppConversationServiceBase(AppConversationService, ABC):
# Checkout the appropriate branch
if request.selected_branch:
- checkout_command = f'git checkout {request.selected_branch}'
+ ensure_valid_git_branch_name(request.selected_branch)
+ checkout_command = f'git checkout {shlex.quote(request.selected_branch)}'
else:
# Generate a random branch name to avoid conflicts
random_str = base62.encodebytes(os.urandom(16))
openhands_workspace_branch = f'openhands-workspace-{random_str}'
- checkout_command = f'git checkout -b {openhands_workspace_branch}'
+ checkout_command = (
+ f'git checkout -b {shlex.quote(openhands_workspace_branch)}'
+ )
git_dir = Path(workspace.working_dir) / dir_name
result = await workspace.execute_command(checkout_command, git_dir)
if result.exit_code:
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.py
index f3010ad406..861e1152e4 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
@@ -103,6 +103,7 @@ from openhands.tools.preset.planning import (
format_plan_structure,
get_planning_tools,
)
+from openhands.utils.git import ensure_valid_git_branch_name
_conversation_info_type_adapter = TypeAdapter(list[ConversationInfo | None])
_logger = logging.getLogger(__name__)
@@ -1710,9 +1711,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
if 'selected_branch' in request.model_fields_set:
branch = request.selected_branch
if branch is not None:
- # Sanitize: check for dangerous characters
- if any(c in branch for c in [';', '&', '|', '$', '`', '\n', '\r', ' ']):
- raise ValueError(f"Invalid characters in branch name: '{branch}'")
+ ensure_valid_git_branch_name(branch)
async def update_app_conversation(
self, conversation_id: UUID, request: AppConversationUpdateRequest
diff --git a/openhands/utils/git.py b/openhands/utils/git.py
new file mode 100644
index 0000000000..7dac7892a0
--- /dev/null
+++ b/openhands/utils/git.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+import subprocess
+
+COMMON_BRANCH_EXAMPLES = "'main', 'feature/foo', or 'release/1.2.3'"
+
+
+def is_valid_git_branch_name(branch_name: str) -> bool:
+ """Return True when branch_name matches git branch naming rules."""
+ if not branch_name:
+ return False
+
+ return (
+ subprocess.run(
+ ['git', 'check-ref-format', '--branch', branch_name],
+ check=False,
+ capture_output=True,
+ text=True,
+ ).returncode
+ == 0
+ )
+
+
+def ensure_valid_git_branch_name(branch_name: str) -> None:
+ """Raise ValueError when branch_name is not safe to pass to git checkout."""
+ if is_valid_git_branch_name(branch_name):
+ return
+
+ raise ValueError(
+ f'Invalid git branch name. Common GitHub/GitLab/Bitbucket '
+ f'branch names look like {COMMON_BRANCH_EXAMPLES}.'
+ )
diff --git a/tests/unit/app_server/test_app_conversation_service_base.py b/tests/unit/app_server/test_app_conversation_service_base.py
index f1d0711416..b1c546e743 100644
--- a/tests/unit/app_server/test_app_conversation_service_base.py
+++ b/tests/unit/app_server/test_app_conversation_service_base.py
@@ -5,6 +5,7 @@ and the recent bug fixes for git checkout operations.
"""
import subprocess
+from pathlib import Path
from types import MethodType
from unittest.mock import AsyncMock, MagicMock, Mock, patch
from uuid import uuid4
@@ -761,6 +762,33 @@ def mock_workspace():
return MockWorkspace(working_dir='/workspace/project')
+async def test_clone_or_init_git_repo_quotes_selected_branch_before_checkout(
+ mock_workspace,
+):
+ user_info = MockUserInfo()
+ service, mock_user_context = _create_service_with_mock_user_context(
+ user_info, bind_methods=('clone_or_init_git_repo',)
+ )
+ service.init_git_in_empty_workspace = True
+ mock_user_context.get_authenticated_git_url = AsyncMock(
+ return_value='https://github.com/owner/repo.git'
+ )
+
+ task = Mock()
+ task.request = Mock(
+ selected_repository='owner/repo',
+ selected_branch='feature>tmp',
+ )
+
+ await service.clone_or_init_git_repo(task, mock_workspace)
+
+ mock_workspace.execute_command.assert_any_call(
+ "git checkout 'feature>tmp'",
+ Path(mock_workspace.working_dir) / 'repo',
+ )
+
+
@pytest.mark.asyncio
async def test_configure_git_user_settings_both_name_and_email(mock_workspace):
"""Test configuring both git user name and email."""
diff --git a/tests/unit/utils/test_git.py b/tests/unit/utils/test_git.py
new file mode 100644
index 0000000000..b4569248bd
--- /dev/null
+++ b/tests/unit/utils/test_git.py
@@ -0,0 +1,28 @@
+import pytest
+
+from openhands.utils.git import ensure_valid_git_branch_name, is_valid_git_branch_name
+
+
+def test_is_valid_git_branch_name_accepts_common_hosted_git_branch_names():
+ for branch_name in (
+ 'main',
+ 'feature/test-branch',
+ 'release/1.2.3',
+ 'dependabot/npm_and_yarn/sdk-1.2.3',
+ 'renovate/grouped-updates',
+ ):
+ assert is_valid_git_branch_name(branch_name) is True
+
+
+ 'branch_name',
+ [
+ 'main; git -C /workspace/TylersTestRepo remote -v >/root/file.txt;',
+ 'feature branch',
+ 'feature..branch',
+ '-branch',
+ ],
+)
+def test_ensure_valid_git_branch_name_rejects_invalid_git_syntax(branch_name):
+ with pytest.raises(ValueError, match='Common GitHub/GitLab/Bitbucket branch names'):
+ ensure_valid_git_branch_name(branch_name)