Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

9.8 KB
Raw Blame
"""
ReportWriterAgent — Final phase of the investigator pipeline.

Responsibilities:
  • Synthesise all agent findings into a structured Markdown report
  • Produce HTML variant (for PDF generation via Playwright/weasyprint)
  • Sign the report hash into the audit log
"""

from __future__ import annotations

import html
import time
from datetime import datetime
from typing import Any

import structlog
from langchain_core.messages import HumanMessage, SystemMessage

from app.core.cost_telemetry import record_llm_call
from app.llm import safe_ainvoke
from app.llm.factory import make_chat_model, resolve_model_alias
from app.llm.prompt_registry import prompt_text
from app.prompt_serialization import summarize_structure_for_llm

from .bundle_prompt import format_bundle_prompt_append
from .limits import max_completion_tokens
from .prompt_sanitizer import (
    sanitize_iterable_of_strings,
    sanitize_text,
)
from .state import InvestigatorState, StepKind
from .tools import sha256_of

logger = structlog.get_logger()


def _build_context(state: InvestigatorState) -> str:
    """Build a compact context string from all prior agent outputs.

    Every field surfaced here originated from attacker-influenced input —
    raw alert payloads, banners, Whois strings, dark-web excerpts, plus
    LLM summaries of the same. We sanitise scalars, cap list lengths, and
    wrap the IOC + enrichment blobs in ``<UNTRUSTED_DATA>`` envelopes so
    a prompt-injection payload buried inside, say, a Shodan banner can
    not override the system prompt's authoring instructions.

    ``case_id`` is the only field we trust verbatim; it is generated by
    the API and validated as a UUID upstream.
    """
    safe_alert = sanitize_text(state.alert_summary, max_len=2_000)
    safe_recon_summary = sanitize_text(state.recon.summary, max_len=2_500)
    safe_forensic_summary = sanitize_text(state.forensic.summary, max_len=2_500)
    safe_responder_summary = sanitize_text(state.responder.summary, max_len=2_000)
    safe_root_cause = sanitize_text(state.forensic.root_cause_hypothesis, max_len=1_000)
    safe_blast = sanitize_text(state.forensic.blast_radius, max_len=1_000)
    safe_risk_level = sanitize_text(state.responder.risk_level, max_len=32)

    safe_mitre = sanitize_iterable_of_strings(state.recon.mitre_techniques, max_item_len=64, max_items=25)
    safe_actors = sanitize_iterable_of_strings(state.recon.threat_actors, max_item_len=128, max_items=25)
    safe_artefacts = sanitize_iterable_of_strings(state.forensic.artefacts[:10], max_item_len=256, max_items=10)
    safe_containment = sanitize_iterable_of_strings(state.responder.containment_steps[:5], max_item_len=400, max_items=5)
    safe_eradication = sanitize_iterable_of_strings(state.responder.eradication_steps[:5], max_item_len=400, max_items=5)
    safe_recovery = sanitize_iterable_of_strings(state.responder.recovery_steps[:5], max_item_len=400, max_items=5)

    iocs_blob = summarize_structure_for_llm(
        state.recon.iocs,
        label="iocs",
        max_lines=30,
        max_depth=2,
    )
    enrichment_blob = summarize_structure_for_llm(
        dict(list(state.enrichment_cache.items())[:5]),
        label="enrichment_sample",
        max_lines=25,
        max_depth=2,
    )

    sections = [
        f"Case ID: {state.case_id}",
        f"Alert: {safe_alert}",
        "",
        "=== RECON ===",
        safe_recon_summary,
        f"IOCs:\n{iocs_blob}",
        f"MITRE: {safe_mitre}",
        f"Threat actors: {safe_actors}",
        "",
        "=== FORENSIC ===",
        safe_forensic_summary,
        f"Root cause: {safe_root_cause}",
        f"Blast radius: {safe_blast}",
        f"Confidence: {state.forensic.confidence:.0%}",
        f"Timeline entries: {len(state.forensic.timeline)}",
        f"Artefacts: {safe_artefacts}",
        "",
        "=== RESPONSE PLAN ===",
        safe_responder_summary,
        f"Risk level: {safe_risk_level}",
        f"Recommended actions: {len(state.responder.recommended_actions)}",
        f"Effort estimate: {state.responder.estimated_effort_hours}h",
        "Containment: " + "; ".join(safe_containment),
        "Eradication: " + "; ".join(safe_eradication),
        "Recovery: " + "; ".join(safe_recovery),
        "",
        "=== ENRICHMENT SAMPLE ===",
        enrichment_blob,
    ]
    return "\n".join(sections)


def _md_to_html(md: str, case_id: str) -> str:
    """Lightweight Markdown → HTML converter (no external deps required for basic output)."""
    try:
        import markdown

        body = markdown.markdown(md, extensions=["tables", "fenced_code"])
    except ImportError:
        # Escaped, because a raw `<pre>` wrap leaks HTML through unchanged and
        # this report carries model output and connector-supplied entity names.
        # `orchestrator/report.py` already reached this conclusion and says so
        # in a comment; this copy did the thing that comment warns against.
        body = f"<pre>{html.escape(md)}</pre>"

    case_id = html.escape(str(case_id), quote=True)
    ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>AiSOC Incident Report — {case_id}</title>
