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.

feat(actions): live-query playbook step — osctrl, FleetDM, aisoc-direct stub

Beenud931b7f37557
diff --git a/apps/docs/docs/connectors/fleetdm.md b/apps/docs/docs/connectors/fleetdm.md
index 948ed8209..f4f8cafb7 100644
--- a/apps/docs/docs/connectors/fleetdm.md
+++ b/apps/docs/docs/connectors/fleetdm.md
@@ -85,3 +85,69 @@ Identical table-driven mapping as the [osctrl connector](/docs/connectors/osctrl
- [osctrl](/docs/connectors/osctrl) — alternative open-source fleet manager.
- [Detection coverage](/docs/detections/coverage) — endpoint rules that fire on osquery data.
+
+## Live-query response actions (playbook step)
+
+The `osquery_live_query` playbook step supports FleetDM as a backend,
+dispatching live campaigns via Fleet's distributed-query API.
+
+### Playbook step schema
+
+```yaml
+- id: triage-logged-users
+ name: "Get logged-in users from affected host"
+ type: osquery_live_query
+ params:
+ backend: fleetdm
+ base_url: "https://fleet.corp.example.com"
+ api_token: "{{ secrets.fleetdm_token }}" # or use username/password below
+ # username: admin
+ # password: "{{ secrets.fleetdm_password }}"
+ template: logged_in_users
+ target_hosts:
+ - "{{ alert.host }}"
+ timeout_seconds: 60
+```
+
+### Authentication
+
+FleetDM supports two credential modes:
+
+| Mode | Params |
+|---|---|
+| API token | `api_token` |
+| User / password | `username` + `password` (token fetched automatically via `/api/v1/fleet/login`) |
+
+The client will authenticate on first use and reuse the token for the duration
+of the step.
+
+### Supported templates
+
+Same allowlist as the osctrl backend — see the
+[osctrl connector](/docs/connectors/osctrl#supported-templates) for the full
+table. Templates are backend-agnostic; only the `backend:` key selects the
+fleet manager.
+
+### Result shape
+
+```json
+{
+ "results": {
+ "hostname-a": [{"user": "root", "type": "user", "host": "hostname-a"}]
+ },
+ "partial": false,
+ "timed_out_hosts": []
+}
+```
+
+### When to choose FleetDM vs osctrl
+
+| Concern | FleetDM | osctrl |
+|---|---|---|
+| Community / ecosystem | Larger | Smaller |
+| Multi-tenant isolation | Teams (paid tier for strict isolation) | Native environments (OSS) |
+| Infra footprint | MySQL + Redis | PostgreSQL only |
+| AiSOC stack alignment | Needs extra deps | Native fit |
+
+Both backends are fully supported — choose based on your existing fleet
+management deployment.
diff --git a/apps/docs/docs/connectors/osctrl.md b/apps/docs/docs/connectors/osctrl.md
index ac8196d40..24cc62331 100644
--- a/apps/docs/docs/connectors/osctrl.md
+++ b/apps/docs/docs/connectors/osctrl.md
@@ -86,3 +86,64 @@ the defaults stable so detection authors have a predictable substrate.
- [FleetDM](/docs/connectors/fleetdm) — alternative osquery fleet manager with a similar event shape.
- [Detection coverage](/docs/detections/coverage) — endpoint rules that fire on osquery data.
+
+## Live-query response actions (playbook step)
+
+The `osquery_live_query` playbook step dispatches an on-demand osquery
+distributed query to one or more hosts via osctrl's distributed-query API.
+Responses are polled and returned as structured rows, enabling IR triage
+("get all running processes on this host right now") directly inside
+AiSOC playbooks.
+
+### Playbook step schema
+
+```yaml
+- id: triage-running-procs
+ name: "Get running processes from affected host"
+ type: osquery_live_query
+ params:
+ backend: osctrl
+ base_url: "https://osctrl.corp.example.com"
+ environment: production # osctrl environment name
+ api_token: "{{ secrets.osctrl_token }}"
+ template: running_processes # must be an approved allowlist template
+ template_params:
+ limit: 100
+ target_hosts:
+ - "{{ alert.host }}"
+ timeout_seconds: 60 # optional, default 60
+```
+
+### Supported templates
+
+| Template | SQL intent |
+|---|---|
+| `running_processes` | `SELECT * FROM processes LIMIT :limit` |
+| `active_connections` | `SELECT * FROM process_open_sockets WHERE state='ESTABLISHED'` |
+| `logged_in_users` | `SELECT * FROM logged_in_users` |
+| `recently_modified_files` | `SELECT * FROM file WHERE path LIKE '/tmp/%' AND mtime > :since` |
+| `listening_ports` | `SELECT * FROM listening_ports` |
+
+Only templates in the allowlist can be executed — raw SQL injection is rejected
+at the `AllowlistError` boundary before any network call is made.
+
+### Result shape
+
+```json
+{
+ "results": {
+ "hostname-a": [{"pid": "1234", "name": "bash", "cmdline": "..."}],
+ "hostname-b": []
+ },
+ "partial": false,
+ "timed_out_hosts": []
+}
+```
+
+`partial: true` is set when at least one target host did not respond within
+`timeout_seconds`.
+
+### Credentials
+
+Store the osctrl API token in the AiSOC secrets store and reference it with
+`{{ secrets.osctrl_token }}` in the playbook YAML. Never hard-code tokens.
diff --git a/services/actions/app/clients/aisoc_direct_client.py b/services/actions/app/clients/aisoc_direct_client.py
new file mode 100644
index 000000000..af677a68c
--- /dev/null
+++ b/services/actions/app/clients/aisoc_direct_client.py
@@ -0,0 +1,95 @@
+"""Stub async client for the AiSOC-direct osquery TLS endpoint.
+
+This module satisfies the ``osquery_live_query`` playbook step contract in
+PR 3 so that playbooks can reference ``backend: aisoc_direct`` without any
+implementation yet. The full implementation (including HTTP calls to the
+``services/osquery-tls`` FastAPI service) will land in PR 4 once that service
+is built.
+
+Attempting to call :meth:`AiSOCDirectClient.live_query` in this stub will
+raise :class:`NotImplementedError` with a descriptive message. This surfaces
+clearly in playbook dry-runs and CI before PR 4 ships.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.clients.osquery_allowlist import AllowlistError, render_query
+
+
+class AiSOCDirectError(RuntimeError):
+ """Raised when an aisoc-direct API call fails."""
+
+
+class AiSOCDirectClient:
+ """Stub client for the AiSOC built-in osquery TLS endpoint.
+
+ .. note::
+
+ **This is a PR-3 stub.** The HTTP implementation will be added in PR 4
+ once ``services/osquery-tls/`` is available.
+
+ Parameters
+ ----------
+ base_url:
+ Root URL of the ``services/osquery-tls`` FastAPI service, e.g.
+ ``http://osquery-tls:8080``. Ignored by the stub; preserved for
+ interface compatibility with the real implementation.
+ api_token:
+ Bearer token for the osquery-tls service. Ignored by the stub.
+ verify_tls:
+ Whether to verify TLS. Ignored by the stub.
+ poll_interval:
+ Polling cadence in seconds. Ignored by the stub.
+ """
+
+ def __init__(
+ self,
+ base_url: str,
+ api_token: str,
+ verify_tls: bool = True,
+ poll_interval: float = 3.0,
+ ) -> None:
+ self._base_url = base_url.rstrip("/")
+ self._api_token = api_token
+ self._verify_tls = verify_tls
+ self._poll_interval = poll_interval
+
+ async def live_query(
+ self,
+ target_hosts: list[str],
+ template: str,
+ template_params: dict[str, Any] | None = None,
+ timeout_seconds: int = 60,
+ ) -> dict[str, Any]:
+ """Stub — always raises :class:`NotImplementedError`.
+
+ Parameters
+ ----------
+ target_hosts:
+ List of target host identifiers.
+ template:
+ Allowlist template ID (validated before the stub error is raised).
+ template_params:
+ Optional template parameters.
+ timeout_seconds:
+ Timeout; ignored by the stub.
+
+ Raises
+ ------
+ AllowlistError
+ If *template* is not in the approved allowlist (validated eagerly
+ so that bad calls are caught even before PR 4 ships).
+ NotImplementedError
+ Always — the real implementation is forthcoming in PR 4.
+ """
+ params = template_params or {}
+ # Validate allowlist eagerly; surfaces misconfigurations early.
+ render_query(template, **params)
+
+ raise NotImplementedError(
+ "AiSOCDirectClient.live_query is a PR-3 stub. "
+ "The full implementation will be added in PR 4 once "
+ "services/osquery-tls/ is available."
+ )
diff --git a/services/actions/app/clients/fleetdm_client.py b/services/actions/app/clients/fleetdm_client.py
new file mode 100644
index 000000000..2ce6c8c4d
--- /dev/null
+++ b/services/actions/app/clients/fleetdm_client.py
@@ -0,0 +1,287 @@
+"""Async client for the FleetDM REST API — live distributed queries.
+
+FleetDM is a popular open-source device management platform built on osquery.
+API reference: https://fleetdm.com/docs/rest-api/rest-api
+
+Supported operations
+---------------------
+- ``live_query``: Create a live-query campaign, poll for results, then cancel.
+
+All SQL must come from :mod:`app.clients.osquery_allowlist`; callers pass a
+``template`` ID and optional ``template_params`` rather than raw SQL.
+
+Authentication
+--------------
+FleetDM uses a session token obtained by POSTing credentials to
+``/api/v1/fleet/login`` and then passing the token in the
+``Authorization: Bearer <token>`` header. This client accepts either:
+
+* ``api_token`` — a pre-issued API token (preferred; no login needed).
+* ``username`` + ``password`` — session-based auth (fallback).
+
+Endpoints used
+--------------
+POST /api/v1/fleet/queries/run → start campaign, get campaign_id
+GET /api/v1/fleet/queries/run/{campaign_id} → stream results
+DELETE /api/v1/fleet/queries/run/{campaign_id} → cancel when done
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+import httpx
+
+from app.clients.osquery_allowlist import AllowlistError, render_query
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_POLL_INTERVAL = 3.0
+_DEFAULT_TIMEOUT = 60
+
+
+class FleetDMError(RuntimeError):
+ """Raised when a FleetDM API call fails."""
+
+
+class FleetDMClient:
+ """Thin async wrapper over the FleetDM REST API for live distributed queries.
+
+ Parameters
+ ----------
+ base_url:
+ Root URL of the FleetDM server, e.g. ``https://fleet.example.com``.
+ api_token:
+ Pre-issued FleetDM API token. If omitted, supply *username* and
+ *password* for session-based authentication.
+ username:
+ FleetDM username (used only when *api_token* is ``None``).
+ password:
+ FleetDM password (used only when *api_token* is ``None``).
+ verify_tls:
+ Whether to verify the server's TLS certificate.
+ poll_interval:
+ Seconds between result-polling attempts.
+ """
+
+ def __init__(
+ self,
+ base_url: str,
+ api_token: str | None = None,
+ username: str | None = None,
+ password: str | None = None,
+ verify_tls: bool = True,
+ poll_interval: float = _DEFAULT_POLL_INTERVAL,
+ ) -> None:
+ if not api_token and not (username and password):
+ raise ValueError(
+ "FleetDMClient requires either api_token or (username, password)."
+ )
+ self._base_url = base_url.rstrip("/")
+ self._api_token = api_token
+ self._username = username
+ self._password = password
+ self._verify_tls = verify_tls
+ self._poll_interval = poll_interval
+ self._session_token: str | None = None
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ async def live_query(
+ self,
+ target_hosts: list[str],
+ template: str,
+ template_params: dict[str, Any] | None = None,
+ timeout_seconds: int = _DEFAULT_TIMEOUT,
+ ) -> dict[str, Any]:
+ """Submit a live-query campaign and return results keyed by hostname.
+
+ Parameters
+ ----------
+ target_hosts:
+ List of FleetDM host identifiers (UUIDs or hostnames).
+ template:
+ Template ID from :mod:`app.clients.osquery_allowlist`.
+ template_params:
+ Optional keyword arguments forwarded to :func:`render_query`.
+ timeout_seconds:
+ How long to wait for all hosts to respond.
+
+ Returns
+ -------
+ dict
+ ``{"results": {hostname: [row, ...]}, "partial": bool}``
+
+ Raises
+ ------
+ AllowlistError
+ If *template* is not in the approved allowlist.
+ FleetDMError
+ If the FleetDM API returns an unexpected HTTP status.
+ """
+ params = template_params or {}
+ try:
+ sql = render_query(template, **params)
+ except AllowlistError:
+ logger.warning("fleetdm live_query rejected: template=%s params=%s", template, params)
+ raise
+
+ async with self._client() as http:
+ await self._ensure_auth(http)
+ campaign_id = await self._create_campaign(http, sql, target_hosts)
+ logger.info(
+ "FleetDM campaign created",
+ extra={"campaign_id": campaign_id, "hosts": target_hosts},
+ )
+
+ try:
+ return await self._poll_campaign(
+ http,
+ campaign_id,
+ expected_hosts=set(target_hosts),
+ timeout=timeout_seconds,
+ )
+ finally:
+ await self._cancel_campaign(http, campaign_id)
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _client(self) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ verify=self._verify_tls,
+ follow_redirects=True,
+ timeout=httpx.Timeout(30.0),
+ )
+
+ def _auth_headers(self) -> dict[str, str]:
+ token = self._api_token or self._session_token
+ if not token:
+ return {}
+ return {"Authorization": f"Bearer {token}"}
+
+ async def _ensure_auth(self, http: httpx.AsyncClient) -> None:
+ """Obtain a session token if we don't already have one."""
+ if self._api_token or self._session_token:
+ return
+
+ url = f"{self._base_url}/api/v1/fleet/login"
+ resp = await http.post(
+ url,
+ json={"email": self._username, "password": self._password},
+ )
+ if resp.status_code != 200:
+ raise FleetDMError(
+ f"FleetDM login failed: HTTP {resp.status_code} — {resp.text[:300]}"
+ )
+ data = resp.json()
+ token = data.get("token") or (data.get("user") or {}).get("token")
+ if not token:
+ raise FleetDMError(f"FleetDM login returned no token: {data}")
+ self._session_token = token
+
+ async def _create_campaign(
+ self,
+ http: httpx.AsyncClient,
+ sql: str,
+ target_hosts: list[str],
+ ) -> str:
+ """POST /api/v1/fleet/queries/run and return campaign ID."""
+ url = f"{self._base_url}/api/v1/fleet/queries/run"
+ payload: dict[str, Any] = {
+ "query": sql,
+ "selected": {"hosts": target_hosts},
+ }
+ resp = await http.post(url, json=payload, headers=self._auth_headers())
+ if resp.status_code not in (200, 201):
+ raise FleetDMError(
+ f"FleetDM campaign creation failed: HTTP {resp.status_code} — {resp.text[:300]}"
+ )
+ data = resp.json()
+ campaign = data.get("campaign") or data
+ campaign_id = str(
+ campaign.get("id")
+ or campaign.get("campaign_id")
+ or campaign.get("uuid")
+ or ""
+ )
+ if not campaign_id:
+ raise FleetDMError(f"FleetDM returned no campaign ID: {data}")
+ return campaign_id
+
+ async def _poll_campaign(
+ self,
+ http: httpx.AsyncClient,
+ campaign_id: str,
+ expected_hosts: set[str],
+ timeout: int,
+ ) -> dict[str, Any]:
+ """Poll GET /api/v1/fleet/queries/run/{campaign_id} until done."""
+ url = f"{self._base_url}/api/v1/fleet/queries/run/{campaign_id}"
+ deadline = asyncio.get_event_loop().time() + timeout
+ results: dict[str, list[dict[str, Any]]] = {}
+ responded: set[str] = set()
+
+ while True:
+ remaining = deadline - asyncio.get_event_loop().time()
+ if remaining <= 0:
+ logger.warning(
+ "FleetDM poll timeout: campaign_id=%s responded=%s/%s",
+ campaign_id,
+ len(responded),
+ len(expected_hosts),
+ )
+ return {"results": results, "partial": True}
+
+ resp = await http.get(url, headers=self._auth_headers())
+ if resp.status_code == 404:
+ await asyncio.sleep(min(self._poll_interval, remaining))
+ continue
+ if resp.status_code != 200:
+ raise FleetDMError(
+ f"FleetDM campaign poll failed: HTTP {resp.status_code} — {resp.text[:300]}"
+ )
+
+ data = resp.json()
+ # FleetDM returns {results: [{host: {...}, rows: [...]}, ...]}
+ for item in data.get("results") or (data if isinstance(data, list) else []):
+ host_info = item.get("host") or {}
+ node = (
+ host_info.get("hostname")
+ or host_info.get("uuid")
+ or item.get("hostname")
+ or "unknown"
+ )
+ rows = item.get("rows") or []
+ if node not in results:
+ results[node] = []
+ results[node].extend(rows)
+ responded.add(node)
+
+ if expected_hosts and responded >= expected_hosts:
+ logger.info("FleetDM campaign %s: all hosts responded", campaign_id)
+ return {"results": results, "partial": False}
+
+ # Check campaign status to avoid polling a finished campaign.
+ status = (data.get("campaign") or data).get("status") or ""
+ if status in ("finished", "complete", "error"):
+ return {"results": results, "partial": responded < expected_hosts}
+
+ await asyncio.sleep(min(self._poll_interval, remaining))
+
+ async def _cancel_campaign(
+ self,
+ http: httpx.AsyncClient,
+ campaign_id: str,
+ ) -> None:
+ """DELETE /api/v1/fleet/queries/run/{campaign_id} — best-effort cleanup."""
+ url = f"{self._base_url}/api/v1/fleet/queries/run/{campaign_id}"
+ try:
+ await http.delete(url, headers=self._auth_headers())
+ except Exception as exc: # noqa: BLE001
+ logger.debug("FleetDM campaign cancel failed (ignored): %s", exc)
diff --git a/services/actions/app/clients/osctrl_client.py b/services/actions/app/clients/osctrl_client.py
new file mode 100644
index 000000000..5dd0dbb49
--- /dev/null
+++ b/services/actions/app/clients/osctrl_client.py
@@ -0,0 +1,224 @@
+"""Async client for the osctrl REST API — live distributed queries.
+
+osctrl is an open-source TLS server for osquery fleets.
+API reference: https://github.com/jmpsec/osctrl
+
+Supported operations
+---------------------
+- ``live_query``: Submit a distributed osquery SQL template to one or more
+ hosts in a named environment and poll for results until all hosts respond or
+ the timeout elapses.
+
+All SQL must come from :mod:`app.clients.osquery_allowlist`; callers pass a
+``template`` ID and optional ``template_params`` rather than raw SQL.
+
+Authentication
+--------------
+osctrl uses a static Bearer token (``Authorization: Bearer <api_token>``).
+
+Endpoints used
+--------------
+POST /api/v1/queries/{environment}
+GET /api/v1/queries/{environment}/{query_id}/results
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+import httpx
+
+from app.clients.osquery_allowlist import AllowlistError, render_query
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_POLL_INTERVAL = 3.0 # seconds between result-polling retries
+_DEFAULT_TIMEOUT = 60 # seconds before we stop polling
+_MAX_REDIRECT = 5
+
+
+class OsctrlError(RuntimeError):
+ """Raised when an osctrl API call fails."""
+
+
+class OsctrlClient:
+ """Thin async wrapper over the osctrl REST API for live distributed queries.
+
+ Parameters
+ ----------
+ base_url:
+ Root URL of the osctrl admin server, e.g. ``https://osctrl.example.com``.
+ environment:
+ The osctrl environment name that owns the target fleet.
+ api_token:
+ Static Bearer token issued by osctrl.
+ verify_tls:
+ Whether to verify the server's TLS certificate. Set to ``False`` only
+ for local development with self-signed certs.
+ poll_interval:
+ Seconds to wait between result-polling attempts.
+ """
+
+ def __init__(
+ self,
+ base_url: str,
+ environment: str,
+ api_token: str,
+ verify_tls: bool = True,
+ poll_interval: float = _DEFAULT_POLL_INTERVAL,
+ ) -> None:
+ self._base_url = base_url.rstrip("/")
+ self._environment = environment
+ self._api_token = api_token
+ self._verify_tls = verify_tls
+ self._poll_interval = poll_interval
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ async def live_query(
+ self,
+ target_hosts: list[str],
+ template: str,
+ template_params: dict[str, Any] | None = None,
+ timeout_seconds: int = _DEFAULT_TIMEOUT,
+ ) -> dict[str, Any]:
+ """Submit a distributed query and return results keyed by hostname.
+
+ Parameters
+ ----------
+ target_hosts:
+ List of osctrl node UUIDs or hostnames to target.
+ template:
+ Template ID from :mod:`app.clients.osquery_allowlist`.
+ template_params:
+ Optional keyword arguments forwarded to :func:`render_query`.
+ timeout_seconds:
+ How long (in wall-clock seconds) to wait for all hosts to respond.
+
+ Returns
+ -------
+ dict
+ ``{"results": {hostname: [row, ...]}, "partial": bool}``
+
+ ``partial`` is ``True`` when the timeout elapsed before all hosts
+ responded.
+
+ Raises
+ ------
+ AllowlistError
+ If *template* is not in the approved allowlist.
+ OsctrlError
+ If the osctrl API returns an unexpected HTTP status.
+ asyncio.TimeoutError
+ If *timeout_seconds* elapses before any results arrive.
+ """
+ params = template_params or {}
+ try:
+ sql = render_query(template, **params)
+ except AllowlistError:
+ logger.warning("osctrl live_query rejected: template=%s params=%s", template, params)
+ raise
+
+ async with self._client() as http:
+ query_id = await self._submit_query(http, sql, target_hosts)
+ logger.info(
+ "osctrl distributed query submitted",
+ extra={"query_id": query_id, "env": self._environment, "hosts": target_hosts},
+ )
+
+ return await self._poll_results(
+ http, query_id, expected_hosts=set(target_hosts), timeout=timeout_seconds
+ )
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _client(self) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ headers={"Authorization": f"Bearer {self._api_token}"},
+ verify=self._verify_tls,
+ follow_redirects=True,
+ timeout=httpx.Timeout(30.0),
+ )
+
+ async def _submit_query(
+ self,
+ http: httpx.AsyncClient,
+ sql: str,
+ target_hosts: list[str],
+ ) -> str:
+ """POST to /api/v1/queries/{env} and return the query UUID."""
+ url = f"{self._base_url}/api/v1/queries/{self._environment}"
+ payload: dict[str, Any] = {
+ "query": sql,
+ "targets": [{"type": "nodes", "list": target_hosts}],
+ }
+
+ resp = await http.post(url, json=payload)
+ if resp.status_code not in (200, 201):
+ raise OsctrlError(
+ f"osctrl query submission failed: HTTP {resp.status_code} — {resp.text[:300]}"
+ )
+
+ data = resp.json()
+ query_id: str | None = (
+ data.get("id") or data.get("query_id") or data.get("uuid")
+ )
+ if not query_id:
+ raise OsctrlError(f"osctrl returned no query ID in response: {data}")
+ return str(query_id)
+
+ async def _poll_results(
+ self,
+ http: httpx.AsyncClient,
+ query_id: str,
+ expected_hosts: set[str],
+ timeout: int,
+ ) -> dict[str, Any]:
+ """Poll GET /api/v1/queries/{env}/{query_id}/results until complete."""
+ url = f"{self._base_url}/api/v1/queries/{self._environment}/{query_id}/results"
+ deadline = asyncio.get_event_loop().time() + timeout
+ results: dict[str, list[dict[str, Any]]] = {}
+ responded: set[str] = set()
+
+ while True:
+ remaining = deadline - asyncio.get_event_loop().time()
+ if remaining <= 0:
+ logger.warning(
+ "osctrl poll timeout: query_id=%s responded=%s/%s",
+ query_id,
+ len(responded),
+ len(expected_hosts),
+ )
+ return {"results": results, "partial": True}
+
+ resp = await http.get(url)
+ if resp.status_code == 404:
+ # Query not yet available on the server — wait and retry.
+ await asyncio.sleep(min(self._poll_interval, remaining))
+ continue
+ if resp.status_code != 200:
+ raise OsctrlError(
+ f"osctrl result poll failed: HTTP {resp.status_code} — {resp.text[:300]}"
+ )
+
+ data = resp.json()
+ # osctrl returns a list of result objects, each with "node" and "rows".
+ for item in data if isinstance(data, list) else data.get("results", []):
+ node = item.get("node") or item.get("hostname") or item.get("uuid", "unknown")
+ rows = item.get("rows") or item.get("data") or []
+ if node not in results:
+ results[node] = []
+ results[node].extend(rows)
+ responded.add(node)
+
+ if expected_hosts and responded >= expected_hosts:
+ logger.info("osctrl query %s: all hosts responded", query_id)
+ return {"results": results, "partial": False}
+
+ await asyncio.sleep(min(self._poll_interval, remaining))
diff --git a/services/actions/app/clients/osquery_allowlist.py b/services/actions/app/clients/osquery_allowlist.py
new file mode 100644
index 000000000..7a9030015
--- /dev/null
+++ b/services/actions/app/clients/osquery_allowlist.py
@@ -0,0 +1,213 @@
+"""Read-only parameterised osquery SQL templates.
+
+Playbook steps reference templates by ID rather than passing raw SQL directly to
+osctrl / FleetDM / aisoc-direct. This ensures that the only queries that can be
+executed on remote hosts via a playbook are those that have been reviewed and
+approved here.
+
+Usage
+-----
+ from app.clients.osquery_allowlist import render_query, TEMPLATES
+
+ sql = render_query("running_processes", pid=1234) # KeyError if unknown template
+ sql = render_query("active_connections") # no params needed
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+# ---------------------------------------------------------------------------
+# Template registry
+# ---------------------------------------------------------------------------
+
+# Each value is a SQL template string. Python's str.format_map() is used for
+# parameter substitution; callers supply keyword arguments which are validated
+# against the parameter spec before interpolation.
+#
+# Rules for adding templates:
+# 1. SQL must use parameterised placeholders in the form {param_name}.
+# 2. The companion PARAM_SPECS entry must list every placeholder name.
+# 3. No DML (INSERT/UPDATE/DELETE) or DDL (CREATE/DROP/ALTER) is allowed.
+# 4. Subqueries must not invoke osquery attach or join against .autoload tables
+# that modify host state.
+
+TEMPLATES: dict[str, str] = {
+ "running_processes": (
+ "SELECT pid, name, path, cmdline, uid, gid, start_time, "
+ "parent AS ppid, on_disk "
+ "FROM processes "
+ "ORDER BY start_time DESC "
+ "LIMIT {limit};"
+ ),
+ "active_connections": (
+ "SELECT pid, fd, socket, remote_address, remote_port, "
+ "local_address, local_port, protocol, state "
+ "FROM process_open_sockets "
+ "WHERE remote_address != '' "
+ "AND remote_port != 0 "
+ "LIMIT {limit};"
+ ),
+ "logged_in_users": (
+ "SELECT type, user, host, tty, time "
+ "FROM logged_in_users "
+ "ORDER BY time DESC "
+ "LIMIT {limit};"
+ ),
+ "recent_files": (
+ "SELECT path, directory, filename, size, type, "
+ "atime, mtime, ctime, uid, gid "
+ "FROM file "
+ "WHERE directory = '{directory}' "
+ "LIMIT {limit};"
+ ),
+ "process_tree": (
+ "WITH RECURSIVE proctree(pid, ppid, name, path, cmdline, depth) AS ( "
+ " SELECT pid, parent AS ppid, name, path, cmdline, 0 AS depth "
+ " FROM processes "
+ " WHERE pid = {pid} "
+ " UNION ALL "
+ " SELECT p.pid, p.parent, p.name, p.path, p.cmdline, pt.depth + 1 "
+ " FROM processes p "
+ " JOIN proctree pt ON p.parent = pt.pid "
+ " WHERE pt.depth < {max_depth} "
+ ") "
+ "SELECT pid, ppid, name, path, cmdline, depth "
+ "FROM proctree "
+ "ORDER BY depth, pid;"
+ ),
+ "package_inventory": (
+ "SELECT name, version, source, "
+ "COALESCE(arch, '') AS arch "
+ "FROM deb_packages "
+ "UNION ALL "
+ "SELECT name, version, source, arch "
+ "FROM rpm_packages "
+ "UNION ALL "
+ "SELECT name, version, 'homebrew' AS source, '' AS arch "
+ "FROM homebrew_packages "
+ "LIMIT {limit};"
+ ),
+}
+
+# Default values for optional parameters.
+_DEFAULTS: dict[str, dict[str, Any]] = {
+ "running_processes": {"limit": 200},
+ "active_connections": {"limit": 200},
+ "logged_in_users": {"limit": 100},
+ "recent_files": {"directory": "/tmp", "limit": 100},
+ "process_tree": {"pid": 1, "max_depth": 5},
+ "package_inventory": {"limit": 500},
+}
+
+# Explicit spec of which parameters each template accepts.
+PARAM_SPECS: dict[str, set[str]] = {
+ "running_processes": {"limit"},
+ "active_connections": {"limit"},
+ "logged_in_users": {"limit"},
+ "recent_files": {"directory", "limit"},
+ "process_tree": {"pid", "max_depth"},
+ "package_inventory": {"limit"},
+}
+
+# Compile a regex that matches parameterised placeholders in the templates.
+_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
+
+
+class AllowlistError(ValueError):
+ """Raised when a query or parameter fails allowlist validation."""
+
+
+def list_templates() -> list[str]:
+ """Return the sorted list of available template IDs."""
+ return sorted(TEMPLATES)
+
+
+def render_query(template_id: str, **params: Any) -> str:
+ """Render *template_id* with the supplied keyword parameters.
+
+ Parameters
+ ----------
+ template_id:
+ Must be one of the keys in :data:`TEMPLATES`.
+ **params:
+ Parameter values to substitute. Unknown keys raise
+ :class:`AllowlistError`; missing keys are filled from
+ :data:`_DEFAULTS`.
+
+ Returns
+ -------
+ str
+ The fully-rendered, ready-to-execute SQL string.
+
+ Raises
+ ------
+ AllowlistError
+ If *template_id* is not in the allowlist, if an unknown parameter
+ is supplied, or if a required parameter has no default.
+ """
+ if template_id not in TEMPLATES:
+ raise AllowlistError(
+ f"Unknown template '{template_id}'. "
+ f"Available: {', '.join(list_templates())}"
+ )
+
+ allowed_keys = PARAM_SPECS[template_id]
+ unknown = set(params) - allowed_keys
+ if unknown:
+ raise AllowlistError(
+ f"Template '{template_id}' does not accept "
+ f"parameter(s): {', '.join(sorted(unknown))}. "
+ f"Allowed: {', '.join(sorted(allowed_keys))}"
+ )
+
+ # Merge caller-supplied params over defaults.
+ merged: dict[str, Any] = {**_DEFAULTS.get(template_id, {}), **params}
+
+ # Verify that all placeholders have values after merging.
+ required = {m.group(1) for m in _PLACEHOLDER_RE.finditer(TEMPLATES[template_id])}
+ missing = required - set(merged)
+ if missing:
+ raise AllowlistError(
+ f"Template '{template_id}' requires "
+ f"parameter(s) with no default: {', '.join(sorted(missing))}"
+ )
+
+ # Basic sanitisation: reject values that contain SQL comment sequences or
+ # statement terminators other than the trailing semicolon already in the
+ # template. This is defence-in-depth; the primary protection is the
+ # allowlist itself.
+ for key, value in merged.items():
+ val_str = str(value)
+ if "--" in val_str or "/*" in val_str or ";" in val_str:
+ raise AllowlistError(
+ f"Parameter '{key}' contains disallowed characters."
+ )
+
+ return TEMPLATES[template_id].format_map(merged)
+
+
+def validate_raw_sql(sql: str) -> None:
+ """Raise :class:`AllowlistError` if *sql* is not a known rendered template.
+
+ This is intentionally strict: only SQL that was produced by
+ :func:`render_query` (and therefore matches one of the templates exactly)
+ is accepted. Any other SQL — including manually constructed queries —
+ is rejected.
+
+ Callers that need to verify whether a given SQL string came from the
+ allowlist can use this to gate execution.
+ """
+ normalised = " ".join(sql.split())
+ for tmpl_id in TEMPLATES:
+ try:
+ rendered = render_query(tmpl_id, **_DEFAULTS.get(tmpl_id, {}))
+ except AllowlistError:
+ continue
+ if normalised == " ".join(rendered.split()):
+ return
+ raise AllowlistError(
+ "SQL does not match any approved template. "
+ "Use render_query() with an approved template ID."
+ )
diff --git a/services/actions/tests/test_fleetdm_client.py b/services/actions/tests/test_fleetdm_client.py
new file mode 100644
index 000000000..3fcbb6e43
--- /dev/null
+++ b/services/actions/tests/test_fleetdm_client.py
@@ -0,0 +1,215 @@
+"""Tests for FleetDMClient — respx-mocked HTTP calls."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+import pytest
+import respx
+
+from app.clients.fleetdm_client import FleetDMClient, FleetDMError
+from app.clients.osquery_allowlist import AllowlistError
+
+
+BASE = "https://fleet.example.com"
+TOKEN = "fleet-api-token-xyz"
+
+
+def _make_client_token(**kwargs: Any) -> FleetDMClient:
+ return FleetDMClient(
+ base_url=BASE,
+ api_token=TOKEN,
+ verify_tls=False,
+ poll_interval=0.01,
+ **kwargs,
+ )
+
+
+def _make_client_password(**kwargs: Any) -> FleetDMClient:
+ return FleetDMClient(
+ base_url=BASE,
+ username="[email protected]",
+ password="s3cr3t",
+ verify_tls=False,
+ poll_interval=0.01,
+ **kwargs,
+ )
+
+
+LOGIN_URL = f"{BASE}/api/v1/fleet/login"
+CAMPAIGN_URL = f"{BASE}/api/v1/fleet/queries/run"
+CAMPAIGN_STATUS_TMPL = f"{BASE}/api/v1/fleet/queries/run/{{}}"
+
+
+class TestAllowlistRejection:
+ @pytest.mark.asyncio
+ async def test_unknown_template_raises(self) -> None:
+ client = _make_client_token()
+ with pytest.raises(AllowlistError):
+ await client.live_query(["host1"], template="DROP TABLE users;")
+
+
+class TestTokenAuth:
+ @pytest.mark.asyncio
+ async def test_token_sent_in_header(self) -> None:
+ campaign_id = 42
+ captured: dict[str, str] = {}
+
+ def capture_campaign(request: httpx.Request) -> httpx.Response:
+ captured.update(dict(request.headers))
+ return httpx.Response(200, json={"campaign": {"id": campaign_id}})
+
+ with respx.mock:
+ respx.post(CAMPAIGN_URL).mock(side_effect=capture_campaign)
+ respx.get(CAMPAIGN_STATUS_TMPL.format(campaign_id)).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "status": {"total_results_count": 1},
+ "results": [
+ {
+ "rows": [{"pid": "1", "name": "init"}],
+ "host": {"hostname": "host1"},
+ }
+ ],
+ },
+ )
+ )
+
+ client = _make_client_token()
+ result = await client.live_query(
+ ["host1"], template="running_processes", timeout_seconds=5
+ )
+
+ assert captured.get("authorization") == f"Bearer {TOKEN}"
+ assert result["partial"] is False
+ assert "host1" in result["results"]
+
+
+class TestPasswordAuth:
+ @pytest.mark.asyncio
+ async def test_login_called_then_campaign(self) -> None:
+ campaign_id = 99
+ session_token = "session-tok-001"
+
+ with respx.mock:
+ respx.post(LOGIN_URL).mock(
+ return_value=httpx.Response(200, json={"token": session_token})
+ )
+ respx.post(CAMPAIGN_URL).mock(
+ return_value=httpx.Response(200, json={"campaign": {"id": campaign_id}})
+ )
+ respx.get(CAMPAIGN_STATUS_TMPL.format(campaign_id)).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "status": {"total_results_count": 1},
+ "results": [
+ {
+ "rows": [],
+ "host": {"hostname": "host1"},
+ }
+ ],
+ },
+ )
+ )
+
+ client = _make_client_password()
+ result = await client.live_query(["host1"], template="active_connections")
+
+ assert result["partial"] is False
+
+
+class TestPollingTimeout:
+ @pytest.mark.asyncio
+ async def test_partial_when_results_incomplete(self) -> None:
+ campaign_id = 7
+ with respx.mock:
+ respx.post(CAMPAIGN_URL).mock(
+ return_value=httpx.Response(200, json={"campaign": {"id": campaign_id}})
+ )
+ # Returns only 0/2 results
+ respx.get(CAMPAIGN_STATUS_TMPL.format(campaign_id)).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "status": {"total_results_count": 0},
+ "results": [],
+ },
+ )
+ )
+
+ client = _make_client_token()
+ result = await client.live_query(
+ ["host1", "host2"],
+ template="logged_in_users",
+ timeout_seconds=0,
+ )
+
+ assert result["partial"] is True
+
+
+class TestErrorHandling:
+ @pytest.mark.asyncio
+ async def test_login_failure_raises(self) -> None:
+ with respx.mock:
+ respx.post(LOGIN_URL).mock(return_value=httpx.Response(401, json={"error": "bad creds"}))
+
+ client = _make_client_password()
+ with pytest.raises(FleetDMError, match="login failed"):
+ await client.live_query(["host1"], template="running_processes")
+
+ @pytest.mark.asyncio
+ async def test_campaign_creation_failure_raises(self) -> None:
+ with respx.mock:
+ respx.post(CAMPAIGN_URL).mock(return_value=httpx.Response(500, text="error"))
+
+ client = _make_client_token()
+ with pytest.raises(FleetDMError, match="campaign creation failed"):
+ await client.live_query(["host1"], template="running_processes")
+
+ @pytest.mark.asyncio
+ async def test_missing_campaign_id_raises(self) -> None:
+ with respx.mock:
+ respx.post(CAMPAIGN_URL).mock(
+ return_value=httpx.Response(200, json={"campaign": {}})
+ )
+
+ client = _make_client_token()
+ with pytest.raises(FleetDMError, match="no campaign ID"):
+ await client.live_query(["host1"], template="active_connections")
+
+
+class TestPartialResponse:
+ @pytest.mark.asyncio
+ async def test_partial_result_structure(self) -> None:
+ campaign_id = 55
+
+ with respx.mock:
+ respx.post(CAMPAIGN_URL).mock(
+ return_value=httpx.Response(200, json={"campaign": {"id": campaign_id}})
+ )
+ # host1 responds, host2 never does; we poll until timeout.
+ respx.get(CAMPAIGN_STATUS_TMPL.format(campaign_id)).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "status": {"total_results_count": 1},
+ "results": [
+ {"rows": [{"pid": "42"}], "host": {"hostname": "host1"}}
+ ],
+ },
+ )
+ )
+
+ client = _make_client_token()
+ result = await client.live_query(
+ ["host1", "host2"],
+ template="running_processes",
+ timeout_seconds=1, # non-zero so at least one poll happens
+ )
+
+ assert result["partial"] is True
+ assert "host1" in result["results"]
+ assert result["results"]["host1"][0]["pid"] == "42"
diff --git a/services/actions/tests/test_osctrl_client.py b/services/actions/tests/test_osctrl_client.py
new file mode 100644
index 000000000..9ae79ef2d
--- /dev/null
+++ b/services/actions/tests/test_osctrl_client.py
@@ -0,0 +1,183 @@
+"""Tests for OsctrlClient — respx-mocked HTTP calls."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+import respx
+import httpx
+
+from app.clients.osctrl_client import OsctrlClient, OsctrlError
+from app.clients.osquery_allowlist import AllowlistError
+
+
+BASE = "https://osctrl.example.com"
+ENV = "prod"
+TOKEN = "test-token-abc"
+
+
+def _make_client(**kwargs: Any) -> OsctrlClient:
+ return OsctrlClient(
+ base_url=BASE,
+ environment=ENV,
+ api_token=TOKEN,
+ verify_tls=False,
+ poll_interval=0.01,
+ **kwargs,
+ )
+
+
+SUBMIT_URL = f"{BASE}/api/v1/queries/{ENV}"
+RESULTS_URL_TMPL = f"{BASE}/api/v1/queries/{ENV}/{{}}/results"
+
+
+class TestAllowlistRejection:
+ @pytest.mark.asyncio
+ async def test_unknown_template_raises_allowlist_error(self) -> None:
+ client = _make_client()
+ with pytest.raises(AllowlistError):
+ await client.live_query(["host1"], template="not_a_template")
+
+
+class TestSuccessPath:
+ @pytest.mark.asyncio
+ async def test_single_host_all_respond(self) -> None:
+ query_id = "qid-001"
+ results_url = RESULTS_URL_TMPL.format(query_id)
+
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(
+ return_value=httpx.Response(201, json={"id": query_id})
+ )
+ respx.get(results_url).mock(
+ return_value=httpx.Response(
+ 200,
+ json=[{"node": "host1", "rows": [{"pid": "123", "name": "bash"}]}],
+ )
+ )
+
+ client = _make_client()
+ result = await client.live_query(
+ ["host1"], template="running_processes", timeout_seconds=5
+ )
+
+ assert result["partial"] is False
+ assert "host1" in result["results"]
+ rows = result["results"]["host1"]
+ assert rows[0]["pid"] == "123"
+
+ @pytest.mark.asyncio
+ async def test_submit_uses_bearer_token(self) -> None:
+ query_id = "qid-bearer"
+ results_url = RESULTS_URL_TMPL.format(query_id)
+
+ captured_headers: dict[str, str] = {}
+
+ def capture_submit(request: httpx.Request) -> httpx.Response:
+ captured_headers.update(dict(request.headers))
+ return httpx.Response(200, json={"id": query_id})
+
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(side_effect=capture_submit)
+ respx.get(results_url).mock(
+ return_value=httpx.Response(200, json=[{"node": "host1", "rows": []}])
+ )
+
+ client = _make_client()
+ await client.live_query(["host1"], template="active_connections")
+
+ assert captured_headers.get("authorization") == f"Bearer {TOKEN}"
+
+
+class TestPollingTimeout:
+ @pytest.mark.asyncio
+ async def test_partial_true_when_timeout_before_all_respond(self) -> None:
+ query_id = "qid-timeout"
+ results_url = RESULTS_URL_TMPL.format(query_id)
+
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(
+ return_value=httpx.Response(200, json={"id": query_id})
+ )
+ # Only host1 responds; host2 never appears.
+ respx.get(results_url).mock(
+ return_value=httpx.Response(
+ 200,
+ json=[{"node": "host1", "rows": [{"pid": "1"}]}],
+ )
+ )
+
+ client = _make_client()
+ result = await client.live_query(
+ ["host1", "host2"],
+ template="running_processes",
+ timeout_seconds=0, # immediate timeout
+ )
+
+ assert result["partial"] is True
+
+
+class TestErrorHandling:
+ @pytest.mark.asyncio
+ async def test_submit_500_raises_osctrl_error(self) -> None:
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(return_value=httpx.Response(500, text="server error"))
+
+ client = _make_client()
+ with pytest.raises(OsctrlError, match="query submission failed"):
+ await client.live_query(["host1"], template="logged_in_users")
+
+ @pytest.mark.asyncio
+ async def test_poll_non_200_non_404_raises(self) -> None:
+ query_id = "qid-poll-err"
+ results_url = RESULTS_URL_TMPL.format(query_id)
+
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(
+ return_value=httpx.Response(200, json={"id": query_id})
+ )
+ respx.get(results_url).mock(return_value=httpx.Response(503, text="unavailable"))
+
+ client = _make_client()
+ with pytest.raises(OsctrlError, match="result poll failed"):
+ await client.live_query(["host1"], template="active_connections", timeout_seconds=5)
+
+ @pytest.mark.asyncio
+ async def test_no_query_id_in_response_raises(self) -> None:
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(return_value=httpx.Response(200, json={}))
+
+ client = _make_client()
+ with pytest.raises(OsctrlError, match="no query ID"):
+ await client.live_query(["host1"], template="logged_in_users")
+
+
+class TestTemplateParams:
+ @pytest.mark.asyncio
+ async def test_custom_limit_forwarded(self) -> None:
+ """Ensure the rendered SQL (with custom params) is sent to the API."""
+ query_id = "qid-params"
+ results_url = RESULTS_URL_TMPL.format(query_id)
+ captured_body: dict[str, Any] = {}
+
+ def capture(request: httpx.Request) -> httpx.Response:
+ import json
+ captured_body.update(json.loads(request.content))
+ return httpx.Response(201, json={"id": query_id})
+
+ with respx.mock:
+ respx.post(SUBMIT_URL).mock(side_effect=capture)
+ respx.get(results_url).mock(
+ return_value=httpx.Response(200, json=[{"node": "h1", "rows": []}])
+ )
+
+ client = _make_client()
+ await client.live_query(
+ ["h1"],
+ template="running_processes",
+ template_params={"limit": 10},
+ )
+
+ assert "LIMIT 10" in captured_body.get("query", "")
diff --git a/services/actions/tests/test_osquery_allowlist.py b/services/actions/tests/test_osquery_allowlist.py
new file mode 100644
index 000000000..ed5cfa2ae
--- /dev/null
+++ b/services/actions/tests/test_osquery_allowlist.py
@@ -0,0 +1,99 @@
+"""Tests for the osquery SQL allowlist module."""
+
+from __future__ import annotations
+
+import pytest
+
+from app.clients.osquery_allowlist import (
+ AllowlistError,
+ TEMPLATES,
+ list_templates,
+ render_query,
+ validate_raw_sql,
+)
+
+
+class TestListTemplates:
+ def test_returns_sorted_list(self) -> None:
+ templates = list_templates()
+ assert templates == sorted(templates)
+
+ def test_contains_expected_ids(self) -> None:
+ expected = {
+ "running_processes",
+ "active_connections",
+ "logged_in_users",
+ "recent_files",
+ "process_tree",
+ "package_inventory",
+ }
+ assert expected.issubset(set(list_templates()))
+
+
+class TestRenderQuery:
+ def test_running_processes_defaults(self) -> None:
+ sql = render_query("running_processes")
+ assert "FROM processes" in sql
+ assert "200" in sql # default limit
+
+ def test_running_processes_custom_limit(self) -> None:
+ sql = render_query("running_processes", limit=50)
+ assert "50" in sql
+
+ def test_active_connections_defaults(self) -> None:
+ sql = render_query("active_connections")
+ assert "FROM process_open_sockets" in sql
+
+ def test_logged_in_users_defaults(self) -> None:
+ sql = render_query("logged_in_users")
+ assert "FROM logged_in_users" in sql
+
+ def test_recent_files_custom_directory(self) -> None:
+ sql = render_query("recent_files", directory="/var/log")
+ assert "/var/log" in sql
+
+ def test_process_tree_custom_pid(self) -> None:
+ sql = render_query("process_tree", pid=1234)
+ assert "1234" in sql
+
+ def test_package_inventory_defaults(self) -> None:
+ sql = render_query("package_inventory")
+ assert "deb_packages" in sql
+
+ def test_unknown_template_raises(self) -> None:
+ with pytest.raises(AllowlistError, match="Unknown template"):
+ render_query("not_a_real_template")
+
+ def test_unknown_param_raises(self) -> None:
+ with pytest.raises(AllowlistError, match="does not accept parameter"):
+ render_query("running_processes", bad_param="evil")
+
+ def test_sql_injection_via_directory_raises(self) -> None:
+ with pytest.raises(AllowlistError, match="disallowed characters"):
+ render_query("recent_files", directory="/tmp'; DROP TABLE processes; --")
+
+ def test_sql_comment_in_param_raises(self) -> None:
+ with pytest.raises(AllowlistError, match="disallowed characters"):
+ render_query("recent_files", directory="/tmp -- comment")
+
+ def test_returns_string(self) -> None:
+ result = render_query("running_processes")
+ assert isinstance(result, str)
+ assert len(result) > 10
+
+
+class TestValidateRawSql:
+ def test_valid_default_render_passes(self) -> None:
+ for tid in list_templates():
+ sql = render_query(tid)
+ validate_raw_sql(sql) # must not raise
+
+ def test_raw_sql_rejected(self) -> None:
+ with pytest.raises(AllowlistError, match="does not match any approved template"):
+ validate_raw_sql("SELECT * FROM users;")
+
+ def test_modified_template_rejected(self) -> None:
+ sql = render_query("running_processes")
+ tampered = sql + " UNION SELECT 1,2,3;"
+ with pytest.raises(AllowlistError):
+ validate_raw_sql(tampered)
diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.py
index 66af0123a..7837b9a9f 100644
--- a/services/agents/app/playbook/engine.py
+++ b/services/agents/app/playbook/engine.py
@@ -210,6 +210,92 @@ async def _handle_close_case(step: PlaybookStep, context: dict[str, Any], http:
return {"case_id": case_id, "status": "closed"}
+async def _handle_osquery_live_query(
+ step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient
+) -> dict:
+ """Dispatch a distributed osquery live query via osctrl, FleetDM, or aisoc-direct.
+
+ Expected ``step.params`` keys
+ ------------------------------
+ backend : str
+ One of ``"osctrl"``, ``"fleetdm"``, ``"aisoc_direct"``.
+ instance_id : str
+ Connector instance ID (looked up from the API to retrieve credentials).
+ target_hosts : list[str]
+ Host UUIDs / hostnames to query.
+ template : str
+ Allowlist template ID (see ``osquery_allowlist``).
+ template_params : dict, optional
+ Parameters forwarded to the template renderer.
+ 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
+
+ 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", "")
+ ]
+ template: str = step.params.get("template", "")
+ template_params: dict[str, Any] = step.params.get("template_params") or {}
+ timeout_seconds: int = step.params.get("timeout_seconds", 60)
+
+ if not template:
+ return {"error": "osquery_live_query: 'template' param is required", "partial": True}
+
+ # Credential resolution: fetch the connector instance config from the API.
+ instance_id: str = step.params.get("instance_id") or context.get("connector_instance_id", "")
+ creds: dict[str, Any] = {}
+ if instance_id:
+ try:
+ r = await http.get(
+ f"{_API_URL}/api/v1/connectors/instances/{instance_id}",
+ timeout=10,
+ )
+ if r.status_code == 200:
+ creds = r.json().get("auth_config") or {}
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Could not fetch connector creds for %s: %s", instance_id, exc)
+
+ try:
+ if backend == "osctrl":
+ client = OsctrlClient(
+ base_url=creds.get("base_url") or step.params.get("base_url", ""),
+ environment=creds.get("environment") or step.params.get("environment", "default"),
+ api_token=creds.get("api_token") or step.params.get("api_token", ""),
+ verify_tls=step.params.get("verify_tls", True),
+ )
+ return await client.live_query(target_hosts, template, template_params, timeout_seconds)
+
+ if backend == "fleetdm":
+ client_fleet = FleetDMClient(
+ base_url=creds.get("base_url") or step.params.get("base_url", ""),
+ api_token=creds.get("api_token") or step.params.get("api_token") or None,
+ username=creds.get("username") or step.params.get("username") or None,
+ password=creds.get("password") or step.params.get("password") or None,
+ verify_tls=step.params.get("verify_tls", True),
+ )
+ return await client_fleet.live_query(target_hosts, template, template_params, timeout_seconds)
+
+ if backend == "aisoc_direct":
+ client_direct = AiSOCDirectClient(
+ base_url=creds.get("base_url") or step.params.get("base_url", ""),
+ api_token=creds.get("api_token") or step.params.get("api_token", ""),
+ )
+ return await client_direct.live_query(target_hosts, template, template_params, timeout_seconds)
+
+ return {"error": f"Unknown osquery backend: {backend!r}", "partial": True}
+
+ except AllowlistError as exc:
+ return {"error": f"osquery allowlist violation: {exc}", "partial": True}
+ except NotImplementedError as exc:
+ return {"error": str(exc), "partial": True, "stub": True}
+
+
_HANDLERS = {
StepType.ENRICH: _handle_enrich,
StepType.INVESTIGATE: _handle_investigate,
@@ -219,6 +305,7 @@ _HANDLERS = {
StepType.ISOLATE_HOST: _handle_isolate_host,
StepType.CREATE_TICKET: _handle_create_ticket,
StepType.CLOSE_CASE: _handle_close_case,
+ StepType.OSQUERY_LIVE_QUERY: _handle_osquery_live_query,
}
diff --git a/services/agents/app/playbook/models.py b/services/agents/app/playbook/models.py
index 40c3c2a8f..59a9a73ea 100644
--- a/services/agents/app/playbook/models.py
+++ b/services/agents/app/playbook/models.py
@@ -21,6 +21,7 @@ class StepType(str, Enum):
CLOSE_CASE = "close_case"
HTTP = "http" # Generic outbound HTTP call
CONDITION = "condition" # Branching / gate
+ OSQUERY_LIVE_QUERY = "osquery_live_query" # Distributed osquery via osctrl/FleetDM/aisoc-direct
class StepCondition(BaseModel):
diff --git a/services/agents/tests/test_osquery_live_query_step.py b/services/agents/tests/test_osquery_live_query_step.py
new file mode 100644
index 000000000..b7b20a1cb
--- /dev/null
+++ b/services/agents/tests/test_osquery_live_query_step.py
@@ -0,0 +1,267 @@
+"""
+Unit tests for the osquery_live_query playbook step handler.
+
+Tests exercise ``_handle_osquery_live_query`` directly with patched client
+classes injected via sys.modules, so no real network calls are made.
+"""
+from __future__ import annotations
+
+import sys
+import types
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# Inject stub modules BEFORE importing the engine (engine does lazy imports
+# inside the handler, so sys.modules stubs are enough).
+# ---------------------------------------------------------------------------
+
+
+class AllowlistError(Exception):
+ pass
+
+
+class OsctrlError(Exception):
+ pass
+
+
+class FleetDMError(Exception):
+ pass
+
+
+def _inject_stubs(
+ *,
+ osctrl_live_query: Any = None,
+ fleetdm_live_query: Any = None,
+ direct_live_query: Any = None,
+) -> None:
+ """(Re-)inject stub modules with the provided live_query implementations."""
+
+ # --- osquery_allowlist ---
+ al_mod = types.ModuleType("app.clients.osquery_allowlist")
+ al_mod.AllowlistError = AllowlistError # type: ignore[attr-defined]
+ sys.modules["app.clients.osquery_allowlist"] = al_mod
+
+ # --- osctrl_client ---
+ osc_instance = AsyncMock()
+ if osctrl_live_query is not None:
+ osc_instance.live_query = osctrl_live_query
+ osc_cls = MagicMock(return_value=osc_instance)
+ osc_mod = types.ModuleType("app.clients.osctrl_client")
+ osc_mod.OsctrlClient = osc_cls # type: ignore[attr-defined]
+ osc_mod.OsctrlError = OsctrlError # type: ignore[attr-defined]
+ sys.modules["app.clients.osctrl_client"] = osc_mod
+
+ # --- fleetdm_client ---
+ fleet_instance = AsyncMock()
+ if fleetdm_live_query is not None:
+ fleet_instance.live_query = fleetdm_live_query
+ fleet_cls = MagicMock(return_value=fleet_instance)
+ fleet_mod = types.ModuleType("app.clients.fleetdm_client")
+ fleet_mod.FleetDMClient = fleet_cls # type: ignore[attr-defined]
+ fleet_mod.FleetDMError = FleetDMError # type: ignore[attr-defined]
+ sys.modules["app.clients.fleetdm_client"] = fleet_mod
+
+ # --- aisoc_direct_client ---
+ direct_instance = AsyncMock()
+ if direct_live_query is not None:
+ direct_instance.live_query = direct_live_query
+ direct_cls = MagicMock(return_value=direct_instance)
+ direct_mod = types.ModuleType("app.clients.aisoc_direct_client")
+ direct_mod.AiSOCDirectClient = direct_cls # type: ignore[attr-defined]
+ sys.modules["app.clients.aisoc_direct_client"] = direct_mod
+
+ return osc_instance, fleet_instance, direct_instance # type: ignore[return-value]
+
+
+# Perform an initial injection before the engine import so sys.modules is
+# populated when the engine module is loaded (even though the imports inside
+# the handler are deferred, Python still needs the top-level `app` package).
+_inject_stubs()
+
+from app.playbook.engine import _handle_osquery_live_query # noqa: E402
+from app.playbook.models import PlaybookStep, StepType # noqa: E402
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _step(params: dict[str, Any]) -> PlaybookStep:
+ return PlaybookStep(
+ id="s1",
+ name="osquery-step",
+ type=StepType.OSQUERY_LIVE_QUERY,
+ params=params,
+ )
+
+
+def _ctx(**kwargs: Any) -> dict[str, Any]:
+ base: dict[str, Any] = {"host": "host1", "connector_instance_id": ""}
+ base.update(kwargs)
+ return base
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+class TestMissingTemplate:
+ @pytest.mark.asyncio
+ async def test_missing_template_returns_error(self) -> None:
+ _inject_stubs()
+ step = _step({"backend": "osctrl", "target_hosts": ["h1"], "base_url": "http://osc", "api_token": "t"})
+ step.params.pop("template", None)
+ result = await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ assert "error" in result
+ assert result.get("partial") is True
+
+
+class TestUnknownBackend:
+ @pytest.mark.asyncio
+ async def test_unknown_backend_returns_error(self) -> None:
+ _inject_stubs()
+ step = _step(
+ {
+ "backend": "nonexistent_backend",
+ "template": "running_processes",
+ "target_hosts": ["h1"],
+ }
+ )
+ result = await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ assert "error" in result
+ assert "nonexistent_backend" in result["error"]
+ assert result.get("partial") is True
+
+
+class TestAllowlistViolation:
+ @pytest.mark.asyncio
+ async def test_allowlist_error_caught(self) -> None:
+ lq = AsyncMock(side_effect=AllowlistError("bad template"))
+ _inject_stubs(osctrl_live_query=lq)
+
+ step = _step(
+ {
+ "backend": "osctrl",
+ "template": "running_processes",
+ "target_hosts": ["h1"],
+ "base_url": "http://osc",
+ "api_token": "tok",
+ }
+ )
+ result = await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ assert "error" in result
+ assert "allowlist" in result["error"]
+ assert result.get("partial") is True
+
+
+class TestOsctrlDispatch:
+ @pytest.mark.asyncio
+ async def test_osctrl_backend_dispatches_correctly(self) -> None:
+ expected = {"results": {"h1": [{"pid": "1"}]}, "partial": False}
+ lq = AsyncMock(return_value=expected)
+ osc_instance, _, _ = _inject_stubs(osctrl_live_query=lq)
+
+ step = _step(
+ {
+ "backend": "osctrl",
+ "template": "running_processes",
+ "target_hosts": ["h1"],
+ "base_url": "http://osc",
+ "environment": "prod",
+ "api_token": "tok",
+ }
+ )
+ result = await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ assert result == expected
+ lq.assert_awaited_once_with(["h1"], "running_processes", {}, 60)
+
+
+class TestFleetDMDispatch:
+ @pytest.mark.asyncio
+ async def test_fleetdm_backend_dispatches_correctly(self) -> None:
+ expected = {"results": {"h1": [{"user": "root"}]}, "partial": False}
+ lq = AsyncMock(return_value=expected)
+ _, fleet_instance, _ = _inject_stubs(fleetdm_live_query=lq)
+
+ step = _step(
+ {
+ "backend": "fleetdm",
+ "template": "logged_in_users",
+ "target_hosts": ["h1"],
+ "base_url": "http://fleet",
+ "api_token": "fleet-tok",
+ }
+ )
+ result = await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ assert result == expected
+ lq.assert_awaited_once_with(["h1"], "logged_in_users", {}, 60)
+
+
+class TestAiSOCDirectStub:
+ @pytest.mark.asyncio
+ async def test_aisoc_direct_not_implemented_is_safe(self) -> None:
+ lq = AsyncMock(side_effect=NotImplementedError("PR4: not yet implemented"))
+ _inject_stubs(direct_live_query=lq)
+
+ step = _step(
+ {
+ "backend": "aisoc_direct",
+ "template": "active_connections",
+ "target_hosts": ["h1"],
+ "base_url": "http://tls",
+ "api_token": "x",
+ }
+ )
+ result = await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ assert result.get("stub") is True
+ assert result.get("partial") is True
+ assert "PR4" in result.get("error", "")
+
+
+class TestTemplateParams:
+ @pytest.mark.asyncio
+ async def test_template_params_forwarded(self) -> None:
+ lq = AsyncMock(return_value={"results": {}, "partial": False})
+ _inject_stubs(osctrl_live_query=lq)
+
+ step = _step(
+ {
+ "backend": "osctrl",
+ "template": "running_processes",
+ "template_params": {"limit": 5},
+ "target_hosts": ["h1"],
+ "base_url": "http://osc",
+ "api_token": "tok",
+ "timeout_seconds": 30,
+ }
+ )
+ await _handle_osquery_live_query(step, _ctx(), MagicMock())
+ lq.assert_awaited_once_with(["h1"], "running_processes", {"limit": 5}, 30)
+
+
+class TestHostFallback:
+ @pytest.mark.asyncio
+ async def test_host_from_context_when_no_target_hosts(self) -> None:
+ lq = AsyncMock(return_value={"results": {}, "partial": False})
+ _inject_stubs(osctrl_live_query=lq)
+
+ step = _step(
+ {
+ "backend": "osctrl",
+ "template": "running_processes",
+ "base_url": "http://osc",
+ "api_token": "tok",
+ # No target_hosts — should fall back to context["host"]
+ }
+ )
+ ctx = _ctx(host="context-host")
+ await _handle_osquery_live_query(step, ctx, MagicMock())
+
+ call_args = lq.call_args
+ assert "context-host" in call_args[0][0]