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.

14.1 KB
Raw Blame
"""Static regression gate for the LLM input contract (T2.3).

Rule: nothing in ``services/agents/app/`` may call ``.ainvoke(...)`` or
``.astream(...)`` directly on an LLM. All LLM calls MUST go through
:func:`app.llm.contract.safe_ainvoke`, :func:`app.llm.contract.safe_astream`,
or :func:`app.llm.contract.make_safe_chat_model`.

The check is intentionally textual-AST (not type-aware) because LangChain
chat models are not nominally typed. We rely on a *receiver allowlist*:
calls like ``self._graph.ainvoke(...)`` and ``investigation_graph.ainvoke(...)``
are LangGraph control-flow primitives, not LLM invocations, and are listed
explicitly so a reviewer notices when the allowlist grows.

To add a new permitted receiver name, append to ``_ALLOWED_RECEIVERS`` with
a short justification comment. To exempt an entire file (because the file
itself implements the wrapper), append to ``_ALLOWED_FILES``.
"""

from __future__ import annotations

import ast
from pathlib import Path

_AGENTS_APP = Path(__file__).resolve().parent.parent / "app"

# Receivers that are NOT chat models. Each entry MUST be explained.
_ALLOWED_RECEIVERS: frozenset[str] = frozenset(
    {
        # LangGraph compiled graph — control-flow, not an LLM. Used in
        # services/agents/app/investigator/orchestrator.py via self._graph.
        "_graph",
        # Module-level LangGraph handle in services/agents/app/api/router.py.
        "investigation_graph",
        # Generic LangGraph handles. If someone wires a graph elsewhere we
        # still don't want to flag it. Keep tight — add new names only when
        # the call site is reviewed as control-flow, not an LLM call.
        "graph",
    }
)

# Files where direct ``llm.ainvoke``/``llm.astream`` IS the implementation of
# the safe wrapper itself. The wrapper validates messages first, then
# delegates — so these calls are by construction safe.
_ALLOWED_FILES: frozenset[Path] = frozenset(
    {
        _AGENTS_APP / "llm" / "contract.py",
    }
)

_METHODS = {"ainvoke", "astream"}


def _receiver_name(node: ast.Attribute) -> str:
    """Best-effort receiver identifier for ``X.method(...)``.

    For ``self._graph.ainvoke(...)`` → ``_graph``.
    For ``investigation_graph.ainvoke(...)`` → ``investigation_graph``.
    For ``some_func().ainvoke(...)`` → ``<call>`` (we treat as unknown and flag).
    """
    value = node.value
    if isinstance(value, ast.Attribute):
        return value.attr
    if isinstance(value, ast.Name):
        return value.id
    return f"<{type(value).__name__}>"


def _getattr_bypass_method(node: ast.Call) -> str | None:
    """Detect ``getattr(x, "ainvoke")(...)`` and ``getattr(x, "astream")(...)``.

    This is the canonical evasion of attribute-name-based AST gates: a
    future author could route around ``.ainvoke``/``.astream`` checks by
    writing ``getattr(llm, "ainvoke")(messages)`` and the bare-attribute
    walker would never see it. We flag the *outer* call here (the call
    that actually invokes the LLM) and report it as if it had been
    ``receiver.method(...)``.

    Returns the method name (``"ainvoke"`` / ``"astream"``) if this
    Call is a ``getattr``-mediated bypass, else ``None``.
    """
    inner = node.func
    if not isinstance(inner, ast.Call):
        return None
    if not isinstance(inner.func, ast.Name) or inner.func.id != "getattr":
        return None
    # getattr(obj, "name"[, default]) — name must be a literal string for
    # the bypass to be useful at the call site.
    if len(inner.args) < 2:
        return None
    name_arg = inner.args[1]
    if not isinstance(name_arg, ast.Constant) or not isinstance(name_arg.value, str):
        return None
    if name_arg.value not in _METHODS:
        return None
    return name_arg.value


def _find_bypasses(path: Path) -> list[tuple[int, str, str]]:
    """Return (lineno, receiver, method) tuples for forbidden calls in ``path``.

    Detects three call shapes:

    1. ``obj.ainvoke(...)`` / ``obj.astream(...)`` — direct attribute call.
    2. ``self.obj.ainvoke(...)`` — chained attribute call (receiver is
       the inner attr, e.g. ``_graph``).
    3. ``getattr(obj, "ainvoke")(...)`` — name-indirection bypass; the
       outer ``Call`` is flagged with receiver ``<getattr>`` because the
       allowlist is by static name and the dynamic lookup deliberately
       defeats that — reviewers must justify and refactor, not allowlist.
    """
    source = path.read_text(encoding="utf-8")
    tree = ast.parse(source, filename=str(path))
    findings: list[tuple[int, str, str]] = []

    for node in ast.walk(tree):
        if not isinstance(node, ast.Call):
            continue

        # Shape 3: getattr(x, "ainvoke")(...) — flagged unconditionally.
        method = _getattr_bypass_method(node)
        if method is not None:
            findings.append((node.lineno, "<getattr>", method))
            continue

        # Shapes 1 + 2: x.ainvoke(...) / self.x.ainvoke(...).
        func = node.func
        if not isinstance(func, ast.Attribute):
            continue
        if func.attr not in _METHODS:
            continue
        receiver = _receiver_name(func)
        if receiver in _ALLOWED_RECEIVERS:
            continue
        findings.append((node.lineno, receiver, func.attr))
    return findings