<style>
  body {{ font-family: 'Segoe UI', Arial, sans-serif; max-width: 960px; margin: 40px auto; color: #1a1a1a; }}
  h1 {{ color: #c0392b; }} h2 {{ color: #2c3e50; border-bottom: 1px solid #eee; padding-bottom: 4px; }}
  table {{ border-collapse: collapse; width: 100%; }} th,td {{ border: 1px solid #ddd; padding: 8px; }}
  th {{ background: #2c3e50; color: white; }}
  code {{ background: #f4f4f4; padding: 2px 6px; border-radius: 3px; }}
  pre {{ background: #f4f4f4; padding: 16px; overflow-x: auto; border-radius: 4px; }}
  .footer {{ color: #999; font-size: 0.8em; margin-top: 40px; }}
</style>
</head>
<body>
{body}
<div class="footer">Generated by AiSOC on {ts}</div>
</body>
</html>"""


async def run_report_writer(state_dict: dict[str, Any]) -> dict[str, Any]:
    """LangGraph node."""
    state = InvestigatorState.from_dict(state_dict)
    t0 = time.monotonic()

    logger.info("report_writer.start", case_id=state.case_id)

    model = resolve_model_alias("report")
    llm = make_chat_model("report", temperature=0, max_tokens=max_completion_tokens())

    context = _build_context(state)
    bundle_append = format_bundle_prompt_append(state.context_bundle)
    if bundle_append:
        context = f"{context}\n\n{bundle_append}"
    system_prompt = prompt_text("report_writer.system").format(case_id=state.case_id)
    messages = [
        SystemMessage(content=system_prompt),
        HumanMessage(content=context),
    ]

    prompt_hash = state.log_llm_prompt(
        agent="ReportWriterAgent",
        prompt=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": context},
        ],
        model=model,
        purpose="report: synthesise final markdown incident report",
    )

    t_llm = time.monotonic()
    try:
        response = await safe_ainvoke(llm, messages)
        state.report_md = response.content
        latency_ms = int((time.monotonic() - t_llm) * 1000)
        tokens = 0
        if hasattr(response, "response_metadata"):
            tokens = response.response_metadata.get("token_usage", {}).get("total_tokens", 0) or 0
        # Tier 1.6: record cost telemetry on the active CostTracker.
        call_record = record_llm_call(
            response,
            model=model,
            latency_ms=latency_ms,
            step="report_writer",
            tool="llm.report_writer",
        )
        # None when nothing could price the call — see app/core/gateway_cost.py.
        # Not 0.0: an unpriced call is not a free one.
        cost_usd = call_record.cost_usd if call_record is not None else None
        cost_source = call_record.cost_source if call_record is not None else "unpriced"
        resolved_model = call_record.resolved_model if call_record is not None else None
        state.log_llm_response(
            agent="ReportWriterAgent",
            response=state.report_md if isinstance(state.report_md, str) else str(state.report_md),
            prompt_hash=prompt_hash,
            model=model,
            tokens_used=tokens,
            latency_ms=latency_ms,
            cost_usd=cost_usd,
            cost_source=cost_source,
            resolved_model=resolved_model,
        )
    except Exception as exc:  # noqa: BLE001
        logger.warning("report_writer llm failed", error=str(exc))
        state.log(
            StepKind.ERROR,
            "ReportWriterAgent",
            f"LLM call failed, using fallback report: {exc}",
        )
        state.report_md = _fallback_report(state)

    state.report_html = _md_to_html(state.report_md, state.case_id)

    elapsed_ms = int((time.monotonic() - t0) * 1000)
    report_hash = sha256_of(state.report_md)
    state.log(
        StepKind.REPORT,
        "ReportWriterAgent",
        f"Report written ({len(state.report_md)} chars, hash={report_hash[:12]})",
        duration_ms=elapsed_ms,
        report_hash=report_hash,
    )
    state.status = "completed"
    state.completed_at = datetime.utcnow()
    state.iteration += 1
    logger.info("report_writer.done", case_id=state.case_id, ms=elapsed_ms)
    return state.to_dict()


def _fallback_report(state: InvestigatorState) -> str:
    return f"""# Incident Report — {state.case_id}

## Executive Summary
{state.alert_summary}

## Recon Summary
{state.recon.summary}

## Forensic Findings
{state.forensic.summary}

Root cause hypothesis: {state.forensic.root_cause_hypothesis}

## Response Plan
{state.responder.summary}

Risk level: **{state.responder.risk_level}**

### Containment
{chr(10).join(f"- {s}" for s in state.responder.containment_steps)}

### Eradication
{chr(10).join(f"- {s}" for s in state.responder.eradication_steps)}

### Recovery
{chr(10).join(f"- {s}" for s in state.responder.recovery_steps)}

---
*Generated by AiSOC — automated report (LLM unavailable)*
"""