feat(config): wire runtime settings from env/config with sane defaults
This commit is contained in:
1 parent
6dac06c117
commit
461512f20a
6 files changed
+195
-20
No files matched your search
@@ -8,11 +8,118 @@ from dotenv import load_dotenv
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
filename='/root/threat-engine-agent/logs/threat-agent.log'
|
||||
)
|
||||
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_HEAL_VERIFY_DELAY = 5
|
||||
DEFAULT_HEAL_MIN_INTERVAL = 900
|
||||
|
||||
|
||||
def _parse_scalar(value):
|
||||
value = value.strip()
|
||||
if value.startswith(("'", '"')) and value.endswith(("'", '"')) and len(value) >= 2:
|
||||
return value[1:-1]
|
||||
if value.lower() == "true":
|
||||
return True
|
||||
if value.lower() == "false":
|
||||
return False
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return value
|
||||
|
||||
|
||||
def _load_config_minimal(config_path):
|
||||
"""
|
||||
Minimal parser for simple two-level YAML mappings.
|
||||
Supports the current config.yaml structure without external deps.
|
||||
"""
|
||||
config = {}
|
||||
current_section = None
|
||||
|
||||
with open(config_path, "r") as f:
|
||||
for raw_line in f:
|
||||
line = raw_line.split("#", 1)[0].rstrip()
|
||||
if not line.strip():
|
||||
continue
|
||||
|
||||
if not line.startswith(" "):
|
||||
if ":" not in line:
|
||||
continue
|
||||
key, value = line.split(":", 1)
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
if value == "":
|
||||
config[key] = {}
|
||||
current_section = key
|
||||
else:
|
||||
config[key] = _parse_scalar(value)
|
||||
current_section = None
|
||||
continue
|
||||
|
||||
if current_section is None:
|
||||
continue
|
||||
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("- "):
|
||||
continue
|
||||
if ":" not in stripped:
|
||||
continue
|
||||
key, value = stripped.split(":", 1)
|
||||
config[current_section][key.strip()] = _parse_scalar(value)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def _load_config(config_path):
|
||||
"""
|
||||
Loads YAML config when available. Falls back to empty config.
|
||||
"""
|
||||
try:
|
||||
import yaml # Local import so runtime still works without PyYAML
|
||||
except ImportError:
|
||||
try:
|
||||
return _load_config_minimal(config_path)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except Exception as e:
|
||||
logging.warning(f"Failed to read config file '{config_path}': {e}")
|
||||
return {}
|
||||
|
||||
try:
|
||||
with open(config_path, "r") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except Exception as e:
|
||||
logging.warning(f"Failed to read config file '{config_path}': {e}")
|
||||
return {}
|
||||
|
||||
|
||||
def _cfg_get(config, *keys, default=None):
|
||||
cur = config
|
||||
for key in keys:
|
||||
if not isinstance(cur, dict):
|
||||
return default
|
||||
cur = cur.get(key)
|
||||
return default if cur is None else cur
|
||||
|
||||
|
||||
def _as_int(value, default):
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _setup_logging(log_path):
|
||||
os.makedirs(os.path.dirname(os.path.abspath(log_path)), exist_ok=True)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
filename=log_path,
|
||||
force=True,
|
||||
)
|
||||
|
||||
################
|
||||
#### Helpers ###
|
||||
@@ -67,16 +174,50 @@ def main():
|
||||
The Orchestrator: Links Audit findings to the State Reporter.
|
||||
"""
|
||||
load_dotenv()
|
||||
config_path = os.getenv("THREAT_AGENT_CONFIG", "config.yaml")
|
||||
config = _load_config(config_path)
|
||||
|
||||
node_name = os.getenv(
|
||||
"SERVER_NAME",
|
||||
_cfg_get(config, "agent", "node_name", default="Unknown Node"),
|
||||
)
|
||||
log_path = os.getenv(
|
||||
"LOG_PATH",
|
||||
_cfg_get(config, "agent", "log_path", default=DEFAULT_LOG_PATH),
|
||||
)
|
||||
state_file = os.getenv(
|
||||
"STATE_FILE",
|
||||
_cfg_get(config, "agent", "state_file", default=DEFAULT_STATE_FILE),
|
||||
)
|
||||
|
||||
check_interval = _as_int(
|
||||
os.getenv("CHECK_INTERVAL", _cfg_get(config, "agent", "check_interval")),
|
||||
DEFAULT_CHECK_INTERVAL,
|
||||
)
|
||||
heal_verify_delay = _as_int(
|
||||
os.getenv(
|
||||
"HEAL_VERIFY_DELAY",
|
||||
_cfg_get(config, "agent", "heal_verify_delay"),
|
||||
),
|
||||
DEFAULT_HEAL_VERIFY_DELAY,
|
||||
)
|
||||
heal_min_interval = _as_int(
|
||||
os.getenv(
|
||||
"HEAL_MIN_INTERVAL",
|
||||
_cfg_get(config, "agent", "heal_min_interval"),
|
||||
),
|
||||
DEFAULT_HEAL_MIN_INTERVAL,
|
||||
)
|
||||
|
||||
_setup_logging(log_path)
|
||||
auditor = FirewallAuditor()
|
||||
reporter = LocalStateReporter()
|
||||
reporter = LocalStateReporter(state_file=state_file, node_name=node_name)
|
||||
|
||||
node_name = os.getenv("SERVER_NAME", "Unknown Node")
|
||||
|
||||
CHECK_INTERVAL = 600
|
||||
HEAL_VERIFY_DELAY = 5
|
||||
print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s")
|
||||
logging.info(f"Threat Engine Agent initialized on {node_name}.")
|
||||
print(f"[*] Agent started. Check interval: {check_interval}s")
|
||||
logging.info(
|
||||
f"Threat Engine Agent initialized on {node_name}. "
|
||||
f"config_path={config_path} log_path={log_path} state_file={state_file}"
|
||||
)
|
||||
|
||||
while True:
|
||||
try:
|
||||
@@ -102,7 +243,11 @@ def main():
|
||||
|
||||
history_file = reporter.state_file.replace(".json", ".history")
|
||||
|
||||
if should_heal(history_file, drift.get("fingerprint", "")):
|
||||
if should_heal(
|
||||
history_file,
|
||||
drift.get("fingerprint", ""),
|
||||
min_interval=heal_min_interval,
|
||||
):
|
||||
logging.warning("Healing approved.")
|
||||
heal_ok = auditor.heal()
|
||||
heal_result = "restart_failed"
|
||||
@@ -116,10 +261,10 @@ def main():
|
||||
|
||||
if heal_ok:
|
||||
logging.info(
|
||||
f"Post-heal verification in {HEAL_VERIFY_DELAY}s "
|
||||
f"Post-heal verification in {heal_verify_delay}s "
|
||||
f"(pre_fingerprint={drift.get('fingerprint', '')})."
|
||||
)
|
||||
time.sleep(HEAL_VERIFY_DELAY)
|
||||
time.sleep(heal_verify_delay)
|
||||
post_is_synced, post_count, post_drift = auditor.reconcile()
|
||||
heal_result = "success" if post_is_synced else "failed"
|
||||
verify_error = None if post_is_synced else "Post-heal verification failed"
|
||||
@@ -155,8 +300,8 @@ def main():
|
||||
else:
|
||||
logging.info(f"Audit Success: {count} IPs in sync.")
|
||||
|
||||
print(f"[*] Sleeping for {CHECK_INTERVAL} seconds...")
|
||||
time.sleep(CHECK_INTERVAL)
|
||||
print(f"[*] Sleeping for {check_interval} seconds...")
|
||||
time.sleep(check_interval)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.info("Agent shutting down manually.")
|
||||
|
||||
Reference in new issue
Block a user