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.

fix(api): unshadow three routes and stop a playbook step crashing on import (#663)

Beenu Arora14fb75511bf6
diff --git a/services/agents/app/api/hunts.py b/services/agents/app/api/hunts.py
index c75dd4c3b..e5bc2ac0d 100644
--- a/services/agents/app/api/hunts.py
+++ b/services/agents/app/api/hunts.py
@@ -70,6 +70,22 @@ async def list_hunts() -> list[dict[str, Any]]:
return [_hunt_summary(h) for h in corpus.list()]
[email protected]("/runs", summary="Recent hunt runs")
+async def list_runs(
+ limit: int = Query(default=50, ge=1, le=500),
+) -> list[dict[str, Any]]:
+ return await hunt_store.list_recent_runs(limit=limit)
+
+
[email protected]("/findings", summary="Recent hunt findings")
+async def list_findings(
+ hunt_id: str | None = Query(default=None),
+ status: str | None = Query(default=None),
+ limit: int = Query(default=100, ge=1, le=500),
+) -> list[dict[str, Any]]:
+ return await hunt_store.list_recent_findings(hunt_id=hunt_id, status=status, limit=limit)
+
+
@router.get("/{hunt_id}", summary="Get a single hunt definition")
async def get_hunt(hunt_id: str) -> dict[str, Any]:
corpus = HuntCorpus.default()
@@ -104,19 +120,3 @@ async def run_hunt(hunt_id: str) -> dict[str, Any]:
# ---------------------------------------------------------------------------
# Read-side (DB-backed)
# ---------------------------------------------------------------------------
-
-
[email protected]("/runs", summary="Recent hunt runs")
-async def list_runs(
- limit: int = Query(default=50, ge=1, le=500),
-) -> list[dict[str, Any]]:
- return await hunt_store.list_recent_runs(limit=limit)
-
-
[email protected]("/findings", summary="Recent hunt findings")
-async def list_findings(
- hunt_id: str | None = Query(default=None),
- status: str | None = Query(default=None),
- limit: int = Query(default=100, ge=1, le=500),
-) -> list[dict[str, Any]]:
- return await hunt_store.list_recent_findings(hunt_id=hunt_id, status=status, limit=limit)
diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.py
index 5bf8b55fc..45faf835b 100644
--- a/services/agents/app/playbook/engine.py
+++ b/services/agents/app/playbook/engine.py
@@ -434,11 +434,32 @@ async def _handle_osquery_live_query(step: PlaybookStep, context: dict[str, Any]
timeout_seconds : int, optional
How long to wait for all hosts to respond (default: 60).
"""
- # Import clients here to avoid circular imports at module load time.
- from app.clients.aisoc_direct_client import AiSOCDirectClient # noqa: PLC0415
- from app.clients.fleetdm_client import FleetDMClient # noqa: PLC0415
- from app.clients.osctrl_client import OsctrlClient # noqa: PLC0415
- from app.clients.osquery_allowlist import AllowlistError # noqa: PLC0415
+ # These osquery clients live in `services/actions`, not in this service —
+ # `services/agents/app/clients/` does not exist. Every `osquery_live_query`
+ # step therefore died with an unhandled ModuleNotFoundError at execution
+ # time, and the `except AllowlistError` handler below referenced a name
+ # that could never bind. The NL playbook drafter actively offers this step
+ # type, so a user could author a playbook that was guaranteed to crash.
+ #
+ # Fail with an actionable message instead of a traceback. Wiring this
+ # properly means dispatching through the actions service over HTTP, the
+ # same way SIEM writeback already does, rather than importing across a
+ # service boundary that does not exist in this image.
+ try:
+ from app.clients.aisoc_direct_client import AiSOCDirectClient # noqa: PLC0415
+ from app.clients.fleetdm_client import FleetDMClient # noqa: PLC0415
+ from app.clients.osctrl_client import OsctrlClient # noqa: PLC0415
+ from app.clients.osquery_allowlist import AllowlistError # noqa: PLC0415
+ except ModuleNotFoundError as exc:
+ logger.error("playbook.osquery_clients_unavailable: %s", exc)
+ return {
+ "error": (
+ "osquery_live_query is not executable in the agents service: the "
+ "osquery backend clients ship in services/actions. Run this step "
+ "through the actions service, or remove it from the playbook."
+ ),
+ "partial": True,
+ }
backend: str = step.params.get("backend", "osctrl")
target_hosts: list[str] = step.params.get("target_hosts") or [context.get("host_id") or context.get("host", "")]
diff --git a/services/api/app/api/v1/endpoints/assets.py b/services/api/app/api/v1/endpoints/assets.py
index 2b6a8451d..adb7c61d7 100644
--- a/services/api/app/api/v1/endpoints/assets.py
+++ b/services/api/app/api/v1/endpoints/assets.py
@@ -134,6 +134,25 @@ async def create_asset(
return asset
[email protected]("/vulnerabilities", response_model=list[VulnerabilityOut])
+async def list_vulnerabilities(
+ severity: str | None = Query(None),
+ is_exploited: bool | None = Query(None),
+ limit: int = Query(50, le=500),
+ offset: int = Query(0, ge=0),
+ db: AsyncSession = Depends(get_db),
+ current_user: User = Depends(get_current_user),
+) -> list[AssetVulnerability]:
+ q = select(AssetVulnerability).where(AssetVulnerability.tenant_id == current_user.tenant_id)
+ if severity:
+ q = q.where(AssetVulnerability.severity == severity)
+ if is_exploited is not None:
+ q = q.where(AssetVulnerability.is_exploited == is_exploited)
+ q = q.order_by(AssetVulnerability.last_found.desc()).offset(offset).limit(limit)
+ result = await db.execute(q)
+ return list(result.scalars().all())
+
+
@router.get("/{asset_id}", response_model=AssetOut)
async def get_asset(
asset_id: uuid.UUID,
@@ -184,25 +203,6 @@ async def delete_asset(
# ---------------------------------------------------------------------------
[email protected]("/vulnerabilities", response_model=list[VulnerabilityOut])
-async def list_vulnerabilities(
- severity: str | None = Query(None),
- is_exploited: bool | None = Query(None),
- limit: int = Query(50, le=500),
- offset: int = Query(0, ge=0),
- db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
-) -> list[AssetVulnerability]:
- q = select(AssetVulnerability).where(AssetVulnerability.tenant_id == current_user.tenant_id)
- if severity:
- q = q.where(AssetVulnerability.severity == severity)
- if is_exploited is not None:
- q = q.where(AssetVulnerability.is_exploited == is_exploited)
- q = q.order_by(AssetVulnerability.last_found.desc()).offset(offset).limit(limit)
- result = await db.execute(q)
- return list(result.scalars().all())
-
-
@router.post("/vulnerabilities", response_model=VulnerabilityOut, status_code=status.HTTP_201_CREATED)
async def create_vulnerability(
body: VulnerabilityCreate,
diff --git a/services/api/tests/test_route_shadowing.py b/services/api/tests/test_route_shadowing.py
new file mode 100644
index 000000000..432cf56db
--- /dev/null
+++ b/services/api/tests/test_route_shadowing.py
@@ -0,0 +1,90 @@
+"""No literal route may be shadowed by an earlier parameterised route.
+
+FastAPI matches routes in registration order. If ``GET /{asset_id}`` is
+registered before ``GET /vulnerabilities``, then a request for
+``/assets/vulnerabilities`` is matched by the first route, fails to parse
+"vulnerabilities" as a UUID, and returns 422 — the literal handler is simply
+unreachable, and nothing in CI noticed because both routes exist and both have
+tests that call them directly.
+
+That is exactly what had happened to ``GET /api/v1/assets/vulnerabilities``.
+
+This is a generic structural check rather than a test of one endpoint, because
+the failure mode is easy to reintroduce and invisible in review: the two route
+declarations are usually tens of lines apart and each looks correct on its own.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi.routing import APIRoute
+
+
+#: A path segment that is a literal, not a ``{param}`` placeholder.
+def _segments(path: str) -> list[str]:
+ return [s for s in path.split("/") if s]
+
+
+def _is_param(segment: str) -> bool:
+ return segment.startswith("{") and segment.endswith("}")
+
+
+def _shadows(earlier: str, later: str) -> bool:
+ """True if a request for ``later`` would be captured by ``earlier``.
+
+ Only meaningful when the two have the same segment count and every
+ differing segment in ``earlier`` is a parameter.
+ """
+ a, b = _segments(earlier), _segments(later)
+ if len(a) != len(b):
+ return False
+ saw_param_over_literal = False
+ for seg_a, seg_b in zip(a, b, strict=True):
+ if seg_a == seg_b:
+ continue
+ if _is_param(seg_a) and not _is_param(seg_b):
+ saw_param_over_literal = True
+ continue
+ return False
+ return saw_param_over_literal
+
+
+def test_no_literal_route_is_shadowed_by_an_earlier_parameterised_route():
+ # Importing the app pulls the full driver stack (neo4j, clickhouse, ...).
+ # CI installs those; a bare checkout may not, and the helper tests below
+ # still give useful signal there.
+ app = pytest.importorskip("app.main", reason="full app dependencies not installed").app
+ routes = [r for r in app.routes if isinstance(r, APIRoute)]
+
+ problems: list[str] = []
+ for i, later in enumerate(routes):
+ for earlier in routes[:i]:
+ shared_methods = earlier.methods & later.methods
+ if not shared_methods:
+ continue
+ if _shadows(earlier.path, later.path):
+ problems.append(
+ f"{sorted(shared_methods)} {later.path} is unreachable: "
+ f"{earlier.path} is registered first and will match it. "
+ f"Move the literal route above the parameterised one."
+ )
+
+ assert not problems, "shadowed routes found:\n " + "\n ".join(problems)
+
+
+ ("earlier", "later", "expected"),
+ [
+ ("/assets/{asset_id}", "/assets/vulnerabilities", True),
+ ("/hunts/{hunt_id}", "/hunts/runs", True),
+ # Different arity cannot shadow.
+ ("/assets/{asset_id}", "/assets/{asset_id}/vulnerabilities", False),
+ # Literal-before-literal is fine.
+ ("/assets/summary", "/assets/vulnerabilities", False),
+ # A parameter in the *later* path is not shadowed by a literal.
+ ("/assets/vulnerabilities", "/assets/{asset_id}", False),
+ ],
+)
+def test_shadow_detection_itself(earlier: str, later: str, expected: bool):
+ """The helper has to be right or the gate above is worthless."""
+ assert _shadows(earlier, later) is expected