diff --git a/changelog.d/780.md b/changelog.d/780.md new file mode 100644 index 0000000000..64851179c5 --- /dev/null +++ b/changelog.d/780.md @@ -0,0 +1,3 @@ +### Security + +- Redact secret-bearing argv items from async subprocess telemetry command summaries and terminate the entire POSIX process group on subprocess timeouts (#780). diff --git a/docs/agent/tasks/task-780-async-process-runner-telemetry-redaction-and-pgid-kill.md b/docs/agent/tasks/task-780-async-process-runner-telemetry-redaction-and-pgid-kill.md new file mode 100644 index 0000000000..5bf8145f1d --- /dev/null +++ b/docs/agent/tasks/task-780-async-process-runner-telemetry-redaction-and-pgid-kill.md @@ -0,0 +1,40 @@ +# Task 780: Async Process Runner Redacts Telemetry and Kills Process Group on Timeout + +**Issue**: [#780](https://github.com/dan-petty/devops-cli/issues/780) +**Status**: Done +**Milestone**: v0.2.28 +**Priority**: priority/p1-high +**Scope**: type/security, scope/cli + +--- + +## 1. Description & Objectives + +The async subprocess runner (`run_subprocess_async` in `src/devops_cli/core/process.py`) had drifted from the synchronous `run_subprocess` implementation in two critical ways: +1. **Telemetry Command Leakage**: `run_subprocess_async` was joining the first 8 raw argv elements directly into `cmd_summary` without sanitization, allowing secret tokens, credentials, and sensitive arguments to reach OpenTelemetry trace attributes (`subprocess.cmd` and `process.command_line`), whereas the sync path invoked `_sanitize_command_for_telemetry`. +2. **Process Group Leakage on Timeout**: On timeout, `run_subprocess_async` called `proc.kill()` solely on the direct child process without isolating the child into a dedicated session, leaving grandchild processes (such as spawned test workers, background subshells, or compilers) running indefinitely as orphaned processes. + +This deliverable: +- Aligns `run_subprocess_async` with `_sanitize_command_for_telemetry(cmd)` so all telemetry command attributes mask secrets, credentials, and parameters identically to the sync path. +- Spawns async subprocesses with POSIX process group isolation (`start_new_session=True`). +- Implements resilient process group termination on timeout (`_terminate_process_group_async`, `_signal_process_group`, `_wait_for_group_exit_async`), cleanly escalating from `SIGTERM` to `SIGKILL` while strictly guarding against signalling PID 1, PID 0, or the caller's own process group. +- Adds comprehensive tests covering secret-bearing argv sanitization, grandchild process group cleanup upon timeout, and process group guard invariants. + +--- + +## 2. Acceptance Criteria + +- [x] The async path sanitizes the telemetry command the same way as the sync path. +- [x] A timeout kills the whole process group rather than only the direct child. +- [x] Tests cover a secret-bearing argv and a child that starts its own child. +- [x] Changelog fragment `changelog.d/780.md` authored. +- [x] Gated CI quality checks pass in `uv run devops ci`. + +--- + +## 3. Deliverables + +- [x] `src/devops_cli/core/process.py`: Telemetry command sanitization and process group termination on timeout. +- [x] `tests/test_process.py`: Unit tests for telemetry secret masking, grandchild timeout termination, and pgid guard helpers. +- [x] `changelog.d/780.md`: Changelog entry. +- [x] `docs/agent/tasks/task-780-async-process-runner-telemetry-redaction-and-pgid-kill.md`: Task documentation. diff --git a/src/devops_cli/core/process.py b/src/devops_cli/core/process.py index 909c820237..c3000b6ddf 100644 --- a/src/devops_cli/core/process.py +++ b/src/devops_cli/core/process.py @@ -6,6 +6,7 @@ import fnmatch import json import os +import signal import subprocess import threading import time @@ -25,6 +26,8 @@ from devops_cli.config.defaults import ( DEFAULT_GH_AUTH_TOKEN_RETRY_SECONDS, DEFAULT_GH_AUTH_TOKEN_TIMEOUT_SECONDS, + DEFAULT_SHELL_STOP_GRACE_SECONDS, + DEFAULT_SHELL_STOP_POLL_SECONDS, DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, ) from devops_cli.dry_run import is_dry_run @@ -466,6 +469,63 @@ def run_subprocess( return proc +def _signal_process_group(pgid: int, sig: int) -> bool: + """Send a signal to the process group, returning False if unreachable.""" + if not hasattr(os, "killpg"): + return False + try: + os.killpg(pgid, sig) + except ProcessLookupError, PermissionError: + return False + return True + + +def _is_invalid_pgid(pgid: int | None) -> bool: + """Check whether a pgid is invalid or belongs to the current process group.""" + if not isinstance(pgid, int) or pgid <= 1: + return True + return bool(hasattr(os, "getpgrp") and pgid == os.getpgrp()) + + +async def _wait_for_group_exit_async( + proc: asyncio.subprocess.Process, pgid: int, deadline: float +) -> bool: + """Poll for group exit until deadline. Returns True if group exited.""" + while time.monotonic() < deadline: + if proc.returncode is not None and not _signal_process_group(pgid, 0): + return True + try: + await asyncio.wait_for(proc.wait(), timeout=DEFAULT_SHELL_STOP_POLL_SECONDS) + if not _signal_process_group(pgid, 0): + return True + except TimeoutError: + pass + return not _signal_process_group(pgid, 0) + + +async def _terminate_process_group_async( + proc: asyncio.subprocess.Process, + *, + stop_grace_seconds: float = DEFAULT_SHELL_STOP_GRACE_SECONDS, +) -> None: + """Terminate the process group of proc on timeout, escalating from SIGTERM to SIGKILL.""" + pgid = proc.pid + if _is_invalid_pgid(pgid) or not _signal_process_group(pgid, signal.SIGTERM): + proc.kill() + await proc.wait() + return + + deadline = time.monotonic() + stop_grace_seconds + if await _wait_for_group_exit_async(proc, pgid, deadline): + return + + _signal_process_group(pgid, signal.SIGKILL) + try: + await asyncio.wait_for(proc.wait(), timeout=stop_grace_seconds) + except TimeoutError: + pass + + async def run_subprocess_async( cmd: list[str], *, @@ -501,7 +561,7 @@ async def run_subprocess_async( print_dry_run_command(cmd, cwd=str(cwd) if cwd else None) bin_name = Path(cmd[0]).name if cmd else "unknown" - cmd_summary = " ".join(cmd[:8]) + ("..." if len(cmd) > 8 else "") if cmd else "" + cmd_summary = _sanitize_command_for_telemetry(cmd) start_time = time.perf_counter() sub_env = build_subprocess_env( @@ -536,14 +596,14 @@ async def run_subprocess_async( env=sub_env, stdout=stdout_pipe, stderr=stderr_pipe, + start_new_session=True, ) try: stdout_bytes, stderr_bytes = await asyncio.wait_for( proc.communicate(), timeout=timeout ) except TimeoutError: - proc.kill() - await proc.wait() + await _terminate_process_group_async(proc) raise subprocess.TimeoutExpired(cmd, timeout) from None except FileNotFoundError: dur = time.perf_counter() - start_time diff --git a/tests/test_process.py b/tests/test_process.py index 20a71c1240..0e5bebfeb4 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -2,6 +2,8 @@ from __future__ import annotations +from pathlib import Path + import pytest from devops_cli.core.process import run_subprocess, run_subprocess_async @@ -105,3 +107,92 @@ async def test_run_subprocess_async_cwd_security() -> None: with pytest.raises(SecurityError): await run_subprocess_async(["echo", "hi"], cwd=Path("/etc")) + + +@pytest.mark.anyio +async def test_run_subprocess_async_telemetry_sanitizes_secrets() -> None: + """Verify run_subprocess_async redacts secrets in telemetry command attributes.""" + from typing import Any + from unittest.mock import MagicMock, patch + + captured_attrs: dict[str, Any] = {} + + def fake_trace_span(name: str, attributes: dict[str, Any] | None = None): + if attributes: + captured_attrs.update(attributes) + mock_ctx = MagicMock() + mock_ctx.__enter__.return_value = MagicMock() + mock_ctx.__exit__.return_value = None + return mock_ctx + + token = "ghp_1234567890abcdef1234567890abcdef1234" + cmd = [ + "python3", + "-c", + "pass", + "--token", + token, + "--body", + "super_secret_body", + "title=super_secret_title", + ] + with patch("devops_cli.core.process.trace_span", side_effect=fake_trace_span): + await run_subprocess_async(cmd) + + cmd_summary = captured_attrs.get("subprocess.cmd", "") + proc_cmd = captured_attrs.get("process.command_line", "") + assert ( + token in cmd_summary, + "super_secret_body" in cmd_summary, + "super_secret_title" in cmd_summary, + cmd_summary == proc_cmd, + ) == (False, False, False, True) + + +@pytest.mark.anyio +async def test_run_subprocess_async_timeout_kills_process_group(tmp_path: Path) -> None: + """Verify run_subprocess_async timeout kills entire process group including grandchildren.""" + import os + import subprocess + import sys + + pid_file = tmp_path / "grandchild.pid" + script = ( + "import sys, time, subprocess\n" + f"child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])\n" + f"with open({str(pid_file)!r}, 'w') as f:\n" + " f.write(str(child.pid))\n" + "time.sleep(30)\n" + ) + cmd = [sys.executable, "-c", script] + + with pytest.raises(subprocess.TimeoutExpired): + await run_subprocess_async(cmd, timeout=0.6) + + assert pid_file.exists() + grandchild_pid = int(pid_file.read_text().strip()) + + is_alive = True + try: + os.kill(grandchild_pid, 0) + except ProcessLookupError: + is_alive = False + + assert is_alive is False + + +def test_process_group_guard_helpers() -> None: + """Verify process group validation guards against PID 1, 0, negative PIDs, and self.""" + import os + + from devops_cli.core.process import _is_invalid_pgid + + self_pgrp = os.getpgrp() if hasattr(os, "getpgrp") else -1 + assert ( + _is_invalid_pgid(1), + _is_invalid_pgid(0), + _is_invalid_pgid(-1), + _is_invalid_pgid(None), # type: ignore[arg-type] + _is_invalid_pgid(self_pgrp) if self_pgrp > 1 else True, + _is_invalid_pgid(999999), + ) == (True, True, True, True, True, False)