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
45 changes: 45 additions & 0 deletions openhands-tools/openhands/tools/terminal/terminal/tmux_terminal.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"""Tmux-based terminal backend implementation."""

import logging
import time
import uuid
from collections.abc import Mapping

import libtmux

from openhands.sdk.logger import get_logger
from openhands.sdk.utils.redact import redact_api_key_literals
from openhands.tools.terminal.constants import (
HISTORY_LIMIT,
TMUX_SESSION_HEIGHT,
Expand All @@ -24,6 +26,48 @@

logger = get_logger(__name__)


class _SecretRedactFilter(logging.Filter):
"""Redact API key literals from libtmux log records."""

def filter(self, record: logging.LogRecord) -> bool:
if record.msg and isinstance(record.msg, str):
record.msg = redact_api_key_literals(record.msg)
if record.args:
if isinstance(record.args, Mapping):
record.args = {
k: redact_api_key_literals(v) if isinstance(v, str) else v
for k, v in record.args.items()
}
elif isinstance(record.args, tuple):
record.args = tuple(
redact_api_key_literals(a) if isinstance(a, str) else a
for a in record.args
)
tmux_cmd = getattr(record, "tmux_cmd", None)
if tmux_cmd and isinstance(tmux_cmd, str):
record.tmux_cmd = redact_api_key_literals(tmux_cmd)
return True


def _install_libtmux_redaction_filter() -> None:
logger_names = [
"libtmux",
*(
name
for name, candidate in logging.Logger.manager.loggerDict.items()
if name.startswith("libtmux.") and isinstance(candidate, logging.Logger)
),
]
for logger_name in logger_names:
libtmux_logger = logging.getLogger(logger_name)
if not any(
isinstance(log_filter, _SecretRedactFilter)
for log_filter in libtmux_logger.filters
):
libtmux_logger.addFilter(_SecretRedactFilter())


# Map normalized special key names to tmux key names.
_TMUX_SPECIALS: dict[str, str] = {
"ENTER": "Enter",
Expand Down Expand Up @@ -64,6 +108,7 @@ def __init__(
env: Mapping[str, str] | None = None,
):
super().__init__(work_dir, username)
_install_libtmux_redaction_filter()
self.PS1 = CmdOutputMetadata.to_ps1_prompt()
self._env = normalize_terminal_env(env)

Expand Down
36 changes: 36 additions & 0 deletions tests/tools/terminal/test_tmux_log_redaction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import io
import logging

from openhands.tools.terminal.terminal.tmux_terminal import TmuxTerminal


def test_tmux_terminal_redacts_secrets_from_libtmux_child_logger(tmp_path):
secret = "sk-proj-abcdefghijklmnopqrstuvwxyz123456"
stream = io.StringIO()
handler = logging.StreamHandler(stream)
libtmux_logger = logging.getLogger("libtmux")
libtmux_loggers = [
libtmux_logger,
*(
candidate
for name, candidate in logging.Logger.manager.loggerDict.items()
if name.startswith("libtmux.") and isinstance(candidate, logging.Logger)
),
]
original_filters = {logger: logger.filters[:] for logger in libtmux_loggers}
original_handlers = libtmux_logger.handlers[:]
original_propagate = libtmux_logger.propagate

libtmux_logger.handlers = [handler]
libtmux_logger.propagate = False
try:
TmuxTerminal(work_dir=str(tmp_path))
logging.getLogger("libtmux.common").error("tmux send-keys %s", secret)

assert secret not in stream.getvalue()
assert "<redacted>" in stream.getvalue()
finally:
for logger, filters in original_filters.items():
logger.filters = filters
libtmux_logger.handlers = original_handlers
libtmux_logger.propagate = original_propagate
Loading