Skip to content

The agent that grows with you

fix(gateway): persist shutdown forensics without process argv

joaomarcos1d291102d6ba
diff --git a/gateway/run.py b/gateway/run.py
index 4182ae9cdde..ffd2d59a9c5 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -5031,7 +5031,7 @@ def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdo
logger.warning("Shutdown context: %s", format_context_for_log(_shutdown_ctx))
def _diagnostic() -> None:
- # Heavyweight (ps auxf, pstree, dmesg), detached so it finishes even if our cgroup is torn
+ # Heavyweight (comm-only ps, pstree, dmesg), detached so it finishes even if our cgroup is torn
# down; bounded by an internal timeout, never blocks.
from gateway.shutdown_forensics import spawn_async_diagnostic
spawn_async_diagnostic(
diff --git a/gateway/shutdown_forensics.py b/gateway/shutdown_forensics.py
index 8c790a392ed..7606d615f58 100644
--- a/gateway/shutdown_forensics.py
+++ b/gateway/shutdown_forensics.py
@@ -48,7 +48,8 @@ def _read_proc_field(pid: int, key: str) -> Optional[str]:
def _proc_summary(pid: int) -> Dict[str, Any]:
- """Compact /proc/<pid> snapshot (pid, ppid, state, uid, cmdline); missing fields omitted."""
+ """Compact /proc/<pid> identity (pid, name, state, ppid, uid). Never reads cmdline/argv —
+ those bytes are not safe to persist (tokens, URIs, ``-e KEY=`` overlays)."""
summary: Dict[str, Any] = {"pid": pid}
if pid <= 0:
return summary
@@ -60,12 +61,6 @@ def _proc_summary(pid: int) -> Dict[str, Any]:
summary["ppid"] = int(ppid)
if (uid := _read_proc_field(pid, "Uid")) is not None:
summary["uid"] = uid.split()[0] if uid else uid # "real effective saved fs"
- try:
- data = Path(f"/proc/{pid}/cmdline").read_bytes()
- except OSError:
- data = b""
- if data: # truncate aggressively — these can be 4KB
- summary["cmdline"] = data.replace(b"\x00", b" ").decode("utf-8", errors="replace").strip()[:300]
return summary
@@ -119,12 +114,28 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:
return ctx
+def _async_diagnostic_script(signal_name: str, self_pid: int) -> str:
+ """POSIX listing used by the detached diagnostic. Columns are identity/resource only — no argv."""
+ return (
+ f"echo '=== shutdown diagnostic @ {signal_name} ==='; "
+ "echo '--- date ---'; date -u +%Y-%m-%dT%H:%M:%SZ; "
+ "echo '--- ps (top 60 by cpu, comm only) ---'; "
+ "ps -eo pid,ppid,user,pcpu,pmem,stat,comm --sort=-pcpu 2>/dev/null | head -60; "
+ f"echo '--- pstree of self ---'; pstree -pl {self_pid} 2>/dev/null | head -40 || true; "
+ "echo '--- /proc/loadavg ---'; cat /proc/loadavg 2>/dev/null || true; "
+ "echo '--- recent dmesg (oom/killed) ---'; "
+ "dmesg -T 2>/dev/null | tail -20 || journalctl --user -n 20 --no-pager 2>/dev/null | tail -20 || true; "
+ "echo '=== end ==='"
+ )
+
+
def spawn_async_diagnostic(log_path: Path, signal_name: str, *,
timeout_seconds: float = 5.0) -> Optional[int]:
"""Fire-and-forget ``ps``-style snapshot appended to ``log_path``: a detached subprocess (own
- ``timeout`` so a wedged ``ps`` self-cleans) rather than a blocking ``ps aux`` in the signal
+ ``timeout`` so a wedged ``ps`` self-cleans) rather than a blocking process listing in the signal
handler, which can freeze the loop >2s on a busy host. Returns the subprocess PID, or ``None``
on failure / Windows (bash -c is available on every POSIX target; Windows has no ps anyway).
+ The listing is comm-only: full argv is not persisted.
"""
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
@@ -132,20 +143,14 @@ def spawn_async_diagnostic(log_path: Path, signal_name: str, *,
return None
if sys.platform == "win32":
return None
- script = (
- f"echo '=== shutdown diagnostic @ {signal_name} ==='; "
- "echo '--- date ---'; date -u +%Y-%m-%dT%H:%M:%SZ; "
- "echo '--- ps auxf (top 60 by cpu) ---'; ps auxf --sort=-pcpu 2>/dev/null | head -60; "
- f"echo '--- pstree of self ---'; pstree -plau {os.getpid()} 2>/dev/null | head -40 || true; "
- "echo '--- /proc/loadavg ---'; cat /proc/loadavg 2>/dev/null || true; "
- "echo '--- recent dmesg (oom/killed) ---'; "
- "dmesg -T 2>/dev/null | tail -20 || journalctl --user -n 20 --no-pager 2>/dev/null | tail -20 || true; "
- "echo '=== end ==='"
- )
+ script = _async_diagnostic_script(signal_name, os.getpid())
try: # O_APPEND so concurrent diagnostics from rapid signals don't trample each other
- fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
+ fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
except OSError:
return None
+ # Unix-only; AttributeError on Windows if this path is ever reached.
+ with contextlib.suppress(OSError, AttributeError):
+ os.fchmod(fd, 0o600)
try: # start_new_session: outlive systemd killing our cgroup (KillMode=control-group) to flush
return subprocess.Popen(
["timeout", f"{timeout_seconds:.0f}", "bash", "-c", script], stdout=fd,
@@ -159,7 +164,7 @@ def spawn_async_diagnostic(log_path: Path, signal_name: str, *,
def format_context_for_log(ctx: Dict[str, Any]) -> str:
- """Render a shutdown context dict as one scannable log line (parent cmdline is key)."""
+ """Render a shutdown context dict as one scannable log line (parent identity, never argv)."""
parent = ctx.get("parent") or {}
load_str = f"{load:.2f}" if isinstance(load := ctx.get("loadavg_1m"), (int, float)) else "?"
extras: List[str] = []
@@ -174,7 +179,7 @@ def format_context_for_log(ctx: Dict[str, Any]) -> str:
return (
f"signal={ctx.get('signal', '?')} under_systemd={'yes' if ctx.get('under_systemd') else 'no'} "
f"parent_pid={parent.get('pid') or '?'} parent_name={parent.get('name') or '?'} "
- f"loadavg_1m={load_str}{extras_str} parent_cmdline={parent.get('cmdline', '(unknown)')!r}"
+ f"loadavg_1m={load_str}{extras_str}"
)
diff --git a/tests/gateway/test_shutdown_forensics.py b/tests/gateway/test_shutdown_forensics.py
index 75565e26cbc..0ddafaf5af4 100644
--- a/tests/gateway/test_shutdown_forensics.py
+++ b/tests/gateway/test_shutdown_forensics.py
@@ -82,6 +82,71 @@ class TestFormatters:
assert decoded["signal"] == "SIGTERM"
assert "weird" in decoded
+ def test_log_line_keeps_parent_identity_without_argv(self):
+ secret = "mongodb+srv://user:[email protected]/db"
+ line = sf.format_context_for_log({
+ "signal": "SIGTERM",
+ "under_systemd": False,
+ "loadavg_1m": 0.25,
+ "parent": {
+ "pid": 42,
+ "name": "systemd",
+ "cmdline": f"docker exec -e LINEAR_API_KEY={secret} myimage",
+ },
+ })
+ assert secret not in line
+ assert "parent_cmdline" not in line
+ assert "hunter2" not in line
+ assert "parent_pid=42" in line
+ assert "parent_name=systemd" in line
+ assert "loadavg_1m=0.25" in line
+
+
+# ---------------------------------------------------------------------------
+# persisted snapshots must never include process argv
+# ---------------------------------------------------------------------------
+
+_ARGV_CANARY = "lin_api_CANARY_SHUTDOWN_FORENSICS_9f3a2c"
+
+
+def _cmdline_bytes_with_canary(path: Path) -> bytes:
+ text = str(path).replace("\\", "/")
+ if text.endswith("/cmdline"):
+ return b"python\x00-c\x00--token=" + _ARGV_CANARY.encode("utf-8")
+ raise OSError("not a cmdline path")
+
+
+class TestArgvFreePersistence:
+
+ def test_proc_summary_omits_cmdline_even_when_proc_has_a_secret(
+ self, monkeypatch
+ ):
+ monkeypatch.setattr(Path, "read_bytes", _cmdline_bytes_with_canary)
+ summary = sf._proc_summary(424242)
+ blob = json.dumps(summary)
+ assert _ARGV_CANARY not in blob
+ assert "cmdline" not in summary
+ assert summary["pid"] == 424242
+
+ def test_snapshot_json_does_not_persist_proc_cmdline(self, monkeypatch):
+ monkeypatch.setattr(Path, "read_bytes", _cmdline_bytes_with_canary)
+ payload = sf.context_as_json(sf.snapshot_shutdown_context(signal.SIGTERM))
+ assert _ARGV_CANARY not in payload
+ decoded = json.loads(payload)
+ for key in ("self", "parent", "tracer"):
+ node = decoded.get(key) or {}
+ assert "cmdline" not in node
+
+ def test_diagnostic_script_requests_comm_not_argv(self):
+ script = sf._async_diagnostic_script("SIGTERM", 1234)
+ assert "auxf" not in script
+ assert "ps aux" not in script
+ assert "-plau" not in script
+ assert "args" not in script
+ assert "comm" in script
+ assert "pstree -pl 1234" in script
+ assert "=== shutdown diagnostic @ SIGTERM ===" in script
+
# ---------------------------------------------------------------------------
# spawn_async_diagnostic
@@ -89,7 +154,7 @@ class TestFormatters:
class TestSpawnAsyncDiagnostic:
# The diagnostic wraps its script in GNU coreutils ``timeout`` and the script
- # body is Linux-only (``ps auxf --sort``, ``/proc/loadavg``, ``dmesg``,
+ # body is Linux-only (``ps -eo ... comm``, ``/proc/loadavg``, ``dmesg``,
# ``pstree``). On hosts without ``timeout`` (macOS) Popen raises and the
# producer returns None by design (fail-soft), so the spawn can only be
# observed on Linux.
@@ -119,6 +184,33 @@ class TestSpawnAsyncDiagnostic:
assert "shutdown diagnostic" in contents
assert "SIGTERM" in contents
+ @pytest.mark.linux_only
+ def test_listing_commands_omit_argv_and_create_owner_only_log(
+ self, tmp_path, monkeypatch
+ ):
+ captured: dict = {}
+
+ class _Spawn:
+ def __init__(self, args, **kwargs):
+ captured["args"] = args
+ self.pid = 77
+
+ monkeypatch.setattr(sf.subprocess, "Popen", _Spawn)
+ log_path = tmp_path / "diag.log"
+ log_path.write_text("prior\n", encoding="utf-8")
+ os.chmod(log_path, 0o644)
+ pid = sf.spawn_async_diagnostic(log_path, "SIGTERM")
+ assert pid == 77
+ argv = captured["args"]
+ assert isinstance(argv, (list, tuple))
+ joined = " ".join(str(part) for part in argv)
+ assert "auxf" not in joined
+ assert "ps aux" not in joined
+ assert "-plau" not in joined
+ assert "comm" in joined
+ assert "pstree" in joined
+ assert (log_path.stat().st_mode & 0o777) == 0o600
+
# ---------------------------------------------------------------------------
# parse_systemd_duration_to_us