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.

13.2 KB
Raw Blame
"""Record real model replies to the real triage prompt, for replay in CI.

Fix pass item 3.5. See ``plans/aisoc_fix_pass_plan.plan.md``.

Why a recording exists at all
-----------------------------
``test_replay_runner.py`` has to prove two things about a replay run that pull
in opposite directions: the same history must produce the same decisions
twice, and the decisions must not all be the same decision. The second one is
what the deterministic tier cannot supply — it answers ``likely_benign`` at
0.10 for every alert, so a reproducibility assertion over it compares one
constant against itself and would pass over a runner that had stopped reading
its input.

A live model supplies the variety and destroys the reproducibility. A
recording supplies both: the replies are what a real model really said to the
real production prompt, and replaying them is byte-stable.

What is real here and what is not
---------------------------------
* The **replies** are real. They were generated by a local model answering the
  production triage prompt, over HTTP, through the gateway client the worker
  builds in ``app.llm.factory.make_chat_model``. Nothing was edited afterwards;
  a reply the parser rejects is recorded as it arrived.
* The **alerts** are synthetic. They are Splunk ES notable rows written for
  this fixture, not customer data, using RFC 5737 documentation addresses.

That distinction is the whole value of the file, so it is also written into
the fixture's ``provenance`` block where a reader of the data will see it.

Re-recording
------------
Any OpenAI-compatible endpoint serving a real model works. The recording
committed to the repository was produced with::

    ollama serve                       # in another terminal
    cd services/agents
    PYTHONPATH=. python tests/record_replay_triage.py \\
        --base-url http://127.0.0.1:11434/v1 --model llama3:8b

The script refuses to write a recording whose verdicts are all one class,
because such a recording would restore exactly the defect this item exists to
remove.
"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import sys
import threading
import urllib.request
import uuid
from collections import Counter
from datetime import UTC, datetime, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any

RECORDING_PATH = Path(__file__).resolve().parent / "eval_data" / "replay_triage_recording.json"

#: Close times are fixed so the split point, and therefore which alerts land in
#: the test window, does not move with the calendar.
_BASE = datetime(2026, 3, 1, tzinfo=UTC)

#: Six Splunk ES notable shapes spanning the taxonomy the triage prompt asks
#: the model to choose from. Written to differ in the signals the prompt names
#: — severity, IOC presence, whether the activity was authorised — rather than
#: to steer any particular verdict, because the point of the recording is what
#: a model says about varied input, not what it says about input built to
#: produce an answer.
_ARCHETYPES: tuple[dict[str, Any], ...] = (
    {
        "slug": "lsass-access",
        "search_name": "Credential Dumping - LSASS Memory Access",
        "urgency": "critical",
        "src": "198.51.100.23",
        "host": "FIN-APP-07",
        "user": "svc_backup",
        "process": "rundll32.exe",
        "signature": "comsvcs.dll MiniDump",
        "mitre": "T1003.001",
    },
    {
        "slug": "authorised-scan",
        "search_name": "Vulnerability Scanner Activity Detected",
        "urgency": "medium",
        "src": "192.0.2.50",
        "host": "DMZ-WEB-02",
        "user": "svc_qualys",
        "process": "n/a",
        "signature": "Scheduled authenticated scan from the approved scanner subnet",
        "mitre": "T1595",
    },
    {
        "slug": "eicar",
        "search_name": "Malware Signature Match",
        "urgency": "high",
        "src": "203.0.113.14",
        "host": "HR-LAPTOP-31",
        "user": "a.mitchell",
        "process": "chrome.exe",
        "signature": "EICAR-Test-File quarantined on write by the endpoint agent",
        "mitre": "T1204.002",
    },
    {
        "slug": "account-lockout",
        "search_name": "Account Lockout Threshold Reached",
        "urgency": "low",
        "src": "198.51.100.77",
        "host": "CORP-DC-01",
        "user": "j.okafor",
        "process": "lsass.exe",
        "signature": "Five failed interactive logons then a successful one from the same workstation",
        "mitre": "T1110.001",
    },
    {
        "slug": "exfil",
        "search_name": "Large Outbound Transfer to Unrecognised Host",
        "urgency": "high",
        "src": "198.51.100.42",
        "host": "ENG-WS-14",
        "user": "p.novak",
        "process": "powershell.exe",
        "signature": "4.2 GB uploaded to 203.0.113.200 outside business hours",
        "mitre": "T1048",
    },
    {
        "slug": "service-account-hours",
        "search_name": "Service Account Interactive Logon",
        "urgency": "medium",
        "src": "198.51.100.9",
        "host": "CORP-FS-03",
        "user": "svc_sql",
        "process": "explorer.exe",
        "signature": "Interactive logon by an account flagged as non-interactive",
        "mitre": "T1078.002",
    },
)

#: Twenty findings so the default 70/30 split leaves a six-alert test window,
#: cycling the archetypes so that window holds all six.
_FINDING_COUNT = 20


def build_findings() -> list[dict[str, Any]]:
    """The synthetic history, as plain data both the recorder and the test read."""
    findings: list[dict[str, Any]] = []
    for index in range(_FINDING_COUNT):
        archetype = _ARCHETYPES[index % len(_ARCHETYPES)]
        finding_id = f"ES-{index:03d}"
        findings.append(
            {
                "finding_id": finding_id,
                "vendor": "splunk",
                "title": archetype["search_name"],
                # The analyst label. Not used by the recording — a replay sends
                # the model the alert, never the answer — and carried so the
                # test exercises the labelled/graded path the product uses.
                "disposition": "true_positive" if index % 3 == 0 else "false_positive",
                "vendor_disposition": "disposition:1" if index % 3 == 0 else "disposition:2",
                "closed_at": (_BASE + timedelta(hours=index)).isoformat(),
                "rule_id": f"rule-{archetype['slug']}",
                "raw": {
                    "event_id": finding_id,
                    "rule_id": f"rule-{archetype['slug']}",
                    "search_name": archetype["search_name"],
                    "urgency": archetype["urgency"],
                    "src": archetype["src"],
                    "host": archetype["host"],
                    "user": archetype["user"],
                    "process_name": archetype["process"],
                    "signature": archetype["signature"],
                    "annotations.mitre_attack": archetype["mitre"],
                    "_time": str(int((_BASE + timedelta(hours=index)).timestamp())),
                },
            }
        )
    return findings


class _RecordingProxy(ThreadingHTTPServer):
    """Loopback gateway that forwards to a real model and keeps the reply.

    The agents service is pointed at this rather than at the model directly,
    because the recorded artefact has to be the response body as the gateway
    client received it. Reading the parsed verdict off the decision instead
    would record this script's interpretation of the reply, which is the one
    thing a replay must not be built on.
    """

    daemon_threads = True

    def __init__(self, upstream: str, model: str) -> None:
        super().__init__(("127.0.0.1", 0), _ProxyHandler)
        self.upstream = upstream.rstrip("/") + "/chat/completions"
        self.model = model
        self.recorded: dict[str, Any] = {}


class _ProxyHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_POST(self) -> None:  # noqa: N802 - BaseHTTPRequestHandler's spelling
        body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
        key = finding_id_in(body)
        server: _RecordingProxy = self.server  # type: ignore[assignment]

        request = urllib.request.Request(  # noqa: S310 - loopback or operator-supplied endpoint
            server.upstream,
            data=json.dumps({**body, "model": server.model}).encode(),
            headers={"Content-Type": "application/json", "Authorization": "Bearer local"},
            method="POST",
        )
        with urllib.request.urlopen(request, timeout=600) as upstream:  # noqa: S310
            payload = json.loads(upstream.read())

        if key:
            server.recorded[key] = payload
        raw = json.dumps(payload).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(raw)))
        self.end_headers()
        self.wfile.write(raw)

    def log_message(self, *args: Any) -> None:
        return


#: The alert's id as the triage prompt renders it. The user message is the
#: stable half of the request — the system message carries a per-run injection
#: nonce — so this line is what a reply can be filed under and found again.
_ID_PREFIX = "id: "


def finding_id_in(request_body: dict[str, Any]) -> str:
    """Which alert this chat-completions request is about.

    Shared with the replay server in the test so the two cannot come to
    disagree about how a recording is addressed.
    """
    for message in request_body.get("messages") or []:
        if message.get("role") != "user":
            continue
        for line in str(message.get("content") or "").splitlines():
            if line.startswith(_ID_PREFIX):
                return line[len(_ID_PREFIX) :].strip()
    return ""


def verdict_in(response_body: dict[str, Any]) -> str:
    """The verdict a recorded reply carries, for the degeneracy check below."""
    try:
        content = response_body["choices"][0]["message"]["content"]
        return str(json.loads(content).get("verdict") or "")
    except Exception:  # noqa: BLE001 - an unparseable reply is a real recording
        return ""


async def _record(base_url: str, model: str) -> dict[str, Any]:
    from app.replay.findings import HistoricalFinding
    from app.replay.runner import ReplayRunner

    findings = build_findings()
    proxy = _RecordingProxy(base_url, model)
    threading.Thread(target=proxy.serve_forever, daemon=True).start()
    port = proxy.server_address[1]

    os.environ.pop("AISOC_DETERMINISTIC", None)
    os.environ["OPENAI_BASE_URL"] = f"http://127.0.0.1:{port}/v1"
    os.environ["OPENAI_API_KEY"] = "recording-session"
    os.environ["AISOC_MODEL_PIN_TRIAGE"] = model

    from tests.replay_recording import SplunkNotableNormalizer

    runner = ReplayRunner(normalizer=SplunkNotableNormalizer(), tenant_id=str(uuid.uuid4()))
    run = await runner.run(
        [
            HistoricalFinding(
                vendor=f["vendor"],
                finding_id=f["finding_id"],
                title=f["title"],
                disposition=f["disposition"],
                vendor_disposition=f["vendor_disposition"],
                closed_at=datetime.fromisoformat(f["closed_at"]),
                rule_id=f["rule_id"],
                raw=dict(f["raw"]),
            )
            for f in findings
        ]
    )
    proxy.shutdown()

    tiers = {d.tier for d in run.decisions}
    if tiers != {"llm"}:
        raise SystemExit(f"recording did not reach the model on every alert: tiers were {sorted(tiers)}")

    return {
        "provenance": {
            "recorded_at": datetime.now(UTC).date().isoformat(),
            "model": model,
            "endpoint": base_url,
            "recorder": "services/agents/tests/record_replay_triage.py",
            "replies": (
                "real — generated by the model named above, answering the production triage prompt "
                "over HTTP through app.llm.factory.make_chat_model. Unedited."
            ),
            "alerts": ("synthetic — Splunk ES notable rows written for this fixture, RFC 5737 documentation addresses, not customer data."),
        },
        "findings": findings,
        "responses": {d.finding_id: proxy.recorded[d.finding_id] for d in run.decisions},
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base-url", required=True, help="OpenAI-compatible base URL, e.g. http://127.0.0.1:11434/v1")
    parser.add_argument("--model", required=True, help="Model the endpoint serves, e.g. llama3:8b")
    parser.add_argument("--out", type=Path, default=RECORDING_PATH)
    args = parser.parse_args()

    recording = asyncio.run(_record(args.base_url, args.model))

    verdicts = Counter(verdict_in(body) for body in recording["responses"].values())
    if len(verdicts) < 2:
        raise SystemExit(
            f"every reply carried the same verdict ({dict(verdicts)}); a constant recording "
            "restores the defect this fixture exists to remove"
        )

    args.out.write_text(json.dumps(recording, indent=2, sort_keys=False) + "\n")
    print(f"wrote {args.out} — {len(recording['responses'])} replies, verdicts {dict(verdicts)}")
    return 0


if __name__ == "__main__":
    sys.exit(main())