feat(config): validate runtime settings at boot and fail fast on critical errors

This commit is contained in:
patrick committed 2026-03-05 20:55:00 -05:00
1 parent be92bb2493
commit 7f323ed78b
4 files changed
+134 -2

No files matched your search

+1
View File
@@ -22,6 +22,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.
- Validates effective runtime config at boot and fails fast on invalid critical settings.
- 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`).
+66
View File
@@ -27,6 +27,12 @@ class RuntimeSettings:
config_path: str
@dataclass(frozen=True)
class ValidationIssue:
level: str # ERROR | WARN
message: str
def _parse_scalar(value):
value = value.strip()
if value.startswith(("'", '"')) and value.endswith(("'", '"')) and len(value) >= 2:
@@ -254,3 +260,63 @@ def load_runtime_settings():
enforcement_sets=enforcement_sets,
config_path=config_path,
)
def validate_runtime_settings(settings):
issues = []
if settings.check_interval < 1:
issues.append(
ValidationIssue(
"ERROR",
f"check_interval must be >= 1 (got {settings.check_interval})",
)
)
if settings.heal_verify_delay < 0:
issues.append(
ValidationIssue(
"ERROR",
f"heal_verify_delay must be >= 0 (got {settings.heal_verify_delay})",
)
)
if settings.heal_min_interval < 0:
issues.append(
ValidationIssue(
"ERROR",
f"heal_min_interval must be >= 0 (got {settings.heal_min_interval})",
)
)
if not settings.enforcement_targets:
issues.append(
ValidationIssue("ERROR", "At least one enforcement target is required.")
)
for target in settings.enforcement_targets:
if (
not isinstance(target, tuple)
or len(target) != 2
or not all(isinstance(part, str) and part.strip() for part in target)
):
issues.append(
ValidationIssue(
"ERROR",
f"Malformed enforcement target: {target!r}",
)
)
if settings.check_jitter_pct < 0.0 or settings.check_jitter_pct > 0.90:
issues.append(
ValidationIssue(
"WARN",
f"check_jitter_pct should be between 0.0 and 0.90 (got {settings.check_jitter_pct})",
)
)
if not os.path.isabs(settings.state_file):
issues.append(
ValidationIssue(
"WARN",
f"state_file is not absolute: {settings.state_file}",
)
)
return issues
+28 -1
View File
@@ -10,7 +10,7 @@ except ImportError:
return None
from auditor import FirewallAuditor
from config import load_runtime_settings, setup_logging
from config import load_runtime_settings, setup_logging, validate_runtime_settings
from healing import execute_heal_and_verify, should_heal
from reporter import LocalStateReporter
@@ -32,6 +32,33 @@ def main():
settings = load_runtime_settings()
setup_logging(settings.log_path)
issues = validate_runtime_settings(settings)
for issue in issues:
if issue.level == "ERROR":
logging.error(f"Config validation: {issue.message}")
else:
logging.warning(f"Config validation: {issue.message}")
if any(issue.level == "ERROR" for issue in issues):
raise RuntimeError("Configuration validation failed; refusing to start.")
targets_desc = ", ".join(
f"{family}:{table}" for family, table in settings.enforcement_targets
)
sets_mode = "explicit" if settings.enforcement_sets else "auto(*-cscli)"
sets_desc = ", ".join(settings.enforcement_sets) if settings.enforcement_sets else "(none)"
logging.info(
"Effective config: "
f"node={settings.node_name} "
f"check_interval={settings.check_interval}s "
f"check_jitter_pct={settings.check_jitter_pct:.2f} "
f"heal_verify_delay={settings.heal_verify_delay}s "
f"heal_min_interval={settings.heal_min_interval}s "
f"state_file={settings.state_file} "
f"targets=[{targets_desc}] "
f"sets_mode={sets_mode} sets=[{sets_desc}]"
)
auditor = FirewallAuditor(
targets=settings.enforcement_targets,
managed_sets=settings.enforcement_sets,
+39 -1
View File
@@ -2,7 +2,7 @@ import os
import unittest
from unittest.mock import patch
from config import load_runtime_settings
from config import RuntimeSettings, load_runtime_settings, validate_runtime_settings
class RuntimeSettingsEnforcementTests(unittest.TestCase):
@@ -63,6 +63,44 @@ class RuntimeSettingsEnforcementTests(unittest.TestCase):
self.assertEqual(0.90, settings.check_jitter_pct)
def test_validate_runtime_settings_reports_errors(self):
settings = RuntimeSettings(
node_name="n1",
log_path="/tmp/agent.log",
state_file="/tmp/state.json",
check_interval=0,
check_jitter_pct=0.10,
heal_verify_delay=-1,
heal_min_interval=-2,
enforcement_targets=(),
enforcement_sets=(),
config_path="config.yaml",
)
issues = validate_runtime_settings(settings)
errors = [issue for issue in issues if issue.level == "ERROR"]
self.assertGreaterEqual(len(errors), 4)
def test_validate_runtime_settings_reports_warn_for_relative_state_file(self):
settings = RuntimeSettings(
node_name="n1",
log_path="/tmp/agent.log",
state_file="relative-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",
)
issues = validate_runtime_settings(settings)
warns = [issue.message for issue in issues if issue.level == "WARN"]
self.assertTrue(any("state_file is not absolute" in msg for msg in warns))
if __name__ == "__main__":
unittest.main()