Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(triage): add benign_true_positive disposition (#526) (#531)
Beenu Arora5d8efde8c0f6
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex d1d14222d..146bc13d7 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -13760,8 +13760,8 @@ components:corrected_verdict:type: stringtitle: Corrected Verdict- description: 'Analyst''s verdict: true_positive | false_positive | benign- | escalate'+ description: 'Analyst''s verdict: true_positive | benign_true_positive |+ false_positive | benign | escalate'reason:anyOf:- type: string@@ -21364,6 +21364,10 @@ components:true_positive_corrections:type: integertitle: True Positive Corrections+ benign_true_positive_corrections:+ type: integer+ title: Benign True Positive Corrections+ default: 0benign_corrections:type: integertitle: Benign Correctionsdiff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.pyindex 9081bb7a1..3f71ac117 100644--- a/services/agents/app/agents/auto_triage_agent.py+++ b/services/agents/app/agents/auto_triage_agent.py@@ -2,9 +2,13 @@Auto-Triage Agent: LLM-based autonomous alert classification.Uses structured LLM reasoning to classify alerts as true_positive,-false_positive, or benign — replacing simple keyword heuristics with-contextual analysis. High-confidence FP/benign verdicts are auto-closed;-uncertain alerts escalate into the full triage → enrichment → investigation+benign_true_positive, false_positive, or benign — replacing simple keyword+heuristics with contextual analysis. The taxonomy separates detection validity+from activity maliciousness so a rule that correctly detects authorized+activity (an approved pen-test, a scheduled scan) is a benign_true_positive,+not a false_positive (see ``app.agents.dispositions``). High-confidence+FP / benign / benign_true_positive verdicts are auto-closed; true_positive and+needs_review escalate into the full triage → enrichment → investigationpipeline.Metrics (module-level counters) are exposed via the /triage/stats API.@@ -20,6 +24,15 @@ from typing import Anyimport structlogfrom langchain_core.messages import HumanMessage, SystemMessage+from app.agents.dispositions import (+ AUTO_CLOSEABLE_DISPOSITIONS,+ BENIGN,+ BENIGN_TRUE_POSITIVE,+ FALSE_POSITIVE,+ LLM_VERDICTS,+ TRUE_POSITIVE,+ normalize_disposition,+)from app.investigator.prompt_sanitizer import sanitize_text, wrap_untrustedfrom app.llm import safe_ainvokefrom app.llm.factory import make_chat_model@@ -37,37 +50,51 @@ _metrics: dict[str, Any] = {"confidence_sum": 0.0,"fp_count": 0,"benign_count": 0,+ "btp_count": 0,"tp_count": 0,}_SYSTEM_PROMPT = """\You are the Auto-Triage Agent of an AI Security Operations Centre.-Given a security alert (summary + raw payload), classify it into exactly one-of three verdicts:-- • true_positive — the alert describes a genuine security threat that- requires investigation and potential response.- • false_positive — the alert was triggered by benign activity that- superficially resembles a threat (e.g. scheduled vulnerability scans,- authorised pen-tests, known-good software flagged by signature).- • benign — the alert describes real but non-threatening activity that- does not warrant investigation (e.g. informational log, expected- configuration change).+Judge two INDEPENDENT questions, then pick one verdict:+ 1. Detection validity — did the rule correctly detect its intended condition?+ 2. Activity maliciousness — was the detected activity an actual threat?++Classify the alert into exactly one of these verdicts:++ • true_positive — a VALID detection of MALICIOUS or unauthorized activity+ that requires investigation and potential response.+ • benign_true_positive — a VALID detection of AUTHORIZED, expected, or+ otherwise non-malicious activity. The rule fired correctly, but the+ behaviour was sanctioned (e.g. a scheduled vulnerability scan, an approved+ penetration test, sanctioned admin/red-team tooling). This is NOT a false+ positive: the detection was right, so recording it as false_positive would+ unfairly penalize the rule and corrupt its false-positive-rate metric.+ • false_positive — an INVALID or noisy detection: the rule's intended+ condition was not actually present (misfire, bad signature, mis-parsed+ field). Only use this when the detection itself was wrong.+ • benign — real but non-threatening activity that is not a detection-validity+ statement (informational log, expected configuration change).+ • needs_review — insufficient evidence to decide safely; route to a human.You MUST respond with a JSON object and nothing else:{- "verdict": "true_positive" | "false_positive" | "benign",+ "verdict": "true_positive" | "benign_true_positive" | "false_positive" | "benign" | "needs_review","confidence": <float 0.0–1.0>,"rationale": "<2-4 sentence explanation of your reasoning>"}Reasoning guidelines:- Consider the severity, IOC presence, MITRE technique IDs, and alert context.-- Vendor risk_score > 0.7 with critical keywords strongly suggests TP.-- Alerts about scheduled scans, test environments, or known-good hashes lean FP.+- Vendor risk_score > 0.7 with critical keywords strongly suggests true_positive.+- Scheduled scans and authorized penetration tests, when the rule correctly+ detected the behaviour, are benign_true_positive — NOT false_positive.+- Reserve false_positive for cases where the rule misfired or its intended+ detection condition was not actually present.- Informational alerts with no IOCs and low risk lean benign.-- Be conservative: when uncertain, lean toward true_positive to avoid missing threats.+- Be conservative: when uncertain, prefer true_positive or needs_review over+ auto-closing, to avoid missing threats.- confidence should reflect how certain you are, not the severity of the threat."""@@ -78,6 +105,9 @@ def get_metrics() -> dict[str, Any]:total = m["total_processed"]m["auto_resolution_rate"] = m["auto_resolved_count"] / total if total > 0 else 0.0m["fp_rate"] = m["fp_count"] / total if total > 0 else 0.0+ # Benign-true-positive rate is reported independently of fp_rate so a valid+ # detection of authorized activity never looks like a false positive.+ m["btp_rate"] = m.get("btp_count", 0) / total if total > 0 else 0.0m["avg_confidence"] = m["confidence_sum"] / total if total > 0 else 0.0return m@@ -148,9 +178,12 @@ def _parse_llm_response(text: str) -> dict[str, Any]:else:raise- verdict = data.get("verdict", "true_positive")- if verdict not in ("true_positive", "false_positive", "benign"):- verdict = "true_positive"+ # Normalize to the canonical taxonomy (shared with the deterministic+ # fallback). ``benign_true_positive`` is a first-class outcome; an+ # unrecognised verdict fails safe to ``true_positive`` (never auto-closed).+ verdict = normalize_disposition(data.get("verdict"), default=TRUE_POSITIVE)+ if verdict not in LLM_VERDICTS:+ verdict = TRUE_POSITIVEconfidence = float(data.get("confidence", 0.5))confidence = max(0.0, min(1.0, confidence))@@ -204,9 +237,13 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:_metrics["total_processed"] += 1_metrics["confidence_sum"] += confidence- if verdict == "false_positive":+ if verdict == FALSE_POSITIVE:_metrics["fp_count"] += 1- elif verdict == "benign":+ elif verdict == BENIGN_TRUE_POSITIVE:+ # Benign true positive is a VALID detection — tracked separately so it+ # never inflates the false-positive rate (#526).+ _metrics["btp_count"] += 1+ elif verdict == BENIGN:_metrics["benign_count"] += 1else:_metrics["tp_count"] += 1@@ -222,7 +259,9 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:state.add_finding(f"Auto-triage: verdict={verdict}, confidence={confidence:.2f}, latency={elapsed_ms}ms")state.add_finding(f"Auto-triage rationale: {rationale}")- should_auto_close = verdict in ("false_positive", "benign") and confidence >= AUTO_CLOSE_THRESHOLD+ # Auto-close FP / benign / benign_true_positive (no active threat, no+ # response needed); true_positive and needs_review always escalate.+ should_auto_close = verdict in AUTO_CLOSEABLE_DISPOSITIONS and confidence >= AUTO_CLOSE_THRESHOLDif should_auto_close:_metrics["auto_resolved_count"] += 1diff --git a/services/agents/app/agents/dispositions.py b/services/agents/app/agents/dispositions.pynew file mode 100644index 000000000..f7937c3f5--- /dev/null+++ b/services/agents/app/agents/dispositions.py@@ -0,0 +1,112 @@+"""Canonical triage disposition taxonomy + normalization layer (#526).++The auto-triage LLM and the deterministic fallback scorer historically spoke+different dialects (``benign`` / ``false_positive`` vs. ``likely_benign`` /+``needs_review`` / ``confirmed_incident``). This module is the single+normalization layer that reconciles them, and it introduces an explicit+``benign_true_positive`` outcome.++The taxonomy separates two *independent* questions:++* **Detection validity** — did the rule correctly detect its intended+ condition?+* **Activity maliciousness** — was the detected activity an actual threat?++ - ``true_positive`` valid detection of malicious / unauthorized+ activity.+ - ``benign_true_positive`` valid detection of AUTHORIZED, expected, or+ non-malicious activity (an approved penetration+ test, a scheduled vulnerability scan, sanctioned+ admin tooling). The rule was CORRECT, so this must+ NOT be recorded as a false positive — doing so+ corrupts per-rule false-positive-rate metrics and+ unfairly penalizes good detections.+ - ``false_positive`` invalid / noisy detection; the intended condition+ was not actually present.+ - ``benign`` real but non-threatening activity that is not a+ detection-validity statement (informational).+ Retained for backward compatibility — see the+ migration note below.+ - ``needs_review`` insufficient evidence to decide safely; route to a+ human / the full pipeline.+ - ``escalate`` analyst-forced escalation.++Compatibility / migration+--------------------------+Existing ``benign`` records remain valid and are intentionally left untouched:+``benign`` and ``benign_true_positive`` are *distinct* outcomes (the former+makes no claim about detection validity), so no data backfill is required.+Consumers that compute false-positive rate already key on the literal+``false_positive`` string, so ``benign_true_positive`` is naturally excluded+from FP metrics and kept separate on dashboards, filters, and exports.+"""++from __future__ import annotations++TRUE_POSITIVE = "true_positive"+BENIGN_TRUE_POSITIVE = "benign_true_positive"+FALSE_POSITIVE = "false_positive"+BENIGN = "benign"+NEEDS_REVIEW = "needs_review"+ESCALATE = "escalate"++#: Every disposition the platform recognises as canonical.+CANONICAL_DISPOSITIONS: frozenset[str] = frozenset(+ {+ TRUE_POSITIVE,+ BENIGN_TRUE_POSITIVE,+ FALSE_POSITIVE,+ BENIGN,+ NEEDS_REVIEW,+ ESCALATE,+ }+)++#: Verdicts the auto-triage LLM is allowed to emit directly.+LLM_VERDICTS: frozenset[str] = frozenset({TRUE_POSITIVE, BENIGN_TRUE_POSITIVE, FALSE_POSITIVE, BENIGN, NEEDS_REVIEW})++#: Dispositions that indicate the detection itself was INVALID. Used for+#: false-positive-rate / rule-tuning metrics. Deliberately excludes+#: ``benign_true_positive`` (a valid detection) so BTP never inflates FPR.+INVALID_DETECTION_DISPOSITIONS: frozenset[str] = frozenset({FALSE_POSITIVE})++#: Dispositions safe to auto-close without a human — no active threat and no+#: response action required.+AUTO_CLOSEABLE_DISPOSITIONS: frozenset[str] = frozenset({FALSE_POSITIVE, BENIGN, BENIGN_TRUE_POSITIVE})++# Graded / vendor / legacy verdicts → canonical. Keys are compared after+# lower-casing and collapsing separators to ``_``.+_ALIASES: dict[str, str] = {+ # deterministic triage scorer (confidence/scoring.py: score_triage)+ "likely_true_positive": TRUE_POSITIVE,+ "likely_benign": BENIGN,+ # deterministic investigation scorer (confidence/scoring.py: score_investigation)+ "confirmed_incident": TRUE_POSITIVE,+ "probable_incident": TRUE_POSITIVE,+ "needs_human_review": NEEDS_REVIEW,+ "likely_false_positive": FALSE_POSITIVE,+ # common synonyms+ "btp": BENIGN_TRUE_POSITIVE,+ "benign_tp": BENIGN_TRUE_POSITIVE,+ "authorized": BENIGN_TRUE_POSITIVE,+ "tp": TRUE_POSITIVE,+ "fp": FALSE_POSITIVE,+ "true positive": TRUE_POSITIVE,+ "false positive": FALSE_POSITIVE,+ "benign true positive": BENIGN_TRUE_POSITIVE,+}+++def normalize_disposition(value: object, *, default: str = TRUE_POSITIVE) -> str:+ """Map any verdict/disposition string to a canonical disposition.++ Unknown / non-string values fall back to ``default`` (``true_positive`` by+ default so the fail-safe is to *not* silently close an alert). This is the+ consistency layer shared by the LLM path and the deterministic fallback.+ """+ if not isinstance(value, str):+ return default+ key = value.strip().lower().replace("-", "_").replace(" ", "_")+ if key in CANONICAL_DISPOSITIONS:+ return key+ return _ALIASES.get(key, _ALIASES.get(value.strip().lower(), default))diff --git a/services/agents/tests/test_auto_triage_dispositions.py b/services/agents/tests/test_auto_triage_dispositions.pynew file mode 100644index 000000000..76fa38f54--- /dev/null+++ b/services/agents/tests/test_auto_triage_dispositions.py@@ -0,0 +1,137 @@+"""#526 — benign_true_positive disposition in LLM auto-triage.++Covers the four required outcomes (approved pen-test, scheduled scanner,+genuine false positive, malicious true positive), the parser/normalization+layer, and the invariant that a benign true positive is never counted as a+false positive.+"""++from __future__ import annotations++import json+from types import SimpleNamespace+from uuid import uuid4++import pytest+from app.agents import auto_triage_agent as ata+from app.agents.dispositions import (+ AUTO_CLOSEABLE_DISPOSITIONS,+ BENIGN,+ BENIGN_TRUE_POSITIVE,+ FALSE_POSITIVE,+ INVALID_DETECTION_DISPOSITIONS,+ NEEDS_REVIEW,+ TRUE_POSITIVE,+ normalize_disposition,+)+from app.models.state import AgentStatus, InvestigationState+++def _state(summary: str, raw: dict) -> InvestigationState:+ return InvestigationState(+ incident_id=uuid4(),+ tenant_id=uuid4(),+ alert_summary=summary,+ raw_alert=raw,+ status=AgentStatus.PENDING,+ )+++def _patch_llm(monkeypatch, verdict: str, confidence: float, rationale: str = "because") -> None:+ payload = json.dumps({"verdict": verdict, "confidence": confidence, "rationale": rationale})++ async def _fake_ainvoke(_llm, _messages):+ return SimpleNamespace(content=payload)++ monkeypatch.setattr(ata, "make_chat_model", lambda *a, **k: object())+ monkeypatch.setattr(ata, "safe_ainvoke", _fake_ainvoke)+++# --- parser + normalization layer ------------------------------------------+++def test_parser_accepts_benign_true_positive():+ out = ata._parse_llm_response('{"verdict": "benign_true_positive", "confidence": 0.9, "rationale": "approved pentest"}')+ assert out["verdict"] == BENIGN_TRUE_POSITIVE+++def test_parser_normalizes_synonym_and_spacing():+ assert ata._parse_llm_response('{"verdict": "BTP", "confidence": 0.9}')["verdict"] == BENIGN_TRUE_POSITIVE+ assert ata._parse_llm_response('{"verdict": "benign true positive", "confidence": 0.9}')["verdict"] == BENIGN_TRUE_POSITIVE+++def test_parser_unknown_verdict_fails_safe_to_true_positive():+ out = ata._parse_llm_response('{"verdict": "banana", "confidence": 0.9}')+ assert out["verdict"] == TRUE_POSITIVE+++ "raw,expected",+ [+ ("likely_true_positive", TRUE_POSITIVE),+ ("likely_benign", BENIGN),+ ("likely_false_positive", FALSE_POSITIVE),+ ("needs_human_review", NEEDS_REVIEW),+ ("confirmed_incident", TRUE_POSITIVE),+ ("probable_incident", TRUE_POSITIVE),+ ("benign_true_positive", BENIGN_TRUE_POSITIVE),+ ],+)+def test_normalize_bridges_deterministic_and_llm_vocabularies(raw, expected):+ assert normalize_disposition(raw) == expected+++def test_btp_is_a_valid_detection_not_a_false_positive():+ # The core invariant of #526: BTP is a valid detection kept out of the FP+ # set (so it never corrupts false-positive-rate metrics), yet still safe to+ # auto-close because no active threat / response is warranted.+ assert BENIGN_TRUE_POSITIVE not in INVALID_DETECTION_DISPOSITIONS+ assert FALSE_POSITIVE in INVALID_DETECTION_DISPOSITIONS+ assert BENIGN_TRUE_POSITIVE in AUTO_CLOSEABLE_DISPOSITIONS+++# --- end-to-end scenarios via a mocked LLM ---------------------------------+++async def test_approved_penetration_test_is_benign_true_positive(monkeypatch):+ _patch_llm(monkeypatch, BENIGN_TRUE_POSITIVE, 0.95, "approved red-team engagement, matches change ticket")+ out = await ata.run_auto_triage(_state("Credential dumping on HR-LAPTOP", {"severity": "high", "risk_score": 0.8}))+ assert out.verdict == BENIGN_TRUE_POSITIVE+ # A valid detection of authorized activity is auto-closeable, not escalated.+ assert out.status == AgentStatus.COMPLETED+++async def test_scheduled_scanner_is_benign_true_positive(monkeypatch):+ _patch_llm(monkeypatch, BENIGN_TRUE_POSITIVE, 0.9, "source matches the authorized Nessus scanner window")+ out = await ata.run_auto_triage(_state("Port scan from 10.0.0.5", {"severity": "medium", "risk_score": 0.4}))+ assert out.verdict == BENIGN_TRUE_POSITIVE+++async def test_genuine_false_positive(monkeypatch):+ _patch_llm(monkeypatch, FALSE_POSITIVE, 0.92, "rule misfired on a mis-parsed command-line field")+ out = await ata.run_auto_triage(_state("Suspicious PowerShell", {"severity": "low", "risk_score": 0.1}))+ assert out.verdict == FALSE_POSITIVE+ assert out.status == AgentStatus.COMPLETED+++async def test_malicious_true_positive_escalates(monkeypatch):+ _patch_llm(monkeypatch, TRUE_POSITIVE, 0.97, "active C2 beacon to a known-bad IP")+ out = await ata.run_auto_triage(_state("Beaconing to 45.9.148.99", {"severity": "critical", "risk_score": 0.95}))+ assert out.verdict == TRUE_POSITIVE+ # A malicious true positive must never auto-close.+ assert out.status != AgentStatus.COMPLETED+++async def test_btp_metric_is_tracked_separately_from_fp(monkeypatch):+ ata._metrics.update({"fp_count": 0, "btp_count": 0, "benign_count": 0, "tp_count": 0, "total_processed": 0, "confidence_sum": 0.0})+ _patch_llm(monkeypatch, BENIGN_TRUE_POSITIVE, 0.95, "approved pentest")+ await ata.run_auto_triage(_state("cred dump", {"severity": "high"}))+ m = ata.get_metrics()+ assert m["btp_count"] == 1+ assert m["fp_count"] == 0+ assert m["btp_rate"] > 0diff --git a/services/api/app/api/v1/endpoints/feedback.py b/services/api/app/api/v1/endpoints/feedback.pyindex 48dcf9dec..de545cebd 100644--- a/services/api/app/api/v1/endpoints/feedback.py+++ b/services/api/app/api/v1/endpoints/feedback.py@@ -40,7 +40,16 @@ logger = structlog.get_logger()router = APIRouter(prefix="/feedback", tags=["feedback"])-_VALID_VERDICTS = {"true_positive", "false_positive", "benign", "escalate"}+# ``benign_true_positive`` (#526): a valid detection of authorized/expected+# activity. Kept distinct from ``false_positive`` so BTP never inflates a rule's+# false-positive rate. Existing ``benign`` records stay valid (no migration).+_VALID_VERDICTS = {+ "true_positive",+ "benign_true_positive",+ "false_positive",+ "benign",+ "escalate",+}def _coerce_uuid(value: str, field: str) -> uuid.UUID:@@ -58,7 +67,7 @@ class AlertOverrideRequest(BaseModel):original_verdict: str = Field(..., description="The AI-generated verdict being overridden")corrected_verdict: str = Field(...,- description="Analyst's verdict: true_positive | false_positive | benign | escalate",+ description="Analyst's verdict: true_positive | benign_true_positive | false_positive | benign | escalate",)reason: str | None = Field(None, description="Optional free-text justification")@@ -249,6 +258,9 @@ class OverrideSummaryResponse(BaseModel):total_overrides: intfalse_positive_corrections: inttrue_positive_corrections: int+ # Counted separately from false_positive so a valid detection of authorized+ # activity never inflates the false-positive rate on the FPR card (#526).+ benign_true_positive_corrections: int = 0benign_corrections: intescalate_corrections: int@@ -261,6 +273,7 @@ async def get_override_summary("""Return a summary of analyst overrides for this tenant."""counts: dict[str, int] = {"true_positive": 0,+ "benign_true_positive": 0,"false_positive": 0,"benign": 0,"escalate": 0,@@ -285,6 +298,7 @@ async def get_override_summary(total_overrides=total,false_positive_corrections=counts["false_positive"],true_positive_corrections=counts["true_positive"],+ benign_true_positive_corrections=counts["benign_true_positive"],benign_corrections=counts["benign"],escalate_corrections=counts["escalate"],)diff --git a/services/api/tests/test_btp_disposition.py b/services/api/tests/test_btp_disposition.pynew file mode 100644index 000000000..c48088321--- /dev/null+++ b/services/api/tests/test_btp_disposition.py@@ -0,0 +1,32 @@+"""#526 — benign_true_positive is a first-class analyst disposition, kept+distinct from false_positive throughout the feedback / rule-tuning surface."""++from __future__ import annotations++from app.api.v1.endpoints.feedback import _VALID_VERDICTS, OverrideSummaryResponse+from app.services.memory_poisoning import PoisoningDetector+++def test_feedback_api_accepts_benign_true_positive():+ assert "benign_true_positive" in _VALID_VERDICTS+++def test_feedback_api_still_accepts_legacy_benign():+ # Existing ``benign`` records/verdicts stay valid — no migration required.+ assert "benign" in _VALID_VERDICTS+++def test_override_summary_tracks_btp_separately_from_fp():+ fields = OverrideSummaryResponse.model_fields+ assert "benign_true_positive_corrections" in fields+ assert "false_positive_corrections" in fields+++def test_btp_is_not_treated_as_false_positive_for_rule_suppression():+ # The poisoning / re-disposition window keys on FP-like dispositions. A+ # benign true positive is a VALID detection: if it landed in this set an+ # attacker could farm authorized-looking activity to suppress a good rule,+ # and per-rule FP-rate metrics would be corrupted.+ detector = PoisoningDetector()+ assert "false_positive" in detector._fp_dispositions+ assert "benign_true_positive" not in detector._fp_dispositions