ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(engine): hoist module_id assignment before finding validation
Mafifrizie8c9ab2338ea
diff --git a/ares/core/engine.py b/ares/core/engine.pyindex f4c9b06..6dae395 100644--- a/ares/core/engine.py+++ b/ares/core/engine.py@@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutinefrom ares.core.logger import get_logger-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom ares.core.campaign import Campaign, Findingfrom ares.core.config import AresSettings, get_settingsfrom ares.core.context import ExecutionContext@@ -301,6 +301,7 @@ class EngineModuleResult(BaseModel):outcome: str = ""outcome_message: str = ""operator_next_steps: list[str] = []+ filtered_findings: dict[str, Any] = Field(default_factory=lambda: {"count": 0, "reasons": {}})def model_post_init(self, __context: Any) -> None:self.error = redact_error_message(self.error)@@ -405,6 +406,32 @@ def _fire_and_log(coro, label: str = "background_task") -> None:_aio.create_task(_wrapper())+def _categorize_rejection_reason(v_res: Any, finding: Finding) -> str:+ """Categorize why a finding was rejected by the validator."""+ explicit_reason = getattr(v_res, "reason", None)+ if explicit_reason and isinstance(explicit_reason, str):+ return explicit_reason+ if hasattr(v_res, "notes") and v_res.notes:+ for n in v_res.notes:+ if n in ("no_evidence", "below_confidence_threshold", "validator_rejected"):+ return n+ ev = finding.evidence or {}+ if not ev or not any(bool(v) for v in ev.values()):+ return "no_evidence"+ if hasattr(v_res, "stage_results") and isinstance(v_res.stage_results, dict):+ for _, _, note in v_res.stage_results.values():+ note_lower = (note or "").lower()+ if (+ "no captured hash" in note_lower+ or "no evidence" in note_lower+ or "missing" in note_lower+ ):+ return "no_evidence"+ if getattr(v_res, "confidence", 0.0) < 0.4:+ return "below_confidence_threshold"+ return "validator_rejected"++class AresEngine:"""ARES Async Engine.@@ -777,6 +804,8 @@ class AresEngine:# Validatevalidation_results: list[ValidationResult] = []if not skip_validation:+ for f in findings:+ f.module_id = f.module_id or module_id# Run all validations in parallel toovalidation_results = list(await asyncio.gather(*[self.validator.validate(f, raw) for f in findings])@@ -786,6 +815,8 @@ class AresEngine:# mutation, or artifact normalization. Those effects are released only# after the coordinator durably commits the terminal attempt.confirmed: list[Finding] = []+ filtered_count = 0+ filtered_reasons: dict[str, int] = {}from ares.core.cvss import enrich_finding_with_cvssfrom ares.core.tracing import get_current_trace_id@@ -804,13 +835,16 @@ class AresEngine:else:f.false_positive = Truef.validated = False+ reason = _categorize_rejection_reason(v_res, f)+ filtered_count += 1+ filtered_reasons[reason] = filtered_reasons.get(reason, 0) + 1logger.warning("finding_rejected_by_validator",finding_id=f.id,title=f.title,severity=str(f.severity),confidence=v_res.confidence,- reason=getattr(v_res, "reason", None) or (v_res.notes[0] if v_res.notes else "below_confidence_threshold"),+ reason=reason,)else:if not f.false_positive:@@ -837,6 +871,7 @@ class AresEngine:validation_results=validation_results,raw_output=raw,duration_ms=duration_ms,+ filtered_findings={"count": filtered_count, "reasons": filtered_reasons},)# ── Parallel plan ──────────────────────────────────────────────────────diff --git a/tests/unit/test_engine.py b/tests/unit/test_engine.pyindex e617885..9970090 100644--- a/tests/unit/test_engine.py+++ b/tests/unit/test_engine.py@@ -9,6 +9,7 @@ not individual module behavior (which is tested in test_modules.py).from __future__ import annotationsimport asyncio+from contextlib import contextmanagerfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import patch, AsyncMock@@ -863,10 +864,78 @@ class TestAsyncEngine:# ── Helpers ───────────────────────────────────────────────────────────────────-from contextlib import contextmanager@contextmanagerdef _noop_ctx():"""No-op context manager for optional patches."""yield+++# ── Filtered Findings Indicator & Reason Categorization Tests ─────────────────+++def test_categorize_rejection_reason_all_branches():+ from ares.core.campaign import Finding, Severity+ from ares.core.engine import _categorize_rejection_reason+ from ares.core.validator import ValidationResult++ finding = Finding(title="Test", description="Desc", severity=Severity.LOW)++ # 1. Validator result with explicit .reason+ v_explicit = ValidationResult(finding_id="f1", passed=False, confidence=0.2)+ v_explicit.reason = "custom_reason"+ assert _categorize_rejection_reason(v_explicit, finding) == "custom_reason"++ # 2. Validator result with .notes containing a known label+ v_notes = ValidationResult(+ finding_id="f2",+ passed=False,+ confidence=0.1,+ notes=["below_confidence_threshold"],+ )+ assert _categorize_rejection_reason(v_notes, finding) == "below_confidence_threshold"++ # 3. Empty evidence+ v_empty_ev = ValidationResult(finding_id="f3", passed=False, confidence=0.0)+ finding_empty = Finding(title="No Ev", description="None", severity=Severity.LOW, evidence={})+ assert _categorize_rejection_reason(v_empty_ev, finding_empty) == "no_evidence"++ # 4. stage_results text containing "no captured hash"+ v_stage = ValidationResult(+ finding_id="f4",+ passed=False,+ confidence=0.0,+ stage_results={"check1": (False, 0.0, "No captured hash evidence found")},+ )+ finding_with_ev = Finding(+ title="With Ev",+ description="Has",+ severity=Severity.LOW,+ evidence={"target": "dc"},+ )+ assert _categorize_rejection_reason(v_stage, finding_with_ev) == "no_evidence"++ # 5. Low-confidence result with evidence present+ v_low = ValidationResult(+ finding_id="f5",+ passed=False,+ confidence=0.2,+ stage_results={"check1": (False, 0.2, "Insufficient lateral execution evidence")},+ )+ assert _categorize_rejection_reason(v_low, finding_with_ev) == "below_confidence_threshold"+++def test_engine_module_result_default_filtered_findings_serialization():+ from ares.core.engine import EngineModuleResult, ModuleStatus++ res = EngineModuleResult(module_id="test.module", status=ModuleStatus.DONE)+ assert res.filtered_findings == {"count": 0, "reasons": {}}++ dumped = res.model_dump()+ assert "filtered_findings" in dumped+ assert dumped["filtered_findings"] == {"count": 0, "reasons": {}}++ json_dumped = res.model_dump(mode="json")+ assert json_dumped["filtered_findings"] == {"count": 0, "reasons": {}}+