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
"""
Tests for ``app.orchestrator.report`` — router report synthesis (T2.2).
Covers the deterministic Markdown + HTML render path that the
``RouterOrchestrator.stream()`` surface will use to ship the same
``report_md`` / ``report_html`` artifact shape the legacy
``InvestigatorOrchestrator`` already emits.
"""
from __future__ import annotations
from datetime import datetime
from uuid import UUID
import pytest
from app.models.state import (
ActionRisk,
AgentStatus,
InvestigationState,
ProposedAction,
)
from app.orchestrator.report import (
render_router_report,
render_router_report_html,
render_router_report_md,
)
def _build_state(**overrides) -> InvestigationState:
"""Build a populated ``InvestigationState`` with sensible defaults.
Pinning identifiers and timestamps keeps assertions stable across runs.
"""
base = {
"run_id": UUID("11111111-1111-1111-1111-111111111111"),
"incident_id": UUID("22222222-2222-2222-2222-222222222222"),
"tenant_id": UUID("33333333-3333-3333-3333-333333333333"),
"alert_summary": "Suspicious login from foreign IP",
"raw_alert": {"src_ip": "203.0.113.42"},
"findings": ["User [email protected] logged in from Russia", "Multiple failed MFA attempts"],
"mitre_mappings": ["T1078.004", "T1110.001"],
"verdict": "true_positive",
"confidence": 0.87,
"confidence_basis": ["High-entropy ASN", "Off-hours access"],
"status": AgentStatus.COMPLETED,
"started_at": datetime(2026, 5, 15, 9, 0, 0),
"completed_at": datetime(2026, 5, 15, 9, 2, 30),
}
base.update(overrides)
return InvestigationState(**base)
def _build_action(
*,
action_type: str = "disable_user",
target: str = "[email protected]",
risk: ActionRisk = ActionRisk.HIGH,
requires_approval: bool = True,
rationale: str = "Account is showing clear takeover signals",
) -> ProposedAction:
return ProposedAction(
action_type=action_type,
description=f"{action_type} for {target}",
risk_level=risk,
target=target,
requires_approval=requires_approval,
rationale=rationale,
)
# ---------------------------------------------------------------------------
# Markdown shape
# ---------------------------------------------------------------------------
def test_markdown_contains_all_core_sections() -> None:
"""A fully-populated state renders every optional section."""
state = _build_state(proposed_actions=[_build_action()])
md = render_router_report_md(
state,
info={"topology": "parallel", "signals": ["multi_agent"], "wall_clock_ms": 1234.5},
)
# Header references the incident id
assert md.startswith("# Incident Report \u2014 22222222-2222-2222-2222-222222222222")
# Each section heading is present
for heading in (
"## Summary",
"## Triage Rationale",
"## Findings",
"## MITRE ATT&CK Mappings",
"## Proposed Actions",
):
assert heading in md, f"missing section heading: {heading}"
# Summary table picks up substrate telemetry from `info`
assert "| Verdict | true_positive |" in md
assert "| Confidence | 0.87 |" in md
assert "| Status | completed |" in md
assert "| Topology | parallel |" in md
assert "| Signals | multi_agent |" in md
assert "| Wall-clock (ms) | 1234.5 |" in md
# Findings rendered as bullets
assert "- User [email protected] logged in from Russia" in md
assert "- Multiple failed MFA attempts" in md
# MITRE techniques wrapped in inline code
assert "- `T1078.004`" in md
assert "- `T1110.001`" in md
# Proposed actions table has header + a populated row
assert "| # | Action | Target | Risk | Approval | Rationale |" in md
assert "| 1 | disable_user | [email protected] | high | yes |" in md
# Footer always emitted
assert "_Generated by AiSOC router on" in md
def test_markdown_skips_optional_sections_when_empty() -> None:
"""Sections backed by empty lists drop out cleanly."""
state = _build_state(
findings=[],
mitre_mappings=[],
confidence_basis=[],
proposed_actions=[],
)
md = render_router_report_md(state)
# Required sections still present
assert "## Summary" in md
# Optional sections dropped
assert "## Findings" not in md
assert "## MITRE ATT&CK Mappings" not in md
assert "## Triage Rationale" not in md
assert "## Proposed Actions" not in md
assert "## Errors" not in md
def test_markdown_error_section_when_state_has_error() -> None:
"""An error on the state surfaces as a fenced ``Errors`` section."""
state = _build_state(error="recon sub-agent timed out after 30s")
md = render_router_report_md(state)
assert "## Errors" in md
assert "recon sub-agent timed out after 30s" in md
# Fenced code block (triple backticks) wraps the error
assert "```" in md
def test_markdown_escapes_pipes_in_action_rationale() -> None:
"""Pipes inside a rationale must be escaped so the table stays valid."""
action = _build_action(rationale="alice|bob exfiltrated\nover SSH")
state = _build_state(proposed_actions=[action])
md = render_router_report_md(state)
# Backslash-escaped pipe + newline collapsed to space
assert "alice\\|bob exfiltrated over SSH" in md
# Newline inside rationale should not break out of the table row
actions_lines = [line for line in md.splitlines() if line.startswith("| 1 |")]
assert len(actions_lines) == 1
def test_markdown_handles_invalid_confidence_gracefully() -> None:
"""A non-numeric confidence shouldn't crash the renderer."""
state = _build_state()
# Bypass Pydantic validation by mutating after construction
object.__setattr__(state, "confidence", "not-a-number") # type: ignore[arg-type]
md = render_router_report_md(state)
assert "| Confidence | 0.00 |" in md
def test_markdown_renders_without_info_dict() -> None:
"""Substrate telemetry is optional — caller may omit ``info``."""
state = _build_state()
md = render_router_report_md(state)
assert "## Summary" in md
# Topology / signals / wall-clock rows skipped when info is missing
assert "| Topology |" not in md
assert "| Signals |" not in md
assert "| Wall-clock (ms) |" not in md
# ---------------------------------------------------------------------------
# HTML shape
# ---------------------------------------------------------------------------
def test_html_wraps_markdown_with_document_chrome() -> None:
"""The HTML output is a full document with the case id in the title.
The ``<h1>``/``<table>`` assertions are about what the ``markdown``
library produces, so without it this asserted the ``<pre>`` fallback's
output against the rendered form and failed. ``markdown`` is a declared
dependency of this service (``pyproject.toml``: ``markdown = "^3.5"``) and
is installed in CI, so a missing one means an incomplete environment
rather than a defect — hence a skip that says so, not a red test nobody
reads. The fallback branch has its own coverage immediately below.
"""
pytest.importorskip(
"markdown",
reason="markdown is a declared agents dependency; these assertions are about its rendering, "
"and the <pre> fallback is covered by test_html_fallback_when_markdown_module_missing",
)
md = "# Incident Report — case-42\n\n## Summary\n\n| Field | Value |\n|---|---|\n| Verdict | tp |\n"
html = render_router_report_html(md, case_id="case-42")
assert html.startswith("<!DOCTYPE html>")
assert "<title>AiSOC Incident Report \u2014 case-42</title>" in html
assert "Generated by AiSOC on" in html
# Markdown library should turn the H1 into an <h1>
assert "<h1>" in html
# Table extension should render the pipe-table as a real HTML table
assert "<table>" in html
def test_html_fallback_when_markdown_module_missing(monkeypatch: pytest.MonkeyPatch) -> None:
"""If ``markdown`` can't be imported we still ship a usable document."""
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs): # type: ignore[no-untyped-def]
if name == "markdown":
raise ImportError("forced failure for test")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
md = "# Hello\n\nsome body text"
html = render_router_report_html(md, case_id="case-1")
# Falls back to wrapping the raw Markdown in <pre>
assert "<pre># Hello\n\nsome body text</pre>" in html
# Still produces a complete HTML document
assert html.startswith("<!DOCTYPE html>")
assert "</html>" in html
# ---------------------------------------------------------------------------
# Convenience wrapper
# ---------------------------------------------------------------------------
def test_render_router_report_returns_md_and_html() -> None:
"""The convenience wrapper returns both artifacts in one call."""
state = _build_state()
md, html = render_router_report(state, info={"topology": "sequential"})
assert md.startswith("# Incident Report \u2014")
assert html.startswith("<!DOCTYPE html>")
# The case id flows through to the HTML title
assert str(state.incident_id) in html
# Sequential topology surfaces in the summary table
assert "| Topology | sequential |" in md
# ---------------------------------------------------------------------------
# XSS / injection regression tests (review feedback on PR #141)
# ---------------------------------------------------------------------------
def test_findings_with_html_tags_are_escaped() -> None:
"""A finding containing raw HTML never reaches the rendered HTML as a tag.
State fields like ``findings`` flow from sub-agent outputs that can in
turn carry adversary-influenced strings from the raw alert. The report
pipeline (``render_router_report_md`` → ``markdown.markdown``) must
escape these so a payload like ``<script>alert(1)</script>`` ships as
literal text rather than an executable script tag.
The property holds on both rendering branches, so this asserts it on
whichever one ran. It used to require the literal ``<script>`` in
the HTML, which only the ``markdown`` branch produces: the ``<pre>``
fallback escapes the already-escaped Markdown body a second time and
emits ``&lt;script&gt;``. That is *more* escaped, not less, so the
old assertion failed on a branch that was behaving correctly — a
misleading red for a payload that was never executable either way.
"""
payload = "<script>alert('xss')</script>"
state = _build_state(findings=[payload])
md, html_out = render_router_report(state)
# Markdown body keeps the escaped form, not the raw tag
assert "<script>" not in md
assert "<script>" in md
# The property that matters, and it is branch-independent: nothing a
# finding carried can reach the document as an executable tag.
assert "<script>alert" not in html_out
assert "<script>" not in html_out
# The payload is still *present*, escaped, so this is not passing because
# the finding was silently dropped.
assert "script" in html_out
# Either branch's escaping is acceptable; naming both keeps the assertion
# honest about which one ran rather than skipping the fallback.
assert "<script>" in html_out or "&lt;script&gt;" in html_out
def test_error_field_with_html_is_escaped() -> None:
"""``state.error`` is HTML-escaped before going into the fenced code block."""
state = _build_state(error="<img src=x onerror=alert(1)>")
md, html_out = render_router_report(state)
assert "<img src=x" not in md
assert "<img src=x onerror=alert(1)>" in md
assert "<img src=x onerror=" not in html_out
def test_proposed_action_target_with_html_is_escaped() -> None:
"""Every action-table cell — not just ``rationale`` — gets escaped."""
bad_action = ProposedAction(
action_type="isolate_host",
description="isolate host",
target="<svg onload=alert(1)>",
risk_level=ActionRisk.HIGH,
requires_approval=True,
rationale="standard",
)
state = _build_state(proposed_actions=[bad_action])
md, html_out = render_router_report(state)
assert "<svg onload" not in md
assert "<svg onload=alert(1)>" in md
assert "<svg onload" not in html_out
def test_proposed_action_target_with_pipe_does_not_break_table() -> None:
"""A ``|`` in any cell — not just ``rationale`` — gets escaped."""
bad_action = ProposedAction(
action_type="disable_user|forever",
description="disable user account",
target="alice|bob",
risk_level=ActionRisk.MEDIUM,
requires_approval=False,
rationale="cleanup",
)
state = _build_state(proposed_actions=[bad_action])
md = render_router_report_md(state)
assert "disable_user\\|forever" in md
assert "alice\\|bob" in md
def test_html_fallback_branch_escapes_body(monkeypatch) -> None:
"""The ``ImportError`` fallback branch must still escape adversary HTML.
The previous implementation wrapped raw Markdown in ``<pre>`` with no
escaping; a finding containing ``<script>`` would have reached the
browser intact when ``markdown`` was unavailable in the runtime.
"""
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "markdown":
raise ImportError("simulated missing dep")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
md = "# Hello\n\n<script>alert(1)</script>"
html_out = render_router_report_html(md, case_id="case-1")
assert "<script>alert(1)</script>" not in html_out
assert "<script>alert(1)</script>" in html_out
def test_case_id_with_html_is_escaped_in_title() -> None:
"""An adversary-controlled case ID can't break out of the ``<title>``."""
md = "# Incident"
html_out = render_router_report_html(md, case_id="</title><script>alert(1)</script>")
assert "</title><script>alert(1)</script>" not in html_out
# Closing tag of title is the one the renderer itself emits
assert "</title><script>alert(1)</script>" in html_out