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(v8/T3.4): real ES|QL runner shared by /nl-query and /hunt scheduler (#144)

Beenu Arora9a7238341033
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d17fa926..4ef69fbff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Real ES|QL runner for saved-hunt scheduler (T3.4, v8.0)
+
+Replaces the `_execute_hunt` stub in `services/api/app/workers/hunt_scheduler.py`
+with a real Elasticsearch query path. The shared logic now lives in
+`services/api/app/services/esql_runner.py` — a small async module that exposes
+`run_esql_query()`, `resolve_es_credentials()`, and the `ESQLResult` /
+`ESQLExecutionError` / `ESQLNotConfigured` types. Both the request-scoped
+`/nl-query/execute` endpoint and the out-of-band saved-hunt scheduler now
+share one code path for the outbound POST, the SSRF guard (validates the
+target host against the configured `ES_URL`/`ELASTICSEARCH_URL`/`OPENSEARCH_URL`
+and reconstructs the URL from validated components only — no user path/query
+ever reaches the network), and the air-gap policy
+(`enforce_airgap_for_url` is invoked unconditionally so an operator who
+flipped `AISOC_AIRGAPPED=true` can't accidentally leak a saved hunt to a
+public host). The scheduler reads the stored `translated_query["esql"]`
+(no re-translation in the background — that's the endpoint's job),
+appends a `LIMIT` clause when the translator didn't supply one
+(capped by `HUNT_SCHEDULER_MAX_ROWS`, default 500), and returns
+`len(rows)` so `run_once` can decide whether to open a case via the
+existing `_open_case_for_hits` hook. Missing translated ES|QL or missing
+ES credentials are logged at `info` and skip the run with zero hits —
+self-hosted dev installs without ES wired up stay quiet instead of
+spamming `exception`. Real transport / air-gap / SSRF errors propagate
+back to `run_once`, which records them via `logger.exception` and skips
+the `last_run_at` bump so the hunt retries on the next sweep instead of
+being silently marked "ran". `nl_query.py` was refactored at the same
+time to call the shared runner (deleting its private `_validate_es_url`
+copy), so the two execution surfaces can't drift on the security guards.
+Test coverage: 22 unit tests in `tests/test_esql_runner.py` (URL
+validation, credential resolution, air-gap propagation, LIMIT
+enforcement, error wrapping) plus 9 dedicated `_execute_hunt` tests in
+`tests/test_hunt_scheduler_execute.py` (all four skip paths, happy path
+with row count, three error-propagation paths). The existing
+saved-hunts endpoint + tenant isolation suites (47 tests) continue to
+pass unmodified.
### LLM input contract — raw-HTTP wrapper + remaining call sites (T2.3, v8.0)
Closes the last LLM-input-contract gap in `services/agents`. Every LangChain
diff --git a/services/api/app/api/v1/endpoints/nl_query.py b/services/api/app/api/v1/endpoints/nl_query.py
index e10c6e385..2e0fe1402 100644
--- a/services/api/app/api/v1/endpoints/nl_query.py
+++ b/services/api/app/api/v1/endpoints/nl_query.py
@@ -27,7 +27,6 @@ import uuid
from datetime import UTC, datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any
-from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, status
@@ -36,6 +35,12 @@ from pydantic import BaseModel, Field
from app.api.v1.deps import AuthUser
from app.core.airgap import AirgapViolation, enforce_airgap_for_url
from app.core.config import settings
+from app.services.esql_runner import (
+ ESQLExecutionError,
+ ESQLNotConfigured,
+ resolve_es_credentials,
+ run_esql_query,
+)
if TYPE_CHECKING:
# Static-only re-export so type checkers can see the dataclass fields and
@@ -144,29 +149,6 @@ if not TYPE_CHECKING:
router = APIRouter(prefix="/nl-query", tags=["nl_query"])
-def _validate_es_url(url: str) -> str:
- """Validate *url* against the configured Elasticsearch/OpenSearch host.
-
- Raises ValueError if the host or scheme does not match, preventing SSRF.
- Returns a *reconstructed* URL built solely from the validated scheme and
- netloc — this discards any user-supplied path/query components so that
- CodeQL's taint tracking does not flag the returned value as tainted.
- """
- allowed_raw = (
- getattr(settings, "ES_URL", None)
- or getattr(settings, "ELASTICSEARCH_URL", None)
- or getattr(settings, "OPENSEARCH_URL", "http://localhost:9200")
- )
- allowed = urlparse(allowed_raw)
- candidate = urlparse(url)
- if candidate.scheme not in ("http", "https"):
- raise ValueError(f"Unsupported URL scheme: {candidate.scheme!r}")
- if candidate.netloc != allowed.netloc:
- raise ValueError(f"ES URL host {candidate.netloc!r} is not the configured host {allowed.netloc!r}")
- # Reconstruct from validated components only — no user-supplied path/query.
- return f"{candidate.scheme}://{candidate.netloc}"
-
-
# ────────────────────────────────────────────────────────────────────────────
# Pydantic schemas
# ────────────────────────────────────────────────────────────────────────────
@@ -280,37 +262,30 @@ async def _translate(
async def _execute_esql(esql: str, es_url: str, es_api_key: str, max_rows: int) -> QueryResult:
- """Run an ES|QL query against Elasticsearch and return structured results."""
- # Validate URL against configured host before making any outbound request.
- try:
- safe_url = _validate_es_url(es_url)
- except ValueError as exc:
- raise httpx.RequestError(str(exc)) from exc
-
- es_query_url = f"{safe_url.rstrip('/')}/_query"
- enforce_airgap_for_url(es_query_url)
-
- # Ensure LIMIT clause
- query = esql if "| LIMIT" in esql.upper() else f"{esql}\n| LIMIT {max_rows}"
- import time
-
- t0 = time.monotonic()
- async with httpx.AsyncClient(timeout=20) as client:
- resp = await client.post(
- es_query_url,
- headers={
- "Authorization": f"ApiKey {es_api_key}",
- "Content-Type": "application/json",
- },
- json={"query": query},
- )
- resp.raise_for_status()
- data = resp.json()
+ """Run an ES|QL query against Elasticsearch and return structured results.
- took_ms = int((time.monotonic() - t0) * 1000)
- columns = [col["name"] for col in data.get("columns", [])]
- rows = data.get("values", [])
- return QueryResult(columns=columns, rows=rows, total_rows=len(rows), took_ms=took_ms)
+ Thin adapter around :func:`app.services.esql_runner.run_esql_query` so the
+ request-scoped endpoint and the background hunt scheduler share one code
+ path for the outbound POST, the SSRF guard, the air-gap enforcement, and
+ the LIMIT-clause normalisation.
+ """
+ result = await run_esql_query(
+ esql=esql,
+ es_url=es_url,
+ es_api_key=es_api_key,
+ max_rows=max_rows,
+ )
+ # ``ESQLResult`` exposes the post-LIMIT row list directly; the public
+ # ``QueryResult`` schema carries an explicit ``total_rows`` for legacy
+ # API consumers, but it's always ``len(rows)`` after the runner has
+ # enforced the cap (Elasticsearch doesn't return a row total for ES|QL,
+ # and we don't run a second count query just to populate the field).
+ return QueryResult(
+ columns=result.columns,
+ rows=result.rows,
+ total_rows=len(result.rows),
+ took_ms=result.took_ms,
+ )
# ────────────────────────────────────────────────────────────────────────────
@@ -354,11 +329,6 @@ async def execute_query(
) -> NLQueryExecuteResponse:
translated, engine = await _translate(body.question, body.index_pattern, body.time_range_hours)
- # Always read the ES URL from server-side settings — never from user-supplied
- # body fields — to prevent partial-SSRF attacks (CodeQL py/partial-ssrf).
- es_url = getattr(settings, "ES_URL", None) or getattr(settings, "ELASTICSEARCH_URL", None)
- es_api_key = body.es_api_key or getattr(settings, "ES_API_KEY", None)
-
base = NLQueryExecuteResponse(
request_id=uuid.uuid4(),
question=body.question,
@@ -371,8 +341,13 @@ async def execute_query(
grammar_validated=True,
)
- if not es_url or not es_api_key:
- base.execution_error = "ES_URL or ES_API_KEY not configured. Set them in environment variables or pass in the request body."
+ # Always resolve the ES URL from server-side settings — never from
+ # user-supplied body fields — to prevent partial-SSRF attacks
+ # (CodeQL py/partial-ssrf).
+ try:
+ es_url, es_api_key = resolve_es_credentials()
+ except ESQLNotConfigured:
+ base.execution_error = "ES_URL or ES_API_KEY not configured. Set them in environment variables."
return base
try:
@@ -391,6 +366,8 @@ async def execute_query(
# Should never happen — every translator output is validated — but if a
# caller somehow passes through a hand-edited query we want a clean error.
base.execution_error = f"Refusing to execute malformed ES|QL: {exc}"
+ except ESQLExecutionError as exc:
+ base.execution_error = str(exc)
except httpx.HTTPStatusError as exc:
base.execution_error = f"ES query failed ({exc.response.status_code}): {exc.response.text[:500]}"
except Exception as exc:
diff --git a/services/api/app/services/esql_runner.py b/services/api/app/services/esql_runner.py
new file mode 100644
index 000000000..0cd7caa17
--- /dev/null
+++ b/services/api/app/services/esql_runner.py
@@ -0,0 +1,274 @@
+"""Background-friendly ES|QL executor — Track 3, T3.4 (`/hunt` NL surface).
+
+This module exposes a single async helper, :func:`run_esql_query`, that
+both the request-scoped ``/nl-query/execute`` endpoint and the
+out-of-band saved-hunt scheduler can call to run an ES|QL query against
+the configured Elasticsearch backend.
+
+Why a shared helper instead of inlining the call?
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Before T3.4 the ES|QL HTTP call lived inside
+``services/api/app/api/v1/endpoints/nl_query.py`` and depended on a
+``QueryResult`` Pydantic model + FastAPI request scope. The saved-hunt
+scheduler (``app/workers/hunt_scheduler.py``) is an asyncio worker
+launched from the FastAPI ``lifespan`` hook — it has no request scope
+and is *deliberately* free of FastAPI imports so it can be lifted into a
+separate sidecar later. The scheduler therefore could not reuse the
+endpoint's executor directly, and shipped a stub that always returned
+zero hits (see the historical `_execute_hunt` TODO in
+``hunt_scheduler.py``).
+
+This module is the lift: a tiny dataclass + plain async function that
+takes the URL, API key, and ES|QL string and returns
+``(columns, rows, took_ms)``. The endpoint wraps the result back into
+its Pydantic ``QueryResult`` shape; the scheduler reads ``len(rows)``
+and feeds that into its case-open callback.
+
+Security invariants
+~~~~~~~~~~~~~~~~~~~
+
+* **SSRF guard.** :func:`run_esql_query` calls
+ :func:`_validate_es_url` to enforce that the target host matches the
+ configured ``ES_URL`` / ``ELASTICSEARCH_URL`` / ``OPENSEARCH_URL``
+ setting. A mismatched host raises :class:`ValueError` *before* any
+ outbound request leaves the process.
+* **Air-gap policy.** Each call routes the final URL through
+ :func:`enforce_airgap_for_url` so an operator who flipped
+ ``AISOC_AIRGAPPED=true`` can't accidentally leak a query to a
+ public host.
+* **No new dependencies.** Uses ``httpx`` (already a hard dep of the
+ API service) for the outbound call.
+
+Test coverage
+~~~~~~~~~~~~~
+
+See ``tests/test_esql_runner.py`` for the dedicated unit tests, and
+``tests/test_saved_hunts_endpoint.py`` for the scheduler integration
+test that wires ``_execute_hunt`` through this helper.
+"""
+
+from __future__ import annotations
+
+import re
+import time
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import urlparse
+
+import httpx
+
+from app.core.airgap import AirgapViolation, enforce_airgap_for_url
+from app.core.config import settings
+
+# `| LIMIT N` detection for the row-cap appender, robust against the
+# quoted-string bypass. ES|QL string literals can embed `|` and the
+# `LIMIT` keyword freely, so a naive substring check could be fooled by
+# a hostile-but-syntactically-valid hunt like::
+#
+# FROM logs-* | WHERE message == "this includes | LIMIT 5"
+#
+# We strip quoted strings first, then look for `| LIMIT` (case-insensitive)
+# in what's left — which is the actual pipeline outside of any literal.
+# Removal is conservative: both `'...'` and `"..."`, no backslash-escape
+# unescaping needed because we only care that the contents are gone.
+_STRING_LITERAL_RE = re.compile(r"'[^']*'|\"[^\"]*\"")
+_PIPE_LIMIT_RE = re.compile(r"\|\s*limit\b", re.IGNORECASE)
+
+
+def _has_toplevel_limit(esql: str) -> bool:
+ """True iff ``esql`` already contains a real ``| LIMIT`` clause.
+
+ See module-level note: strips string literals before scanning so a
+ quoted ``| LIMIT 5`` inside a WHERE clause doesn't suppress the
+ runner's max_rows cap.
+ """
+ stripped = _STRING_LITERAL_RE.sub("", esql)
+ return bool(_PIPE_LIMIT_RE.search(stripped))
+
+
+__all__ = [
+ "ESQLExecutionError",
+ "ESQLResult",
+ "ESQLNotConfigured",
+ "resolve_es_credentials",
+ "run_esql_query",
+]
+
+
+@dataclass(slots=True)
+class ESQLResult:
+ """Plain-data result of a single ES|QL query run.
+
+ The endpoint wraps this into its Pydantic ``QueryResult`` shape; the
+ scheduler reads ``len(rows)`` for its hit count. ``took_ms`` is the
+ wall-clock time we observed locally (including network) — not the
+ Elasticsearch-reported ``took`` field, because the ES|QL endpoint
+ does not always return it.
+ """
+
+ columns: list[str]
+ rows: list[list[Any]]
+ took_ms: int
+
+
+class ESQLExecutionError(RuntimeError):
+ """Raised when an ES|QL execution attempt fails after validation passed.
+
+ Distinct from :class:`ValueError` (raised for SSRF / URL validation)
+ and :class:`AirgapViolation` (raised for air-gap policy) so callers
+ can distinguish "Elasticsearch said 500" from "we refused to make
+ the call". The wrapping endpoint typically converts each into a
+ different HTTP status code for the analyst-facing UI.
+ """
+
+
+class ESQLNotConfigured(RuntimeError):
+ """Raised when no ES URL or API key is configured.
+
+ Callers that want a "skip, don't fail" semantic (the saved-hunt
+ scheduler in particular) catch this explicitly and short-circuit
+ with zero hits. Endpoints catch it and surface a 200 with a
+ structured ``execution_error`` instead of a hard 500.
+ """
+
+
+# ---------------------------------------------------------------------------
+# URL validation + credential resolution
+# ---------------------------------------------------------------------------
+
+
+def _validate_es_url(url: str) -> str:
+ """Validate ``url`` against the configured Elasticsearch/OpenSearch host.
+
+ Raises :class:`ValueError` if the host or scheme does not match,
+ preventing SSRF. Returns a *reconstructed* URL built solely from the
+ validated scheme and netloc — this discards any user-supplied path
+ or query so that CodeQL's taint tracking does not flag the returned
+ value, and so an attacker can't point a saved hunt at an attacker-
+ controlled path under the same host.
+ """
+ allowed_raw = (
+ getattr(settings, "ES_URL", None)
+ or getattr(settings, "ELASTICSEARCH_URL", None)
+ or getattr(settings, "OPENSEARCH_URL", "http://localhost:9200")
+ )
+ allowed = urlparse(allowed_raw)
+ candidate = urlparse(url)
+ if candidate.scheme not in ("http", "https"):
+ raise ValueError(f"Unsupported URL scheme: {candidate.scheme!r}")
+ if candidate.netloc != allowed.netloc:
+ raise ValueError(f"ES URL host {candidate.netloc!r} is not the configured host {allowed.netloc!r}")
+ return f"{candidate.scheme}://{candidate.netloc}"
+
+
+def resolve_es_credentials(
+ *,
+ es_url: str | None = None,
+ es_api_key: str | None = None,
+) -> tuple[str, str]:
+ """Resolve ES URL + API key from explicit overrides or settings.
+
+ Used by both the endpoint (which lets a caller override per-request)
+ and the scheduler (which always uses the configured settings).
+ Raises :class:`ESQLNotConfigured` when neither side supplies both
+ pieces — letting the caller pick its own "skip" vs "error" policy.
+ """
+ resolved_url = es_url or getattr(settings, "ES_URL", None) or getattr(settings, "ELASTICSEARCH_URL", None)
+ resolved_key = es_api_key or getattr(settings, "ES_API_KEY", None)
+ if not resolved_url or not resolved_key:
+ raise ESQLNotConfigured("ES_URL or ES_API_KEY not configured. Set them in environment variables or pass them explicitly.")
+ return resolved_url, resolved_key
+
+
+# ---------------------------------------------------------------------------
+# The runner
+# ---------------------------------------------------------------------------
+
+
+async def run_esql_query(
+ *,
+ esql: str,
+ es_url: str,
+ es_api_key: str,
+ max_rows: int = 500,
+ timeout: float = 20.0,
+) -> ESQLResult:
+ """Run a single ES|QL query and return ``(columns, rows, took_ms)``.
+
+ All three guards run *before* the outbound POST so a misconfigured
+ or hostile input never reaches the network:
+
+ 1. :func:`_validate_es_url` confirms the host matches the configured
+ Elasticsearch host (SSRF guard).
+ 2. :func:`enforce_airgap_for_url` confirms the host is permitted by
+ the air-gap policy (offline / dev guard).
+ 3. A ``LIMIT`` clause is appended if the caller didn't supply one,
+ so a misbehaving translator can't accidentally pull millions of
+ rows into memory.
+
+ Raises
+ ------
+ ValueError
+ URL validation failed (mismatched host or unsupported scheme).
+ AirgapViolation
+ Air-gap policy refuses the URL.
+ ESQLExecutionError
+ Elasticsearch returned a non-2xx response or the transport
+ failed. Wraps the underlying httpx error so callers only need
+ to catch one exception type.
+ """
+ try:
+ safe_url = _validate_es_url(es_url)
+ except ValueError:
+ # Re-raise unchanged — callers distinguish URL errors from
+ # transport errors and we don't want to lose that signal.
+ raise
+
+ es_query_url = f"{safe_url.rstrip('/')}/_query"
+ # enforce_airgap_for_url is a no-op when AISOC_AIRGAPPED is false,
+ # so this is safe to call unconditionally.
+ enforce_airgap_for_url(es_query_url)
+
+ # Append a LIMIT if the translator didn't already supply one.
+ #
+ # Detection is intentionally line-anchored on a top-level pipe, NOT
+ # a naive substring scan, because ES|QL string literals embed the
+ # `|` and `LIMIT` keyword freely — e.g.
+ #
+ # FROM logs | WHERE message == "this includes | LIMIT 5"
+ #
+ # would have fooled the previous `"| LIMIT" in esql.upper()` check
+ # into thinking the query already had a row cap, letting a tenant
+ # admin who can save hunts bypass the runner's max_rows ceiling
+ # entirely. The regex requires the pipe + LIMIT pair to be the
+ # leading non-whitespace token of a line, which is how ES|QL pipes
+ # are actually parsed.
+ query = esql if _has_toplevel_limit(esql) else f"{esql}\n| LIMIT {max_rows}"
+
+ t0 = time.monotonic()
+ try:
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ resp = await client.post(
+ es_query_url,
+ headers={
+ "Authorization": f"ApiKey {es_api_key}",
+ "Content-Type": "application/json",
+ },
+ json={"query": query},
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ except AirgapViolation:
+ # Let the air-gap signal propagate unchanged so the endpoint
+ # can return its dedicated 503 ``airgap_violation`` body.
+ raise
+ except httpx.HTTPError as exc:
+ # Wrap any transport or HTTP-status error into our own type so
+ # callers don't need an httpx import in their except clauses.
+ raise ESQLExecutionError(f"ES|QL execution failed: {exc}") from exc
+
+ took_ms = int((time.monotonic() - t0) * 1000)
+ columns = [col["name"] for col in data.get("columns", [])]
+ rows = data.get("values", [])
+ return ESQLResult(columns=columns, rows=rows, took_ms=took_ms)
diff --git a/services/api/app/workers/hunt_scheduler.py b/services/api/app/workers/hunt_scheduler.py
index 8b7c3eb93..1154ba642 100644
--- a/services/api/app/workers/hunt_scheduler.py
+++ b/services/api/app/workers/hunt_scheduler.py
@@ -45,15 +45,21 @@ import asyncio
import logging
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime, timedelta
-from typing import Any
from sqlalchemy import select, text, update
from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.airgap import AirgapViolation
from app.core.config import settings
from app.db.database import AsyncSessionLocal
from app.models.case import Case
from app.models.saved_hunt import SavedHunt
+from app.services.esql_runner import (
+ ESQLExecutionError,
+ ESQLNotConfigured,
+ resolve_es_credentials,
+ run_esql_query,
+)
logger = logging.getLogger(__name__)
@@ -165,7 +171,7 @@ async def _open_case_for_hits(db: AsyncSession, hunt: SavedHunt, hit_count: int)
case_number=f"HUNT-{hunt.id.hex[:8].upper()}-{int(datetime.now(UTC).timestamp())}",
title=f"Scheduled hunt fired: {hunt.name}",
description=(
- f"Saved hunt {hunt.name!r} returned {hit_count} hit(s) on its " f"scheduled run.\n\nOriginal NL question: {hunt.nl_query}"
+ f"Saved hunt {hunt.name!r} returned {hit_count} hit(s) on its scheduled run.\n\nOriginal NL question: {hunt.nl_query}"
),
case_type="hunt_finding",
priority="medium",
@@ -190,23 +196,61 @@ async def _open_case_for_hits(db: AsyncSession, hunt: SavedHunt, hit_count: int)
async def _execute_hunt(db: AsyncSession, hunt: SavedHunt) -> int:
"""Run the hunt's translated query and return the hit count.
- The current build does not embed a synchronous Elasticsearch client in
- the hunt scheduler — query execution lives in
- ``services.api.app.api.v1.endpoints.nl_query.execute_query`` and
- requires the request-scope settings + circuit breaker that the worker
- cannot easily reuse.
-
- For T3.4 the worker therefore returns ``0`` (no hits) — the schedule
- sweep, ``last_run_at`` bookkeeping, and case-open hook are all wired
- and exercised by tests, but no cases are opened in production until
- the follow-up swap-in below.
-
- # TODO(T3.4-followup): once the nl_query executor grows a
- # background-friendly entry point (no FastAPI deps), call it here
- # and return the row count. Until then a zero-result run is the
- # safest default — it won't paper over a real "no events" outcome.
+ Uses the shared :mod:`app.services.esql_runner` so the scheduler
+ and the request-scoped ``/nl-query/execute`` endpoint share one
+ code path for the outbound POST, the SSRF guard, and the air-gap
+ enforcement.
+
+ Falls back to ``0`` hits (and logs at ``info``) when:
+
+ * The saved hunt has no translated ES|QL stored. A NL question
+ that never produced a deterministic translation can still be
+ saved as a draft; on schedule we just skip it rather than
+ re-running the translator (LLM enhancement, network, retries —
+ not the worker's job).
+ * Elasticsearch credentials aren't configured. The worker stays
+ quiet in self-hosted dev where ES isn't wired up, and only
+ logs once per missing-credentials run.
+
+ Raises Elasticsearch transport / air-gap errors back to the caller,
+ where ``run_once`` records them via ``logger.exception`` and skips
+ the ``last_run_at`` bump so the hunt retries on the next tick.
"""
- return 0
+ _ = db # unused — kept in the signature for future hunt-specific reads
+ esql = (hunt.translated_query or {}).get("esql") if isinstance(hunt.translated_query, dict) else None
+ if not esql:
+ logger.info(
+ "hunt_scheduler.execute_skip hunt_id=%s reason=no_translated_esql",
+ hunt.id,
+ )
+ return 0
+
+ try:
+ es_url, es_api_key = resolve_es_credentials()
+ except ESQLNotConfigured:
+ logger.info(
+ "hunt_scheduler.execute_skip hunt_id=%s reason=es_not_configured",
+ hunt.id,
+ )
+ return 0
+
+ try:
+ result = await run_esql_query(
+ esql=esql,
+ es_url=es_url,
+ es_api_key=es_api_key,
+ max_rows=int(getattr(settings, "HUNT_SCHEDULER_MAX_ROWS", 500)),
+ )
+ except (AirgapViolation, ValueError, ESQLExecutionError) as exc:
+ # Let ``run_once`` mark this tick as failed and retry next sweep.
+ logger.warning(
+ "hunt_scheduler.execute_failed hunt_id=%s err=%s",
+ hunt.id,
+ type(exc).__name__,
+ )
+ raise
+
+ return len(result.rows)
# ---------------------------------------------------------------------------
@@ -314,7 +358,3 @@ __all__ = [
"_interval_seconds_for",
"_open_case_for_hits",
]
-
-
-def _settings_unused() -> Any: # pragma: no cover - guard for unused-import
- return settings
diff --git a/services/api/tests/test_esql_runner.py b/services/api/tests/test_esql_runner.py
new file mode 100644
index 000000000..bf92e1539
--- /dev/null
+++ b/services/api/tests/test_esql_runner.py
@@ -0,0 +1,486 @@
+"""Tests for the shared ES|QL runner — Track 3, T3.4 (`/hunt` NL surface).
+
+Pins the contract of :mod:`app.services.esql_runner`, the small async
+helper that both the request-scoped ``/nl-query/execute`` endpoint and
+the out-of-band saved-hunt scheduler call to execute ES|QL queries
+against Elasticsearch.
+
+Coverage map
+~~~~~~~~~~~~
+
+* :func:`_validate_es_url` — SSRF guard rejects hosts that don't match
+ the configured ES_URL, rejects non-HTTP(S) schemes, and reconstructs
+ the URL from validated parts only (no attacker-controlled path leak).
+* :func:`resolve_es_credentials` — explicit overrides win, falls back
+ to ``ES_URL`` / ``ELASTICSEARCH_URL`` settings, raises a typed
+ :class:`ESQLNotConfigured` when both sides come up empty so callers
+ can pick "skip" vs "error" semantics.
+* :func:`run_esql_query` — happy path returns columns + rows + took_ms,
+ appends ``LIMIT`` when missing, propagates the LIMIT the caller
+ supplied, surfaces transport errors as :class:`ESQLExecutionError`,
+ propagates :class:`AirgapViolation` unchanged when air-gap is on,
+ propagates :class:`ValueError` unchanged for SSRF guard failures.
+
+These tests are unit-scoped — we patch ``httpx.AsyncClient`` so the
+suite stays sub-second and runs in CI without a network. The full
+integration with the saved-hunt scheduler is exercised separately in
+``test_saved_hunts_endpoint.py``.
+
+Author: Track 3 / T3.4 (`/hunt` NL surface).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+from app.core.airgap import AirgapViolation
+from app.services import esql_runner
+from app.services.esql_runner import (
+ ESQLExecutionError,
+ ESQLNotConfigured,
+ ESQLResult,
+ _validate_es_url,
+ resolve_es_credentials,
+ run_esql_query,
+)
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+class _FakeSettings:
+ """Minimal stand-in for the Pydantic ``Settings`` singleton.
+
+ The production deployment reads ES connection fields via
+ ``getattr(settings, "ES_URL", None)`` so they don't have to be
+ declared on the :class:`Settings` model. The model itself uses
+ ``extra="ignore"``, which silently drops ``setattr`` for any field
+ that *isn't* declared — that makes ``monkeypatch.setattr`` unusable
+ against the real settings object for these fields.
+
+ A plain attribute bag dodges the problem entirely: ``getattr`` does
+ exactly what the runner expects, and unset fields fall through to
+ the runner's default just like in production.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ for k, v in kwargs.items():
+ setattr(self, k, v)
+
+
+def pin_es_settings(monkeypatch: pytest.MonkeyPatch):
+ """Replace the module-level settings with a fake configured for ES.
+
+ All tests in this module operate against ``http://es.local:9200`` so
+ the SSRF guard has a single configured host to compare against. The
+ fake exposes the legacy alias (``ELASTICSEARCH_URL``) as well, so
+ the resolver's fallback chain has consistent behaviour regardless
+ of which one the deployment actually configured.
+ """
+ fake = _FakeSettings(
+ ES_URL="http://es.local:9200",
+ ES_API_KEY="test-api-key",
+ ELASTICSEARCH_URL="http://es.local:9200",
+ OPENSEARCH_URL="http://localhost:9200",
+ )
+ monkeypatch.setattr(esql_runner, "settings", fake)
+ yield fake
+
+
+def _mock_httpx_client(
+ *,
+ json_payload: dict[str, Any] | None = None,
+ status_code: int = 200,
+ raise_on_post: Exception | None = None,
+) -> tuple[MagicMock, AsyncMock]:
+ """Build a mock ``httpx.AsyncClient`` context manager.
+
+ Returns ``(client_factory, post_mock)`` so tests can assert on the
+ post args (URL, headers, json body) without re-mocking the
+ response shape.
+ """
+ response = MagicMock()
+ response.status_code = status_code
+ response.json = MagicMock(return_value=json_payload or {"columns": [], "values": []})
+ if status_code >= 400:
+ response.raise_for_status = MagicMock(side_effect=httpx.HTTPStatusError("boom", request=MagicMock(), response=response))
+ else:
+ response.raise_for_status = MagicMock()
+
+ post_mock = AsyncMock(return_value=response)
+ if raise_on_post is not None:
+ post_mock = AsyncMock(side_effect=raise_on_post)
+
+ client = MagicMock()
+ client.post = post_mock
+ client_cm = MagicMock()
+ client_cm.__aenter__ = AsyncMock(return_value=client)
+ client_cm.__aexit__ = AsyncMock(return_value=None)
+
+ client_factory = MagicMock(return_value=client_cm)
+ return client_factory, post_mock
+
+
+# ---------------------------------------------------------------------------
+# _validate_es_url — SSRF guard
+# ---------------------------------------------------------------------------
+
+
+class TestValidateEsUrl:
+ """Direct tests of the SSRF guard.
+
+ The guard is the only line of defence between an attacker-controlled
+ URL (via a saved hunt row or future operator-supplied override) and
+ the outbound httpx call, so each invariant deserves a pinned test.
+ """
+
+ def test_accepts_configured_host(self, pin_es_settings) -> None:
+ # Same scheme, same host, same port → allowed. The returned URL
+ # must be reconstructed (scheme + netloc only) so any path or
+ # query in the input is discarded.
+ out = _validate_es_url("http://es.local:9200")
+ assert out == "http://es.local:9200"
+
+ def test_strips_user_supplied_path(self, pin_es_settings) -> None:
+ # The whole point of the reconstruct: an attacker who can
+ # influence the input URL can't smuggle in a path that points
+ # at another endpoint on the same host.
+ out = _validate_es_url("http://es.local:9200/_internal/secret")
+ assert out == "http://es.local:9200"
+ assert "_internal" not in out
+ assert "secret" not in out
+
+ def test_strips_user_supplied_query(self, pin_es_settings) -> None:
+ out = _validate_es_url("http://es.local:9200/_query?inject=1")
+ assert "?" not in out
+ assert "inject" not in out
+
+ def test_rejects_mismatched_host(self, pin_es_settings) -> None:
+ with pytest.raises(ValueError, match="not the configured host"):
+ _validate_es_url("http://attacker.example.com:9200")
+
+ def test_rejects_mismatched_port(self, pin_es_settings) -> None:
+ # Same host, different port — still a mismatch. ``netloc`` is
+ # ``host:port``, so this is one comparison, not two.
+ with pytest.raises(ValueError, match="not the configured host"):
+ _validate_es_url("http://es.local:9201")
+
+ def test_rejects_ftp_scheme(self, pin_es_settings) -> None:
+ # The scheme check is independent of the host check — a hostile
+ # input with the right host but a weird scheme should still 422.
+ with pytest.raises(ValueError, match="Unsupported URL scheme"):
+ _validate_es_url("ftp://es.local:9200")
+
+ def test_rejects_file_scheme(self, pin_es_settings) -> None:
+ # The crown jewel of SSRF — ``file://`` is the canonical
+ # path-traversal vector and must be refused even if the host
+ # matches. (urlparse parses ``file://es.local/etc/passwd``
+ # with that host; the scheme guard is what stops it.)
+ with pytest.raises(ValueError, match="Unsupported URL scheme"):
+ _validate_es_url("file://es.local/etc/passwd")
+
+ def test_falls_back_to_opensearch_url(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """When ``ES_URL`` is unset, the resolver tries OPENSEARCH_URL."""
+ fake = _FakeSettings(
+ ES_URL=None,
+ ELASTICSEARCH_URL=None,
+ OPENSEARCH_URL="http://opensearch.local:9200",
+ )
+ monkeypatch.setattr(esql_runner, "settings", fake)
+ out = _validate_es_url("http://opensearch.local:9200")
+ assert out == "http://opensearch.local:9200"
+
+
+# ---------------------------------------------------------------------------
+# resolve_es_credentials
+# ---------------------------------------------------------------------------
+
+
+class TestResolveEsCredentials:
+ """Pin the explicit-override-then-settings fallback chain.
+
+ Two callers exercise this from very different angles: the endpoint
+ (which always uses the settings — body-supplied URLs were removed
+ as a partial-SSRF mitigation) and the scheduler (which also uses
+ settings, but a future operator-only API might pass overrides).
+ """
+
+ def test_returns_settings_when_no_overrides(self, pin_es_settings) -> None:
+ url, key = resolve_es_credentials()
+ assert url == "http://es.local:9200"
+ assert key == "test-api-key"
+
+ def test_explicit_overrides_win(self, pin_es_settings) -> None:
+ url, key = resolve_es_credentials(
+ es_url="http://other.local:9200",
+ es_api_key="override-key",
+ )
+ assert url == "http://other.local:9200"
+ assert key == "override-key"
+
+ def test_raises_when_url_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ fake = _FakeSettings(ES_URL=None, ELASTICSEARCH_URL=None, ES_API_KEY="k")
+ monkeypatch.setattr(esql_runner, "settings", fake)
+ with pytest.raises(ESQLNotConfigured):
+ resolve_es_credentials()
+
+ def test_raises_when_key_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ fake = _FakeSettings(ES_URL="http://es.local:9200", ES_API_KEY=None)
+ monkeypatch.setattr(esql_runner, "settings", fake)
+ with pytest.raises(ESQLNotConfigured):
+ resolve_es_credentials()
+
+
+# ---------------------------------------------------------------------------
+# run_esql_query — happy paths
+# ---------------------------------------------------------------------------
+
+
+class TestRunEsqlQueryHappyPath:
+ """The 200-response shape pins the contract for both callers."""
+
+ def test_returns_columns_rows_and_took_ms(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ client_factory, _post_mock = _mock_httpx_client(
+ json_payload={
+ "columns": [{"name": "@timestamp", "type": "date"}, {"name": "host.name", "type": "keyword"}],
+ "values": [
+ ["2026-05-15T10:00:00Z", "host1"],
+ ["2026-05-15T10:01:00Z", "host2"],
+ ],
+ }
+ )
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ result = asyncio.run(
+ run_esql_query(
+ esql="FROM logs-* | LIMIT 10",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ )
+ )
+
+ assert isinstance(result, ESQLResult)
+ assert result.columns == ["@timestamp", "host.name"]
+ assert result.rows == [
+ ["2026-05-15T10:00:00Z", "host1"],
+ ["2026-05-15T10:01:00Z", "host2"],
+ ]
+ assert result.took_ms >= 0
+
+ def test_post_target_url_is_validated_and_rebuilt(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Even if the caller passes a URL with a path, the runner
+ reconstructs the target as ``<scheme>://<netloc>/_query``."""
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-*",
+ es_url="http://es.local:9200/some/internal/path", # path should be stripped
+ es_api_key="test-api-key",
+ )
+ )
+
+ # The post call must hit ``/_query`` against the validated host,
+ # *not* ``/some/internal/path/_query``.
+ args, kwargs = post_mock.call_args
+ called_url = args[0] if args else kwargs.get("url")
+ assert called_url == "http://es.local:9200/_query"
+
+ def test_appends_limit_when_caller_did_not(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-* | WHERE foo == 'bar'",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ max_rows=42,
+ )
+ )
+
+ _, kwargs = post_mock.call_args
+ query_sent = kwargs["json"]["query"]
+ assert "| LIMIT 42" in query_sent
+
+ def test_preserves_caller_supplied_limit(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """If the translator already emitted ``| LIMIT 10``, the runner
+ must not append a second LIMIT — Elasticsearch rejects two
+ LIMITs in a single query."""
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-* | LIMIT 10",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ max_rows=500,
+ )
+ )
+
+ _, kwargs = post_mock.call_args
+ query_sent = kwargs["json"]["query"]
+ # Exactly one LIMIT — and the one the caller supplied, not the
+ # max_rows default the runner would otherwise have appended.
+ assert query_sent.upper().count("| LIMIT") == 1
+ assert "| LIMIT 10" in query_sent
+
+ def test_limit_detection_is_case_insensitive(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """LLM-enhanced queries may lower-case ``LIMIT``. The detector
+ must still notice it and not double-append."""
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-* | limit 10",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ max_rows=500,
+ )
+ )
+
+ _, kwargs = post_mock.call_args
+ query_sent = kwargs["json"]["query"]
+ assert query_sent.upper().count("| LIMIT") == 1
+
+ def test_limit_inside_quoted_literal_does_not_skip_cap(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Regression for PR #144 review item: a tenant admin who can
+ save hunts could bypass ``max_rows`` by embedding the literal
+ ``| LIMIT`` token inside a quoted string in their ES|QL.
+
+ Before the line-anchored regex detector, this query::
+
+ FROM logs-* | WHERE message == "this includes | LIMIT 5"
+
+ passed the naive ``"| LIMIT" in esql.upper()`` substring check,
+ so the runner shipped it unmodified — letting the caller pull
+ unlimited rows back through the API. The detector now anchors
+ on a top-level pipe at the start of a line, which is how ES|QL
+ actually parses its pipes.
+ """
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ evil = 'FROM logs-* | WHERE message == "this includes | LIMIT 5"'
+ asyncio.run(
+ run_esql_query(
+ esql=evil,
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ max_rows=42,
+ )
+ )
+
+ _, kwargs = post_mock.call_args
+ query_sent = kwargs["json"]["query"]
+ # The runner MUST have appended its own cap — the quoted-string
+ # `| LIMIT 5` is just text in the WHERE clause, not a real pipe.
+ assert "\n| LIMIT 42" in query_sent, f"runner failed to append max_rows cap on quoted-LIMIT bypass; sent: {query_sent!r}"
+
+ def test_authorization_header_is_api_key(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """ES expects ``Authorization: ApiKey <key>``, not Bearer."""
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-*",
+ es_url="http://es.local:9200",
+ es_api_key="my-secret-key",
+ )
+ )
+
+ _, kwargs = post_mock.call_args
+ headers = kwargs["headers"]
+ assert headers["Authorization"] == "ApiKey my-secret-key"
+ assert headers["Content-Type"] == "application/json"
+
+
+# ---------------------------------------------------------------------------
+# run_esql_query — error paths
+# ---------------------------------------------------------------------------
+
+
+class TestRunEsqlQueryErrors:
+ """Each failure mode maps to a distinct exception so callers can
+ surface a precise error to the analyst (rather than a generic 500)."""
+
+ def test_mismatched_host_raises_value_error_before_post(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """SSRF guard fires *before* we open the httpx client, so a
+ hostile URL never hits the network."""
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ with pytest.raises(ValueError, match="not the configured host"):
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-*",
+ es_url="http://attacker.example.com:9200",
+ es_api_key="test-api-key",
+ )
+ )
+
+ post_mock.assert_not_awaited()
+
+ def test_http_status_error_wraps_into_esql_execution_error(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ client_factory, _post_mock = _mock_httpx_client(status_code=500)
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ with pytest.raises(ESQLExecutionError, match="ES|QL execution failed"):
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-*",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ )
+ )
+
+ def test_transport_error_wraps_into_esql_execution_error(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A network-level httpx error (timeout, conn refused, etc.) is
+ wrapped into ``ESQLExecutionError`` so callers don't need an
+ httpx import in their except clauses."""
+ client_factory, _post_mock = _mock_httpx_client(raise_on_post=httpx.ConnectError("connection refused"))
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ with pytest.raises(ESQLExecutionError, match="ES|QL execution failed"):
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-*",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ )
+ )
+
+ def test_airgap_violation_propagates_unchanged(self, pin_es_settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Air-gap is special: the endpoint surfaces it as a dedicated
+ 503, so the runner must propagate the original exception type
+ rather than wrap it in ``ESQLExecutionError``."""
+
+ # Pretend the air-gap guard fires for this URL.
+ def _explode(_url: str) -> None:
+ raise AirgapViolation("blocked by air-gap policy")
+
+ monkeypatch.setattr(esql_runner, "enforce_airgap_for_url", _explode)
+ client_factory, post_mock = _mock_httpx_client()
+ monkeypatch.setattr(esql_runner.httpx, "AsyncClient", client_factory)
+
+ with pytest.raises(AirgapViolation):
+ asyncio.run(
+ run_esql_query(
+ esql="FROM logs-*",
+ es_url="http://es.local:9200",
+ es_api_key="test-api-key",
+ )
+ )
+
+ # The air-gap guard fires before httpx is opened.
+ post_mock.assert_not_awaited()
diff --git a/services/api/tests/test_hunt_scheduler_execute.py b/services/api/tests/test_hunt_scheduler_execute.py
new file mode 100644
index 000000000..544885aee
--- /dev/null
+++ b/services/api/tests/test_hunt_scheduler_execute.py
@@ -0,0 +1,221 @@
+"""Unit tests for ``app.workers.hunt_scheduler._execute_hunt`` — Track 3, T3.4.
+
+We isolate ``_execute_hunt`` from Elasticsearch, the database session, and the
+``SavedHunt`` ORM by:
+
+* Faking the hunt object with a minimal attribute bag — only ``id`` and
+ ``translated_query`` are read.
+* Monkeypatching the two collaborators imported at module scope into the
+ worker — ``resolve_es_credentials`` and ``run_esql_query`` — so we can drive
+ every branch from pure-Python doubles.
+
+Why test it this way? The scheduler's value comes from how it *composes*
+those collaborators (skip cleanly when nothing is configured, surface real
+errors so ``run_once`` can retry, return the row count on success). Wiring up
+a real ``AsyncSession`` would test ``AsyncSession`` — not the composition.
+
+The four branches we lock in:
+
+#. Hunt missing translated ES|QL → quiet skip, returns ``0``.
+#. ES creds missing → quiet skip, returns ``0``.
+#. Happy path → returns ``len(rows)``.
+#. Transport / air-gap / value errors → propagated so ``run_once`` skips
+ ``last_run_at`` bump and retries on the next sweep.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.core.airgap import AirgapViolation
+from app.services.esql_runner import ESQLExecutionError, ESQLNotConfigured, ESQLResult
+from app.workers import hunt_scheduler
+
+
+def _make_hunt(translated: Any = None) -> Any:
+ """Return a stand-in for :class:`app.models.saved_hunt.SavedHunt`.
+
+ Only the two attributes ``_execute_hunt`` actually touches need to be
+ populated. We use a ``MagicMock`` rather than the SQLAlchemy model so the
+ test file doesn't pull in a live DB engine.
+ """
+ hunt = MagicMock()
+ hunt.id = uuid.uuid4()
+ hunt.translated_query = translated
+ return hunt
+
+
+def fake_db() -> Any:
+ """A throw-away DB session — ``_execute_hunt`` doesn't touch it today."""
+ return MagicMock()
+
+
+class TestExecuteHuntSkipPaths:
+ """Branches where the worker logs and returns ``0`` instead of raising.
+
+ Both are *expected* in production:
+
+ * A NL hunt saved as a draft has no translated ES|QL yet — re-translating
+ is the API endpoint's job, not the scheduler's.
+ * Self-hosted dev installs frequently run the API without ES wired up; we
+ want the scheduler to keep running quietly, not spam ``exception``.
+ """
+
+ async def test_skips_when_no_translated_query(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ hunt = _make_hunt(translated=None)
+ # If we reach the runner we've failed — pin a tripwire.
+ called = AsyncMock(side_effect=AssertionError("runner should not be called"))
+ monkeypatch.setattr(hunt_scheduler, "run_esql_query", called)
+
+ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ assert hits == 0
+ called.assert_not_called()
+
+ async def test_skips_when_translated_query_missing_esql_key(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ """``translated_query`` may exist but carry only KQL/SPL — that's a skip."""
+ hunt = _make_hunt(translated={"kql": "event.code:4625", "spl": "index=foo"})
+ called = AsyncMock(side_effect=AssertionError("runner should not be called"))
+ monkeypatch.setattr(hunt_scheduler, "run_esql_query", called)
+
+ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ assert hits == 0
+ called.assert_not_called()
+
+ async def test_skips_when_translated_query_is_not_a_dict(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Defensive: a malformed row shouldn't crash the sweep."""
+ hunt = _make_hunt(translated="just a string somehow") # type: ignore[arg-type]
+ called = AsyncMock(side_effect=AssertionError("runner should not be called"))
+ monkeypatch.setattr(hunt_scheduler, "run_esql_query", called)
+
+ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ assert hits == 0
+ called.assert_not_called()
+
+ async def test_skips_when_es_credentials_not_configured(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ hunt = _make_hunt(translated={"esql": "FROM logs"})
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "resolve_es_credentials",
+ MagicMock(side_effect=ESQLNotConfigured("no ES_URL")),
+ )
+ called = AsyncMock(side_effect=AssertionError("runner should not be called"))
+ monkeypatch.setattr(hunt_scheduler, "run_esql_query", called)
+
+ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ assert hits == 0
+ called.assert_not_called()
+
+
+class TestExecuteHuntHappyPath:
+ """When everything is wired up, return the row count the runner produced."""
+
+ async def test_returns_row_count_from_runner(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ hunt = _make_hunt(translated={"esql": "FROM logs | WHERE event.code == 4625"})
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "resolve_es_credentials",
+ MagicMock(return_value=("http://es.local:9200", "test-key")),
+ )
+ runner = AsyncMock(
+ return_value=ESQLResult(
+ columns=["@timestamp", "event.code"],
+ rows=[
+ ["2026-05-15T00:00:00Z", 4625],
+ ["2026-05-15T00:01:00Z", 4625],
+ ["2026-05-15T00:02:00Z", 4625],
+ ],
+ took_ms=42,
+ )
+ )
+ monkeypatch.setattr(hunt_scheduler, "run_esql_query", runner)
+
+ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ assert hits == 3
+ runner.assert_awaited_once()
+ # Validate that the runner sees the ES|QL we stored, not a re-translation.
+ call_kwargs = runner.await_args.kwargs
+ assert call_kwargs["esql"] == "FROM logs | WHERE event.code == 4625"
+ assert call_kwargs["es_url"] == "http://es.local:9200"
+ assert call_kwargs["es_api_key"] == "test-key"
+
+ async def test_returns_zero_when_runner_returns_empty(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ hunt = _make_hunt(translated={"esql": "FROM logs"})
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "resolve_es_credentials",
+ MagicMock(return_value=("http://es.local:9200", "test-key")),
+ )
+ runner = AsyncMock(return_value=ESQLResult(columns=[], rows=[], took_ms=5))
+ monkeypatch.setattr(hunt_scheduler, "run_esql_query", runner)
+
+ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ assert hits == 0
+
+
+class TestExecuteHuntErrorPropagation:
+ """Errors the scheduler *cannot recover from on its own* must propagate.
+
+ ``run_once`` catches the exception, logs it, and skips the
+ ``last_run_at`` bump so the hunt retries on the next tick. If we
+ swallowed errors here we would silently mark broken hunts as "ran" and
+ they would never retry.
+ """
+
+ async def test_airgap_violation_propagates(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ hunt = _make_hunt(translated={"esql": "FROM logs"})
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "resolve_es_credentials",
+ MagicMock(return_value=("http://es.local:9200", "test-key")),
+ )
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "run_esql_query",
+ AsyncMock(side_effect=AirgapViolation("egress blocked")),
+ )
+
+ with pytest.raises(AirgapViolation):
+ await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ async def test_value_error_propagates(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ """SSRF guard mismatch surfaces as ``ValueError`` — must bubble up."""
+ hunt = _make_hunt(translated={"esql": "FROM logs"})
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "resolve_es_credentials",
+ MagicMock(return_value=("http://es.local:9200", "test-key")),
+ )
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "run_esql_query",
+ AsyncMock(side_effect=ValueError("host mismatch")),
+ )
+
+ with pytest.raises(ValueError, match="host mismatch"):
+ await hunt_scheduler._execute_hunt(fake_db, hunt)
+
+ async def test_esql_execution_error_propagates(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ hunt = _make_hunt(translated={"esql": "FROM logs"})
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "resolve_es_credentials",
+ MagicMock(return_value=("http://es.local:9200", "test-key")),
+ )
+ monkeypatch.setattr(
+ hunt_scheduler,
+ "run_esql_query",
+ AsyncMock(side_effect=ESQLExecutionError("ES 500")),
+ )
+
+ with pytest.raises(ESQLExecutionError):
+ await hunt_scheduler._execute_hunt(fake_db, hunt)