def _python_sources() -> list[Path]:
    return [p for p in _AGENTS_APP.rglob("*.py") if "__pycache__" not in p.parts and p not in _ALLOWED_FILES]


# ── Raw-HTTP LLM calls ─────────────────────────────────────────────────────
#
# The gate above walks the AST for `.ainvoke` / `.astream`, which proves the
# LangChain path is clean and says nothing about the other way to reach a
# model: POST to a chat-completions URL with httpx. `app/api/explain.py` did
# exactly that and was invisible here for several releases, under a test named
# "no bypass".
#
# The same shape is the whole story in `services/api`, which had no contract
# at all while seven endpoints POSTed untrusted input to a provider.

_API_APP = _AGENTS_APP.parent.parent / "api" / "app"

#: A URL fragment that means "this is a chat-completions endpoint".
_COMPLETIONS_MARKERS = ("chat/completions", "/completions")

#: Files that legitimately construct such a request: the safe wrappers
#: themselves, which validate before the POST.
_ALLOWED_HTTP_FILES: frozenset[Path] = frozenset(
    {
        _AGENTS_APP / "llm" / "contract.py",
        _API_APP / "services" / "llm_safety.py",
        # Vendored copy of the rules; carries no HTTP call, listed so a future
        # sync that adds one is a deliberate decision.
        _API_APP / "_vendor" / "llm_contract_rules.py",
    }
)


#: ``.post`` receivers that are route registrars, not HTTP clients. A FastAPI
#: ``@router.post("/...")`` decorator is the same attribute name as an httpx
#: POST and means the opposite thing.
_NOT_HTTP_CLIENTS: frozenset[str] = frozenset({"router", "app", "api_router"})


def _mentions_completions(source: str) -> bool:
    return any(marker in source for marker in _COMPLETIONS_MARKERS)


def _find_raw_http_llm_calls(path: Path) -> list[tuple[int, str]]:
    """Flag a `client.post(...)`-shaped call in a file that names a
    completions endpoint and does not import a safe wrapper.

    Deliberately coarse. Proving that a particular `post` targets a
    completions URL requires following a variable through string formatting,
    which an AST walker cannot do reliably — so the test asks the answerable
    question instead: does this file both talk about a completions endpoint
    and issue its own POST? A file that routes through
    `safe_chat_completions_request` passes, because it no longer issues the
    POST itself.
    """
    source = path.read_text(encoding="utf-8")
    if not _mentions_completions(source):
        return []
    if "safe_chat_completions_request" in source:
        return []

    tree = ast.parse(source, filename=str(path))
    findings: list[tuple[int, str]] = []
    for node in ast.walk(tree):
        if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
            continue
        if node.func.attr != "post":
            continue
        receiver = _receiver_name(node.func)
        if receiver in _NOT_HTTP_CLIENTS:
            continue
        findings.append((node.lineno, receiver))
    return findings


def _http_sources() -> list[Path]:
    roots = [r for r in (_AGENTS_APP, _API_APP) if r.is_dir()]
    return [p for root in roots for p in root.rglob("*.py") if "__pycache__" not in p.parts and p not in _ALLOWED_HTTP_FILES]


def test_no_raw_http_llm_calls() -> None:
    """An LLM call over raw HTTP must go through the safe wrapper too.

    This is the gate that was missing. `services/agents/app/api/explain.py`
    reached a model with `httpx.AsyncClient().post(...)` and never touched the
    contract, and every LLM call in `services/api` did the same — while the
    suite reported the contract fully enforced.
    """
    violations: list[str] = []
    for path in _http_sources():
        for lineno, receiver in _find_raw_http_llm_calls(path):
            try:
                rel = path.relative_to(_AGENTS_APP.parent.parent)
            except ValueError:  # pragma: no cover - defensive
                rel = path
            violations.append(f"{rel}:{lineno}  {receiver}.post(...) to a completions endpoint")

    assert not violations, (
        "Raw-HTTP LLM call detected — route it through "
        "safe_chat_completions_request (app.llm.contract in services/agents, "
        "app.services.llm_safety in services/api) so the input contract runs "
        "before the request rather than after it.\n  " + "\n  ".join(violations)
    )


