From be92bb24936a48867af7ea7a1824eb97a2a85ed4 Mon Sep 17 00:00:00 2001 From: patrick Date: Thu, 5 Mar 2026 20:49:37 -0500 Subject: [PATCH] feat(agent): add --doctor preflight self-test mode with structured checks --- README.md | 7 ++ agent.py | 27 ++++++- doctor.py | 164 ++++++++++++++++++++++++++++++++++++++++ tests/test_agent_cli.py | 38 ++++++++++ tests/test_doctor.py | 77 +++++++++++++++++++ 5 files changed, 311 insertions(+), 2 deletions(-) create mode 100644 doctor.py create mode 100644 tests/test_agent_cli.py create mode 100644 tests/test_doctor.py diff --git a/README.md b/README.md index 436baf1..02a42f5 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,13 @@ Supported env overrides: tail -f /root/threat-engine-agent/logs/threat-agent.log ``` +4. Preflight Self-Test: + +```bash +# Run startup diagnostics without entering the main loop +python3 agent.py --doctor +``` + ## 🔍 Troubleshooting If you see a "Heal Loop" in the logs: diff --git a/agent.py b/agent.py index f9e8721..8ec33e6 100644 --- a/agent.py +++ b/agent.py @@ -1,8 +1,31 @@ +import argparse +import sys + +from config import load_runtime_settings +from doctor import run_doctor from healing import execute_heal_and_verify, should_heal from main import main -__all__ = ["main", "should_heal", "execute_heal_and_verify"] +__all__ = ["main", "should_heal", "execute_heal_and_verify", "run_doctor"] + + +def cli(argv=None): + parser = argparse.ArgumentParser(description="Threat Engine Agent") + parser.add_argument( + "--doctor", + action="store_true", + help="Run startup self-tests and exit.", + ) + args = parser.parse_args(argv) + + if args.doctor: + settings = load_runtime_settings() + ok = run_doctor(settings) + return 0 if ok else 1 + + main() + return 0 if __name__ == "__main__": - main() + raise SystemExit(cli(sys.argv[1:])) diff --git a/doctor.py b/doctor.py new file mode 100644 index 0000000..85f09c9 --- /dev/null +++ b/doctor.py @@ -0,0 +1,164 @@ +import json +import os +import tempfile +import subprocess +from dataclasses import dataclass + + +@dataclass(frozen=True) +class CheckResult: + name: str + status: str # PASS | WARN | FAIL + detail: str + + +def _run_cmd(cmd, timeout=20): + return subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + timeout=timeout, + ) + + +def check_runtime_settings(settings): + if settings.check_interval < 1: + return CheckResult( + "runtime_settings", + "FAIL", + f"check_interval must be >= 1 (got {settings.check_interval})", + ) + if settings.check_jitter_pct < 0 or settings.check_jitter_pct > 0.90: + return CheckResult( + "runtime_settings", + "FAIL", + f"check_jitter_pct must be within [0.0, 0.90] (got {settings.check_jitter_pct})", + ) + if not settings.enforcement_targets: + return CheckResult("runtime_settings", "FAIL", "No enforcement targets configured.") + return CheckResult( + "runtime_settings", + "PASS", + ( + f"check_interval={settings.check_interval}s " + f"check_jitter_pct={settings.check_jitter_pct:.2f} " + f"targets={len(settings.enforcement_targets)}" + ), + ) + + +def check_cscli_json(): + try: + res = _run_cmd(["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"]) + payload = json.loads(res.stdout or "[]") + if isinstance(payload, list): + return CheckResult("cscli_json", "PASS", f"Parsed {len(payload)} top-level entries.") + if isinstance(payload, dict): + return CheckResult("cscli_json", "PASS", "Parsed JSON object payload.") + return CheckResult("cscli_json", "FAIL", "Unexpected JSON type from cscli.") + except subprocess.CalledProcessError as e: + stderr = (e.stderr or "").strip() + return CheckResult("cscli_json", "FAIL", f"Command failed: {stderr or e}") + except json.JSONDecodeError as e: + return CheckResult("cscli_json", "FAIL", f"Invalid JSON output: {e}") + except Exception as e: + return CheckResult("cscli_json", "FAIL", f"Unexpected error: {e}") + + +def check_nft_tables(settings): + failures = [] + summaries = [] + for family, table in settings.enforcement_targets: + try: + res = _run_cmd(["/usr/sbin/nft", "-j", "list", "table", family, table]) + data = json.loads(res.stdout or "{}") + set_count = sum( + 1 for item in data.get("nftables", []) if isinstance(item.get("set"), dict) + ) + summaries.append(f"{family} {table} ({set_count} sets)") + except Exception as e: + failures.append(f"{family} {table}: {e}") + + if failures: + return CheckResult("nft_tables", "FAIL", "; ".join(failures)) + return CheckResult("nft_tables", "PASS", ", ".join(summaries)) + + +def check_state_paths(settings): + state_dir = os.path.dirname(os.path.abspath(settings.state_file)) + history_file = os.path.splitext(settings.state_file)[0] + ".history" + history_dir = os.path.dirname(os.path.abspath(history_file)) + try: + os.makedirs(state_dir, exist_ok=True) + os.makedirs(history_dir, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=state_dir, prefix="doctor-", delete=True): + pass + return CheckResult("state_paths", "PASS", f"Writable: {state_dir}") + except Exception as e: + return CheckResult("state_paths", "FAIL", f"Path check failed: {e}") + + +def check_systemctl_restart_capability(): + if os.geteuid() != 0: + return CheckResult( + "systemctl_restart_capability", + "WARN", + "Not running as root; bouncer restart may fail.", + ) + try: + res = _run_cmd( + [ + "systemctl", + "show", + "crowdsec-firewall-bouncer", + "--property=LoadState", + "--property=CanStart", + "--value", + ] + ) + lines = [line.strip() for line in (res.stdout or "").splitlines() if line.strip()] + load_state = lines[0] if len(lines) >= 1 else "" + can_start = lines[1] if len(lines) >= 2 else "" + if load_state == "not-found": + return CheckResult( + "systemctl_restart_capability", + "FAIL", + "crowdsec-firewall-bouncer unit not found.", + ) + if can_start.lower() == "no": + return CheckResult( + "systemctl_restart_capability", + "FAIL", + "systemd reports CanStart=no for crowdsec-firewall-bouncer.", + ) + return CheckResult( + "systemctl_restart_capability", + "PASS", + f"LoadState={load_state or 'unknown'} CanStart={can_start or 'unknown'}", + ) + except Exception as e: + return CheckResult( + "systemctl_restart_capability", + "WARN", + f"Could not verify via systemctl: {e}", + ) + + +def run_doctor(settings, output=print): + checks = [ + check_runtime_settings(settings), + check_cscli_json(), + check_nft_tables(settings), + check_state_paths(settings), + check_systemctl_restart_capability(), + ] + + output("Threat Engine Agent doctor results:") + for item in checks: + output(f"[{item.status}] {item.name}: {item.detail}") + + failed = [item for item in checks if item.status == "FAIL"] + warned = [item for item in checks if item.status == "WARN"] + output(f"Summary: {len(failed)} failed, {len(warned)} warnings, {len(checks)} total.") + return len(failed) == 0 diff --git a/tests/test_agent_cli.py b/tests/test_agent_cli.py new file mode 100644 index 0000000..2e898da --- /dev/null +++ b/tests/test_agent_cli.py @@ -0,0 +1,38 @@ +import unittest +from unittest.mock import patch + +from config import RuntimeSettings +from agent import cli + + +def _settings(): + return RuntimeSettings( + node_name="n1", + log_path="/tmp/threat-agent.log", + state_file="/tmp/threat-agent-state.json", + check_interval=600, + check_jitter_pct=0.10, + heal_verify_delay=5, + heal_min_interval=900, + enforcement_targets=(("ip", "crowdsec"),), + enforcement_sets=(), + config_path="config.yaml", + ) + + +class AgentCliTests(unittest.TestCase): + @patch("agent.load_runtime_settings", return_value=_settings()) + @patch("agent.run_doctor", return_value=True) + def test_cli_doctor_returns_zero_on_success(self, _run_doctor, _settings_mock): + code = cli(["--doctor"]) + self.assertEqual(0, code) + + @patch("agent.main") + def test_cli_without_doctor_runs_main(self, main_mock): + code = cli([]) + self.assertEqual(0, code) + main_mock.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_doctor.py b/tests/test_doctor.py new file mode 100644 index 0000000..92ceeaf --- /dev/null +++ b/tests/test_doctor.py @@ -0,0 +1,77 @@ +import subprocess +import unittest +from unittest.mock import patch + +from config import RuntimeSettings +from doctor import ( + CheckResult, + check_cscli_json, + check_systemctl_restart_capability, + run_doctor, +) + + +def _settings(): + return RuntimeSettings( + node_name="n1", + log_path="/tmp/threat-agent.log", + state_file="/tmp/threat-agent-state.json", + check_interval=600, + check_jitter_pct=0.10, + heal_verify_delay=5, + heal_min_interval=900, + enforcement_targets=(("ip", "crowdsec"),), + enforcement_sets=(), + config_path="config.yaml", + ) + + +class DoctorTests(unittest.TestCase): + @patch("doctor._run_cmd") + def test_check_cscli_json_fail_on_invalid_json(self, run_cmd_mock): + run_cmd_mock.return_value = subprocess.CompletedProcess( + args=[], + returncode=0, + stdout="not-json", + ) + + result = check_cscli_json() + + self.assertEqual("FAIL", result.status) + self.assertIn("Invalid JSON", result.detail) + + @patch("doctor.os.geteuid", return_value=1000) + def test_check_systemctl_restart_capability_warns_when_not_root(self, _geteuid): + result = check_systemctl_restart_capability() + + self.assertEqual("WARN", result.status) + self.assertIn("Not running as root", result.detail) + + @patch("doctor.check_systemctl_restart_capability") + @patch("doctor.check_state_paths") + @patch("doctor.check_nft_tables") + @patch("doctor.check_cscli_json") + @patch("doctor.check_runtime_settings") + def test_run_doctor_returns_false_when_any_fail( + self, + check_runtime_mock, + check_cscli_mock, + check_nft_mock, + check_state_mock, + check_systemctl_mock, + ): + check_runtime_mock.return_value = CheckResult("runtime", "PASS", "ok") + check_cscli_mock.return_value = CheckResult("cscli", "FAIL", "bad") + check_nft_mock.return_value = CheckResult("nft", "PASS", "ok") + check_state_mock.return_value = CheckResult("state", "PASS", "ok") + check_systemctl_mock.return_value = CheckResult("systemctl", "WARN", "warn") + + lines = [] + ok = run_doctor(_settings(), output=lines.append) + + self.assertFalse(ok) + self.assertTrue(any("Summary:" in line for line in lines)) + + +if __name__ == "__main__": + unittest.main()