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.

6.5 KB
Raw Blame
"""Tenable findings reach the vulnerability table, so KEV exposure has data.

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

What was wrong
--------------
`asset_vulnerabilities` had exactly one writer in the whole tree:
`POST /api/v1/assets/vulnerabilities`, a route a human calls by hand. The
Tenable connector -- the only vulnerability scanner AiSOC integrates -- modelled
its findings as **alerts** and never wrote a vulnerability row.

`_tenant_has_vulnerability_data` in `kev_exposure.py` exists precisely to tell
"you are not exposed" apart from "nobody has told me what you run", and it
queries that table. So for any tenant whose vulnerability data came from
Tenable, KEV exposure answered *"no vulnerability data"* forever, however many
findings the connector had polled.

The data was not merely unwritten, it was never fetched: `fetch_alerts` calls
`/workbenches/vulnerabilities`, which returns plugin-level aggregates carrying
neither a CVE nor an asset. `normalize()` sets `host: None` outright. A row in
`asset_vulnerabilities` needs an asset and a CVE, and the connector asked
Tenable for neither.

What this file asserts
----------------------
The connector against a stubbed Tenable: that it asks for per-asset findings
and for the plugin details that carry CVEs, and that it emits findings a
vulnerability row can be built from. The fan-out is capped, because a plugin
list of any size would otherwise become one HTTP request per plugin against a
customer's scanner.
"""

from __future__ import annotations

import pytest


def _connector():
    from app.connectors.tenable import TenableConnector

    return TenableConnector(
        access_key="ak-test",
        secret_key="sk-test",
    )


class _StubTenable:
    """Enough of Tenable.io to answer the three calls the connector makes."""

    def __init__(self) -> None:
        self.paths: list[str] = []

    async def get(self, url: str, **_: object):
        self.paths.append(url)

        if url.endswith("/workbenches/assets/vulnerabilities"):
            return _Response(
                200,
                {
                    "assets": [
                        {
                            "id": "asset-1",
                            "fqdn": ["web-01.corp.example"],
                            "ipv4": ["198.51.100.10"],
                            "severities": [{"name": "critical", "count": 2}],
                            "vulnerabilities": [
                                {"plugin_id": 12345, "severity": 4, "count": 1},
                                {"plugin_id": 67890, "severity": 3, "count": 1},
                            ],
                        }
                    ]
                },
            )

        if "/plugins/plugin/12345" in url:
            return _Response(
                200,
                {
                    "id": 12345,
                    "name": "Log4Shell",
                    "attributes": [
                        {"attribute_name": "cve", "attribute_value": "CVE-2021-44228"},
                        {"attribute_name": "cvss3_base_score", "attribute_value": "10.0"},
                    ],
                },
            )

        if "/plugins/plugin/67890" in url:
            return _Response(
                200,
                {
                    "id": 67890,
                    "name": "Some other finding",
                    "attributes": [{"attribute_name": "cve", "attribute_value": "CVE-2023-1111"}],
                },
            )

        return _Response(404, {})


class _Response:
    def __init__(self, status_code: int, payload: dict) -> None:
        self.status_code = status_code
        self._payload = payload
        self.text = str(payload)

    def json(self) -> dict:
        return self._payload


@pytest.fixture
def stubbed(monkeypatch):
    stub = _StubTenable()

    class _Client:
        async def __aenter__(self):
            return stub

        async def __aexit__(self, *_):
            return False

    monkeypatch.setattr("app.connectors.tenable.httpx.AsyncClient", lambda **_: _Client())
    return stub


class TestItAsksTenableForWhatAVulnerabilityRowNeeds:
    @pytest.mark.asyncio
    async def test_it_fetches_per_asset_findings(self, stubbed) -> None:
        """`/workbenches/vulnerabilities` returns plugin aggregates with no
        asset at all, so no row could ever name what is affected."""
        await _connector().fetch_vulnerability_findings()

        assert any("/workbenches/assets/vulnerabilities" in p for p in stubbed.paths), (
            f"never asked for per-asset findings; called {stubbed.paths}"
        )

    @pytest.mark.asyncio
    async def test_it_fetches_the_plugin_details_that_carry_cves(self, stubbed) -> None:
        """A KEV entry is a CVE. Tenable publishes the CVE list on the plugin,
        not on the workbench row, so without this call every finding is
        anonymous and `check_exposure` can match nothing."""
        await _connector().fetch_vulnerability_findings()

        assert any("/plugins/plugin/12345" in p for p in stubbed.paths), f"never asked for plugin details; called {stubbed.paths}"


class TestTheFindingsCanBecomeRows:
    @pytest.mark.asyncio
    async def test_each_finding_names_an_asset_and_a_cve(self, stubbed) -> None:
        findings = await _connector().fetch_vulnerability_findings()

        assert findings, "no findings produced from a workbench with two"
        log4shell = next((f for f in findings if f["cve_id"] == "CVE-2021-44228"), None)
        assert log4shell is not None, f"the Log4Shell finding is missing: {findings}"
        assert log4shell["hostname"] == "web-01.corp.example"
        assert log4shell["severity"] == "critical"

    @pytest.mark.asyncio
    async def test_the_severity_ladder_is_preserved(self, stubbed) -> None:
        """Tenable's 4 is Critical. Collapsing it into `high` is the defect the
        connector conventions call out by name."""
        findings = await _connector().fetch_vulnerability_findings()

        assert {f["severity"] for f in findings} == {"critical", "high"}

    @pytest.mark.asyncio
    async def test_the_plugin_fan_out_is_capped(self, monkeypatch) -> None:
        """The negative control on cost. One request per plugin against a
        customer's scanner is a denial of service aimed at the customer, so an
        unbounded loop here is worse than no feature."""
        from app.connectors import tenable

        assert isinstance(tenable.MAX_PLUGIN_LOOKUPS, int)
        assert 0 < tenable.MAX_PLUGIN_LOOKUPS <= 200, f"MAX_PLUGIN_LOOKUPS is {tenable.MAX_PLUGIN_LOOKUPS}; that is not a cap"