def test_the_http_gate_detects_a_synthetic_bypass(tmp_path: Path) -> None:
    """A gate nobody has seen fail is a gate nobody knows works."""
    bad = tmp_path / "sneaky.py"
    bad.write_text(
        "import httpx\n"
        "async def go(key):\n"
        "    async with httpx.AsyncClient() as c:\n"
        '        return await c.post("https://api.openai.com/v1/chat/completions", json={})\n',
        encoding="utf-8",
    )
    assert _find_raw_http_llm_calls(bad), "the raw-HTTP walker missed an obvious bypass"


def test_the_http_gate_accepts_a_wrapped_call(tmp_path: Path) -> None:
    good = tmp_path / "fine.py"
    good.write_text(
        "from app.services.llm_safety import safe_chat_completions_request\n"
        "async def go(key):\n"
        '    return await safe_chat_completions_request(api_key=key, model="m", messages=[], url="https://x/chat/completions")\n',
        encoding="utf-8",
    )
    assert not _find_raw_http_llm_calls(good)


def test_no_direct_ainvoke_or_astream_bypass() -> None:
    """No file under services/agents/app/ may call .ainvoke/.astream directly on an LLM."""
    violations: list[str] = []
    for path in _python_sources():
        for lineno, receiver, method in _find_bypasses(path):
            rel = path.relative_to(_AGENTS_APP.parent)
            violations.append(f"{rel}:{lineno}  {receiver}.{method}(...)")

    assert not violations, (
        "Direct LLM `.ainvoke`/`.astream` call detected — route through "
        "app.llm.contract.safe_ainvoke / safe_astream / make_safe_chat_model. "
        "If the receiver is genuinely not an LLM (e.g. a LangGraph compiled "
        "graph), add its name to _ALLOWED_RECEIVERS in this test with a "
        "justification comment.\n  " + "\n  ".join(violations)
    )


def test_gate_detects_synthetic_bypass(tmp_path: Path) -> None:
    """Sanity-check the AST walker: a fake bypass file must trip the detector."""
    fake = tmp_path / "fake_agent.py"
    fake.write_text(
        "class Foo:\n    async def run(self, llm):\n        return await llm.ainvoke([{'role': 'user', 'content': 'hi'}])\n",
        encoding="utf-8",
    )
    findings = _find_bypasses(fake)
    assert findings, "AST walker failed to flag a synthetic llm.ainvoke bypass"
    assert findings[0][1] == "llm"
    assert findings[0][2] == "ainvoke"


def test_gate_respects_receiver_allowlist(tmp_path: Path) -> None:
    """Calls on whitelisted receivers (e.g. _graph) must NOT be flagged."""
    fake = tmp_path / "fake_graph.py"
    fake.write_text(
        "class Orch:\n"
        "    def __init__(self):\n"
        "        self._graph = object()\n"
        "    async def run(self):\n"
        "        return await self._graph.ainvoke({'x': 1})\n",
        encoding="utf-8",
    )
    findings = _find_bypasses(fake)
    assert findings == [], f"allowlisted receiver should not trip the gate; got {findings}"


def test_gate_detects_getattr_indirection_bypass(tmp_path: Path) -> None:
    """The classic AST-gate evasion is ``getattr(llm, "ainvoke")(...)``.

    A bare-attribute walker (only inspecting ``Attribute`` nodes) would
    happily walk past this — the outer ``Call.func`` is a ``Call`` to
    the ``getattr`` builtin, not an ``Attribute`` at all. We flag it
    with a synthetic ``<getattr>`` receiver, which is intentionally
    NOT in the allowlist so a future author can't just append to the
    allowlist to whitelist away the protection.
    """
    fake = tmp_path / "fake_getattr.py"
    fake.write_text(
        "async def sneaky(llm, msgs):\n"
        "    # Future author tries to dodge the .ainvoke attribute scan.\n"
        "    fn = getattr(llm, 'ainvoke')\n"
        "    return await fn(msgs)\n"
        "async def stream_sneaky(llm, msgs):\n"
        "    return getattr(llm, 'astream')(msgs)\n",
        encoding="utf-8",
    )
    findings = _find_bypasses(fake)
    # Note: the first form (`fn = getattr(...)`; `fn(...)`) splits the
    # getattr Call from the invocation Call, so the AST scanner sees a
    # bare `fn(...)` with no method-name signal. That's a known limit
    # of static name analysis. The second form (`getattr(llm, 'astream')(msgs)`)
    # invokes inline and MUST be flagged.
    flagged_methods = sorted({m for _, _, m in findings})
    assert "astream" in flagged_methods, f"getattr(llm, 'astream')(msgs) inline-invocation must be flagged; got {findings}"
    for _lineno, receiver, method in findings:
        if method == "astream":
            assert receiver == "<getattr>", f"getattr-indirection bypass must report '<getattr>' receiver; got {receiver}"