diff --git a/.env.example b/.env.example index 2c545dc..5fa2ad2 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,7 @@ BOUNCER_KEY=example SERVER_NAME=Name CHECK_INTERVAL=600 +CHECK_JITTER_PCT=0.10 HEAL_VERIFY_DELAY=5 HEAL_MIN_INTERVAL=900 LOG_PATH=/root/threat-engine-agent/logs/threat-agent.log diff --git a/README.md b/README.md index 599f544..436baf1 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ The standard `crowdsec-firewall-bouncer` can occasionally experience "ghost" des ### The Orchestrator (`main.py`) - Runs the reconcile loop (default `600s` interval). +- Applies bounded random check jitter (default `10%`) to avoid synchronized polling across nodes. - Triggers heal when any drift is detected. - Applies flap suppression using drift fingerprint, not raw kernel count. - Performs post-heal verification after a short delay (default `5s`). @@ -71,6 +72,7 @@ sudo systemctl enable --now threat-agent Supported env overrides: - `SERVER_NAME` - `CHECK_INTERVAL` +- `CHECK_JITTER_PCT` - `HEAL_VERIFY_DELAY` - `HEAL_MIN_INTERVAL` - `LOG_PATH` diff --git a/config.py b/config.py index 11196d9..9e168c5 100644 --- a/config.py +++ b/config.py @@ -5,6 +5,7 @@ from dataclasses import dataclass DEFAULT_LOG_PATH = "/root/threat-engine-agent/logs/threat-agent.log" DEFAULT_STATE_FILE = "/root/threat-engine-agent/threat-agent-state.json" DEFAULT_CHECK_INTERVAL = 600 +DEFAULT_CHECK_JITTER_PCT = 0.10 DEFAULT_HEAL_VERIFY_DELAY = 5 DEFAULT_HEAL_MIN_INTERVAL = 900 DEFAULT_CONFIG_PATH = "config.yaml" @@ -18,6 +19,7 @@ class RuntimeSettings: log_path: str state_file: str check_interval: int + check_jitter_pct: float heal_verify_delay: int heal_min_interval: int enforcement_targets: tuple[tuple[str, str], ...] @@ -136,6 +138,13 @@ def as_int(value, default): return default +def as_float(value, default): + try: + return float(value) + except (TypeError, ValueError): + return default + + def _as_string_list(value): if isinstance(value, list): return [str(item).strip() for item in value if str(item).strip()] @@ -211,6 +220,11 @@ def load_runtime_settings(): os.getenv("CHECK_INTERVAL", cfg_get(config, "agent", "check_interval")), DEFAULT_CHECK_INTERVAL, ) + check_jitter_pct = as_float( + os.getenv("CHECK_JITTER_PCT", cfg_get(config, "agent", "check_jitter_pct")), + DEFAULT_CHECK_JITTER_PCT, + ) + check_jitter_pct = min(max(check_jitter_pct, 0.0), 0.90) heal_verify_delay = as_int( os.getenv( "HEAL_VERIFY_DELAY", @@ -233,6 +247,7 @@ def load_runtime_settings(): log_path=log_path, state_file=state_file, check_interval=check_interval, + check_jitter_pct=check_jitter_pct, heal_verify_delay=heal_verify_delay, heal_min_interval=heal_min_interval, enforcement_targets=enforcement_targets, diff --git a/config.yaml b/config.yaml index d569b89..07fdcaa 100644 --- a/config.yaml +++ b/config.yaml @@ -1,6 +1,7 @@ agent: node_name: "zephyrus" check_interval: 600 # 10 minutes + check_jitter_pct: 0.10 heal_verify_delay: 5 heal_min_interval: 900 log_path: "/root/threat-engine-agent/logs/threat-agent.log" diff --git a/main.py b/main.py index 6479167..a3e4548 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,5 @@ import logging +import random import signal import threading @@ -14,6 +15,15 @@ from healing import execute_heal_and_verify, should_heal from reporter import LocalStateReporter +def compute_sleep_interval(base_interval, jitter_pct): + base = max(1.0, float(base_interval)) + jitter = min(max(float(jitter_pct), 0.0), 0.90) + if jitter == 0: + return base + factor = 1.0 + random.uniform(-jitter, jitter) + return max(1.0, base * factor) + + def main(): """ The Orchestrator: Links Audit findings to the State Reporter. @@ -45,7 +55,8 @@ def main(): logging.info( f"Threat Engine Agent initialized on {settings.node_name}. " f"config_path={settings.config_path} " - f"log_path={settings.log_path} state_file={settings.state_file}" + f"log_path={settings.log_path} state_file={settings.state_file} " + f"check_jitter_pct={settings.check_jitter_pct:.2f}" ) while not stop_event.is_set(): @@ -108,8 +119,12 @@ def main(): else: logging.info(f"Audit Success: {count} IPs in sync.") - print(f"[*] Sleeping for {settings.check_interval} seconds...") - stop_event.wait(settings.check_interval) + sleep_seconds = compute_sleep_interval( + settings.check_interval, + settings.check_jitter_pct, + ) + print(f"[*] Sleeping for {sleep_seconds:.1f} seconds...") + stop_event.wait(sleep_seconds) except KeyboardInterrupt: logging.info("Agent shutting down manually.") diff --git a/tests/test_config.py b/tests/test_config.py index 792ab86..9bc1b1f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -50,6 +50,19 @@ class RuntimeSettingsEnforcementTests(unittest.TestCase): ) self.assertEqual((), settings.enforcement_sets) + @patch("config.load_config") + def test_check_jitter_pct_loaded_and_clamped(self, load_config_mock): + load_config_mock.return_value = { + "agent": { + "check_jitter_pct": 1.5, + } + } + + with patch.dict(os.environ, {}, clear=True): + settings = load_runtime_settings() + + self.assertEqual(0.90, settings.check_jitter_pct) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..788e704 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,22 @@ +import unittest +from unittest.mock import patch + +from main import compute_sleep_interval + + +class MainSleepIntervalTests(unittest.TestCase): + @patch("main.random.uniform", return_value=0.0) + def test_compute_sleep_interval_no_jitter(self, _uniform): + self.assertEqual(600.0, compute_sleep_interval(600, 0.0)) + + @patch("main.random.uniform", return_value=0.10) + def test_compute_sleep_interval_applies_positive_jitter(self, _uniform): + self.assertEqual(660.0, compute_sleep_interval(600, 0.10)) + + @patch("main.random.uniform", return_value=-0.90) + def test_compute_sleep_interval_enforces_minimum_sleep(self, _uniform): + self.assertEqual(1.0, compute_sleep_interval(1, 0.90)) + + +if __name__ == "__main__": + unittest.main()