Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,11 @@ class AppConversationStartTask(OpenHandsModel):
# credential helper can fetch the current token for any of that provider's
# repositories, not only the selected one. Empty when nothing was minted.
_git_credential_access_tokens: dict[str, str] = PrivateAttr(default_factory=dict)
# The providers whose credential helper the setup flow installed in the
# sandbox. A clone from one of them leaves the token out of its remote URL,
# so none lands in ``.git/config`` under the workspace (OHE-3812); every
# other clone keeps the authenticated URL. Empty until the helpers are set up.
_git_credential_providers: set[ProviderType] = PrivateAttr(default_factory=set)
# Clone results of the request's additional repositories, saved on the
# conversation once it starts.
_additional_repositories: list[AdditionalRepository] = PrivateAttr(
Expand Down
148 changes: 131 additions & 17 deletions openhands/app_server/app_conversation/app_conversation_service_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, AsyncGenerator
from typing import TYPE_CHECKING, Any, AsyncGenerator, NamedTuple
from urllib.parse import unquote, urlsplit, urlunsplit
from uuid import UUID

from openhands.sdk.settings import ACPAgentSettings, OpenHandsAgentSettings
Expand Down Expand Up @@ -206,6 +207,60 @@ def _azure_devops_credential_helper_script(web_url: str | None) -> str:
"""


class _GitCredentialTarget(NamedTuple):
"""What a clone needs to leave an authenticated URL's credentials to the
sandbox's git credential helper."""

provider: ProviderType
# ``host[:port]``, the ``host`` git hands the credential helper.
host: str
# The authenticated URL without its userinfo.
clean_url: str


def _git_credential_target(
remote_repo_url: str, git_provider: ProviderType | None
) -> _GitCredentialTarget | None:
"""The credential-helper target for an authenticated clone URL, or None.

None when the URL carries no credentials, when the provider has no helper
here (Azure DevOps has its own; Forgejo keeps its token URL), or when an
unspecified provider cannot be told apart from the URL shape
``get_authenticated_git_url`` gave it.
"""
parsed = urlsplit(remote_repo_url)
hostname = parsed.hostname
if not hostname or not parsed.username:
return None
if git_provider == ProviderType.AZURE_DEVOPS or 'dev.azure.com' in hostname:
return None
host = hostname if parsed.port is None else f'{hostname}:{parsed.port}'
if parsed.password is None:
# ``<token>@host``: GitHub, or Forgejo.
if git_provider not in (None, ProviderType.GITHUB):
return None
if git_provider is None and hostname != 'github.com':
return None
provider = ProviderType.GITHUB
else:
if git_provider is None:
if unquote(parsed.username) == 'oauth2':
git_provider = ProviderType.GITLAB
elif hostname == 'bitbucket.org':
git_provider = ProviderType.BITBUCKET
else:
return None
if git_provider not in (
ProviderType.GITLAB,
ProviderType.BITBUCKET,
ProviderType.BITBUCKET_DATA_CENTER,
):
return None
provider = git_provider
clean_url = urlunsplit(parsed._replace(netloc=host))
return _GitCredentialTarget(provider, host, clean_url)


# Per-conversation exchange JWTs for the other git providers, one file per
# provider (``<provider>.token``, mode 600), read by the shared credential helper
# below. The provider token the helper returns to git is never persisted.
Expand Down Expand Up @@ -516,6 +571,13 @@ async def run_setup_scripts(
) -> AsyncGenerator[AppConversationStartTask, None]:
task.status = AppConversationStartTaskStatus.PREPARING_REPOSITORY
yield task
# Deliver this conversation's per-provider git credentials before any
# clone: a helper per provider host, so hooks and the agent can clone any
# repository the user can reach with plain git, and so the clones below
# can leave the token out of their remote URL (OHE-3812).
task._git_credential_providers = await self._configure_git_credential_helpers(
workspace, getattr(task, '_git_credential_access_tokens', None)
)
await self.clone_or_init_git_repo(task, workspace, sandbox)

# Deliver this conversation's Azure DevOps credential (per conversation,
Expand All @@ -527,11 +589,6 @@ async def run_setup_scripts(
task.request.selected_repository,
azure_devops_repositories(task.request.additional_repositories),
)
# Same for the other providers: a helper per provider host, so hooks and
# the agent can clone any repository the user can reach with plain git.
await self._configure_git_credential_helpers(
workspace, getattr(task, '_git_credential_access_tokens', None)
)

task._additional_repositories = await self.clone_additional_repositories(
task, workspace
Expand Down Expand Up @@ -893,6 +950,7 @@ async def clone_or_init_git_repo(
request.selected_branch,
request.git_provider,
full_clone,
task=task,
)
if not cloned:
at_branch = (
Expand All @@ -915,13 +973,31 @@ async def _clone_repository(
branch: str | None,
git_provider: ProviderType | None,
full_clone: bool,
task: AppConversationStartTask | None = None,
) -> bool:
"""Clone a repository into ``dir_name`` and check out its branch.

Returns False when nothing usable was cloned. Never includes git's
output in errors: the URL and that output can hold credentials.

With ``task``, a repository on a provider whose credential helper the
setup flow installed (``_configure_git_credential_helpers``) is cloned
with the URL stripped of its embedded credentials, so none lands in
``.git/config`` (OHE-3812); the helper supplies the token to git.
Otherwise the authenticated URL is cloned as before.
"""
quoted_remote_repo_url = shlex.quote(remote_repo_url)
clone_url = remote_repo_url
helper_host: str | None = None
target = _git_credential_target(remote_repo_url, git_provider)
providers = getattr(task, '_git_credential_providers', None)
if (
target is not None
and isinstance(providers, (set, frozenset))
and target.provider in providers
):
clone_url = target.clean_url
helper_host = target.host
quoted_remote_repo_url = shlex.quote(clone_url)
quoted_dir_name = shlex.quote(dir_name)
git_dir = Path(workspace.working_dir) / dir_name
azure_devops_bearer_token = await self._get_azure_devops_bearer_token_for_git(
Expand Down Expand Up @@ -966,6 +1042,8 @@ async def _clone_repository(
)
if existing.exit_code:
return False
if helper_host:
await self._strip_origin_credentials(workspace, git_dir, helper_host)

# Checkout the appropriate branch
if branch:
Expand Down Expand Up @@ -1008,7 +1086,7 @@ async def clone(
) -> AdditionalRepository:
async with semaphore:
error = await self._clone_additional_repository(
workspace, item, folder, full_clone
workspace, item, folder, full_clone, task=task
)
return AdditionalRepository(
repository=item.repository,
Expand Down Expand Up @@ -1041,6 +1119,7 @@ async def _clone_additional_repository(
item: AdditionalRepositoryRequest,
folder: str,
full_clone: bool,
task: AppConversationStartTask | None = None,
) -> str | None:
"""Clone one additional repository; return an error message on failure."""
at_branch = f' at branch {item.branch!r}' if item.branch else ''
Expand All @@ -1062,6 +1141,7 @@ async def _clone_additional_repository(
item.branch,
item.git_provider,
full_clone,
task=task,
):
return None
except Exception as exc:
Expand All @@ -1083,6 +1163,36 @@ async def _get_azure_devops_bearer_token_for_git(

return await get_azure_devops_bearer_token(self.user_context)

async def _strip_origin_credentials(
self, workspace: AsyncRemoteWorkspace, git_dir: Path, helper_host: str
) -> None:
"""Drop embedded credentials from ``origin`` of an already-present clone.

A sub-conversation sharing its sandbox finds the repository cloned by an
earlier conversation with the token in the remote URL. Now that the
credential helper supplies the token for ``helper_host``, the URL is
rewritten without its userinfo so it leaves ``.git/config``.
"""
result = await workspace.execute_command('git remote get-url origin', git_dir)
if result.exit_code:
return
parsed = urlsplit(result.stdout.strip())
hostname = parsed.hostname
if not hostname or not parsed.username:
return
host = hostname if parsed.port is None else f'{hostname}:{parsed.port}'
if host != helper_host:
return
clean_url = urlunsplit(parsed._replace(netloc=host))
result = await workspace.execute_command(
f'git remote set-url origin {shlex.quote(clean_url)}', git_dir
)
if result.exit_code:
_logger.warning(
'Git remote set-url failed: '
f'{redact_url_credentials_in_text(result.stderr)}'
)

async def _configure_azure_devops_git_credentials(
self,
workspace: AsyncRemoteWorkspace,
Expand Down Expand Up @@ -1165,26 +1275,27 @@ async def _configure_git_credential_helpers(
self,
workspace: AsyncRemoteWorkspace,
access_tokens: Mapping[str, str] | None,
) -> None:
) -> set[ProviderType]:
"""Deliver this conversation's per-provider credentials to the sandbox.

For each provider with a minted exchange JWT, writes the JWT to a
mode-600 file and configures the shared credential helper for that
provider's git host (``credential.<protocol>://<host>``) in the global
git config, so plain ``git clone/fetch/push`` of any repository on that
host, from the agent's terminal or a hook, authenticates with the
user's current token. The selected repository keeps its authenticated
remote URL, which git prefers over a helper. Skips entirely when nothing
was minted. Azure DevOps is handled by
user's current token. Returns the providers whose helper is in place:
``_clone_repository`` clones their repositories without the token in
the remote URL. Empty, and the clones keep their authenticated URL,
when nothing was minted or the setup failed. Azure DevOps is handled by
``_configure_azure_devops_git_credentials``.
"""
if not isinstance(access_tokens, Mapping) or not access_tokens:
return
return set()
try:
provider_handler = await self.user_context.get_provider_handler()
except Exception as exc:
_logger.debug(f'No provider handler for git credential helpers: {exc}')
return
return set()

web_url = getattr(self, 'web_url', None)
if web_url is None:
Expand All @@ -1202,6 +1313,7 @@ async def _configure_git_credential_helpers(
'chmod 700 "$helper"',
]
configured: list[str] = []
providers: set[ProviderType] = set()
for value, token in access_tokens.items():
try:
provider = ProviderType(value)
Expand All @@ -1228,14 +1340,16 @@ async def _configure_git_credential_helpers(
f'{shlex.quote(prefix + ".helper")} "!\\"$helper\\" {value}"',
]
configured.append(f'{value}@{host}')
providers.add(provider)
if not configured:
return
return set()
# Run in '/', which always exists; every path here is absolute under $HOME.
result = await workspace.execute_command(' && '.join(commands), '/')
if result.exit_code:
_logger.warning(f'Git credential helper setup failed: {result.stderr}')
else:
_logger.info(f'Git credential helpers configured for {configured}')
return set()
_logger.info(f'Git credential helpers configured for {configured}')
return providers

async def _configure_marketplace_git_credentials(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,11 @@ async def _mint_git_credential_access_tokens(
"""
if not self.web_url:
return
# The helper exchanges each JWT at the webhook secrets endpoint; when
# the sandbox cannot call back, nothing is minted and the clones keep
# their authenticated URL (``_clone_repository``).
if not self._secret_lookup_url():
return
try:
provider_handler = await self.user_context.get_provider_handler()
user_id = await self.user_context.get_user_id()
Expand Down
25 changes: 25 additions & 0 deletions tests/unit/app_server/test_additional_repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,31 @@ async def _run_setup(service, request):
return task, workspace


@pytest.mark.asyncio
async def test_setup_installs_the_credential_helpers_before_cloning():
"""The per-provider credential helpers go in before any clone, and the
providers they cover are recorded on the task, so the clones can leave the
token out of their remote URL."""
service = _setup_service([])
order: list = []

async def configure_helpers(workspace, tokens):
order.append('helpers')
return {GITHUB}

async def clone(task, workspace, sandbox):
order.append(('clone', set(task._git_credential_providers)))

service._configure_git_credential_helpers = AsyncMock(side_effect=configure_helpers)
service.clone_or_init_git_repo = AsyncMock(side_effect=clone)

task, workspace = await _run_setup(service, _start_request())

assert order == ['helpers', ('clone', {GITHUB})]
assert task._git_credential_providers == {GITHUB}
service._configure_git_credential_helpers.assert_awaited_once_with(workspace, {})


@pytest.mark.asyncio
async def test_require_all_fails_the_start_when_a_repository_does_not_clone():
service = _setup_service(
Expand Down
Loading
Loading