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
29 changes: 7 additions & 22 deletions openhands-sdk/openhands/sdk/git/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,6 @@
GIT_EMPTY_TREE_HASH = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"


def _redact_args_for_logging(args: list[str]) -> str:
"""Redact credentials from git command arguments for safe logging.

Joins command args with shlex.join and redacts any URLs containing credentials.

Args:
args: List of command arguments.

Returns:
A string representation of the command with credentials redacted.
"""
redacted_args = [redact_url_credentials(arg) for arg in args]
return shlex.join(redacted_args)


def run_git_command(
args: list[str],
cwd: str | Path | None = None,
Expand All @@ -48,6 +33,9 @@ def run_git_command(
Raises:
GitCommandError: If the git command fails
"""
redacted_args = [redact_url_credentials(a) for a in args]
cmd_str = shlex.join(redacted_args)

try:
result = subprocess.run(
args,
Expand All @@ -59,29 +47,26 @@ def run_git_command(
)

if result.returncode != 0:
# Redact credentials from command for logging and error messages
cmd_str = _redact_args_for_logging(args)
error_msg = f"Git command failed: {cmd_str}"
logger.error(
f"{error_msg}. Exit code: {result.returncode}. Stderr: {result.stderr}"
)
raise GitCommandError(
message=error_msg,
command=args,
command=redacted_args,
exit_code=result.returncode,
stderr=result.stderr.strip(),
)

logger.debug(f"Git command succeeded: {_redact_args_for_logging(args)}")
logger.debug(f"Git command succeeded: {cmd_str}")
return result.stdout.strip()

except subprocess.TimeoutExpired as e:
cmd_str = _redact_args_for_logging(args)
error_msg = f"Git command timed out: {cmd_str}"
logger.error(error_msg)
raise GitCommandError(
message=error_msg,
command=args,
command=redacted_args,
exit_code=-1,
stderr="Command timed out",
) from e
Expand All @@ -90,7 +75,7 @@ def run_git_command(
logger.error(error_msg)
raise GitCommandError(
message=error_msg,
command=args,
command=redacted_args,
exit_code=-1,
stderr="Git executable not found",
) from e
Expand Down
49 changes: 48 additions & 1 deletion tests/sdk/git/test_url_redaction.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
"""Tests for URL credential redaction utilities."""

from openhands.sdk.git.utils import redact_url_credentials # re-exported for compat
import subprocess
from unittest.mock import patch

import pytest

from openhands.sdk.git.exceptions import GitCommandError
from openhands.sdk.git.utils import (
redact_url_credentials,
run_git_command,
) # re-exported for compat
from openhands.sdk.plugin.types import PluginSource, ResolvedPluginSource
from openhands.sdk.utils.redact import (
redact_url_credentials as redact_url_credentials_central,
Expand Down Expand Up @@ -195,3 +204,41 @@ def test_importable_from_sdk_utils_redact(self):
assert (
redact_url_credentials_central("https://t@host/r") == "https://****@host/r"
)


CREDENTIAL_URL = "https://oauth2:SUPERSECRET@github.com/o/r.git"
REDACTED_URL = "https://****@github.com/o/r.git"


class TestRunGitCommandCredentialRedaction:
"""Credentials must not leak into GitCommandError.command on any error path."""

def _args(self):
return ["git", "clone", CREDENTIAL_URL, "/tmp/x"]

def test_nonzero_returncode_redacts_command(self):
completed = subprocess.CompletedProcess(
args=self._args(), returncode=128, stdout="", stderr="fatal: repo not found"
)
with patch("subprocess.run", return_value=completed):
with pytest.raises(GitCommandError) as exc_info:
run_git_command(self._args())
assert CREDENTIAL_URL not in exc_info.value.command
assert REDACTED_URL in exc_info.value.command

def test_timeout_expired_redacts_command(self):
with patch(
"subprocess.run",
side_effect=subprocess.TimeoutExpired(cmd=self._args(), timeout=30),
):
with pytest.raises(GitCommandError) as exc_info:
run_git_command(self._args())
assert CREDENTIAL_URL not in exc_info.value.command
assert REDACTED_URL in exc_info.value.command

def test_file_not_found_redacts_command(self):
with patch("subprocess.run", side_effect=FileNotFoundError):
with pytest.raises(GitCommandError) as exc_info:
run_git_command(["git-not-on-path", "clone", CREDENTIAL_URL, "/tmp/x"])
assert CREDENTIAL_URL not in exc_info.value.command
assert REDACTED_URL in exc_info.value.command
Loading