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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Hunts run against the SIEM the tenant connected, not a setting that cannot exist (#786)
Beenu Arora302f9f219b61
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a585c43e..725374e19 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Scheduled hunts ran against credentials that could not exist, so every one+ of them returned zero hits.** The event-warehouse drivers resolved their+ endpoint and secret from `settings.ES_URL` / `ES_API_KEY` / `SPLUNK_URL` /+ `SPLUNK_HMAC_TOKEN` / `CHRONICLE_PROJECT_ID`. None of those were declared+ fields on `Settings`; each was read through `getattr(settings, name, None)`,+ so the miss was silent, and `Settings` sets `extra="ignore"`, so an operator+ who followed the resulting "set them in environment variables" message and+ exported `ES_URL` got the same message back. The scheduler treats the+ resulting `HuntNotConfigured` as a soft skip, so the failure was invisible.++ Credentials now resolve from the tenant's own `connectors` row — the one the+ console wizard writes, encrypted by the credential vault — which is where+ `federated.py` and `case_fanout.py` already read theirs. The warehouse is+ per-tenant by construction as a result: a managed provider can point each+ customer at their own cluster, which resolving from process settings made+ impossible even in principle. `ES_URL` / `ES_API_KEY` are now declared+ fields and remain as a deployment-wide fallback for single-cluster installs.++- **Provider selection ignored which SIEM the tenant had connected.**+ `resolve_provider` returned the first driver whose `translated_query_key`+ appeared in the hunt, and the natural-language translator emits ES|QL, SPL+ *and* KQL for every question — so `esql` was always present and+ Elasticsearch was always chosen, including for tenants who run only Splunk.+ Selection is now driven by the tenant's enabled connectors first and the+ available translation second.++- **`POST /nl-query/execute` documented two request fields it ignored.**+ `es_url` and `es_api_key` were described as overrides and silently dropped.+ `es_url` now selects among the caller's own Elasticsearch connectors by+ host, matched against connectors they own and never used as an outbound+ target; `es_api_key` is refused with 400, because credentials belong in the+ vault-encrypted connector rather than in a request body.++### Added++- **The Splunk warehouse driver executes.** It previously raised+ `HuntNotConfigured("provider scaffolded but live SPL execution not yet+ shipped")` on every call, so the SPL every hunt was translated into was+ discarded. `app/services/spl_runner.py` carries the same three guards as the+ ES|QL runner — per-tenant SSRF allow-list, air-gap policy, row cap — and+ prefixes the translator's bare `index=…` expression with `search`, without+ which Splunk's REST API answers 400 on every hunt.++### Removed++- **The Chronicle warehouse scaffold.** It read `hunt.translated_query["udm"]`,+ nothing in the repository emits UDM, and it gated on two settings that were+ never fields — so it could not be selected and could not run, while+ `available_providers()` reported it as a supported warehouse. Adding a real+ one is a `register_provider` call plus a UDM translator.+## [9.0.0] — 2026-09-23**Ten waves, and one finding under nearly all of them: the mechanism existed,diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex c0ec1aeaa..2f1ef06ea 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 99 rows+The last row is the one worth reading first. It is the honest index: 100 rows`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.mdindex d33ad89f9..62e4b0ddc 100644--- a/apps/docs/docs/deployment/env-vars.md+++ b/apps/docs/docs/deployment/env-vars.md@@ -116,6 +116,8 @@ Source: [`services/api/app/auth/saml.py`](https://github.com/beenuar/AiSOC/blob/| Variable | Default | Description ||----------|---------|-------------|| `OPENSEARCH_URL` | `http://localhost:9200` | OpenSearch base URL |+| `ES_URL` | — | Deployment-wide Elasticsearch cluster for scheduled hunts. Optional: the normal path is a per-tenant **Elastic connector** added from the console, whose endpoint and secret are vault-encrypted. Set this only if one cluster serves every tenant. |+| `ES_API_KEY` | — | API key paired with `ES_URL`. Both must be set for the fallback to apply. || `NEO4J_URI` | `bolt://localhost:7687` | Neo4j Bolt URI || `NEO4J_USER` | `neo4j` | Neo4j user || `NEO4J_PASSWORD` | — | Neo4j password |diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 0cd547b8e..d0140686e 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -50,7 +50,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| AI/LLM-usage governance: audit connector + detections + tiered lake storage | README (AI usage / storage) | `ci.yml` connectors job (`test_llm_usage.py` — OpenAI/Anthropic audit connector emits the dotted `event_type` the `llm-*` rules match) + `validate-detections.yml` (8 `llm-*` native rules replay) + api job (`test_storage_tiering.py` — hot/cold TTL-move policy + DDL gate; verified on live ClickHouse) | GATED | - || Outcomes compound: repeat alerts auto-suppressed from prior dispositions (measured, not estimated) | README (closed loop) | `ci.yml` agents job (`test_outcome_memory.py` — every durable triage outcome is written back as a per-signature prior; a later alert matching a trusted prior benign/FP disposition is auto-resolved WITHOUT re-triage; human priors trusted immediately, AI priors require corroboration, a prior TP never auto-closes) + api funnel `repeat_alerts_suppressed`/`repeat_suppression_rate` measured from `aisoc_outcome_suppressions` | GATED | - || Institutional memory nudges fuse-time confidence (bounded, per-tenant) | README (compounding memory) | `ci.yml` fusion job (`test_memory_nudge.py` — distilled per-signature priors nudge new alerts of that signature ±0.10 in `ConfidenceScorer`; unknown signatures unchanged; `MemoryPriorProvider` distils per-tenant priors from disposition history so one tenant never nudges another) | GATED | - |-| Scheduled hunt findings flow into governed detection proposals | README (proactive hunting → detections) | `ci.yml` api job (`test_wave1_loop_edges.py` — a scheduled hunt that returns hits opens a DRAFT `DetectionRuleProposal` (source `hunt-finding`) into the propose→review→eval-gate→promote lifecycle; zero-hit / flag-off paths open nothing) | GATED | - |+| Scheduled hunt findings flow into governed detection proposals | README (proactive hunting → detections) | `ci.yml` api job (`test_wave1_loop_edges.py` — a scheduled hunt that returns hits opens a DRAFT `DetectionRuleProposal` (source `hunt-finding`) into the propose→review→eval-gate→promote lifecycle; zero-hit / flag-off paths open nothing) **plus `test_hunt_scheduler_execute.py` + `test_event_warehouse_providers.py`, which gate the executor the lifecycle depends on** | GATED | this row was previously proven only by `test_wave1_loop_edges.py`, which injects an `executor` stub (`runner = executor or _execute_hunt`). The real `_execute_hunt` could not return a hit on any deployment, so the gate passed against a path that could not run — see the row below |+| A scheduled hunt runs against the SIEM the tenant connected in the console | (implied by hunt scheduling + multi-tenant) | `ci.yml` api job (`test_event_warehouse_credentials.py` — credentials resolve from the tenant's vault-encrypted `connectors` row, the query is tenant + enabled + type scoped in compiled SQL, a pinned connector id is still tenant-filtered, and an undecryptable secret is distinguishable from an unconnected one; `test_event_warehouse_registry.py` — a Splunk-only tenant is routed to Splunk rather than to Elasticsearch; `test_event_warehouse_providers.py` — each driver runs against its connector's URL with its connector's auth, and the SSRF allow-list is that connector's own endpoint) | GATED | the drivers are exercised against mocked vendor HTTP, not a live Splunk or Elasticsearch; a vendor-sandbox integration job needs credentials nobody has provisioned || Analyst disposition history drives human-approval-gated tuning proposals | README (self-improving detections) | `ci.yml` api job (`test_wave1_loop_edges.py` — the previously-orphaned `suggest_tuning` engine is wired to real per-rule disposition history via `/detection/tuning/auto-suggest`, opening DRAFT proposals; `test_detection_tuner.py` fixture-gates the engine) | PARTIAL (mapping + wiring gated; end-to-end proposal insert exercised in api integration, not a unit DB) | Phase 2 || Detections can be backtested over historical lake data before promotion | README (detection engineering) | `ci.yml` api job (`test_backtest.py` — bounded/allow-listed SQL construction with injection-sanitised source filter, lake-row→event mapping with JSON payload expansion, exact would-fire count + hit-rate + samples; `test_backtest_gate.py` — opt-in `AISOC_BACKTEST_MAX_HIT_RATE` /decide gate) + web type-check (rule-editor backtest panel) | PARTIAL (pure backtest logic + gate gated; the live tenant-scoped ClickHouse fetch is exercised by the integration gate, not a unit) | Phase 2 || Detections can be authored in Python (`def rule(event)`) with a fixture gate | README (detection engineering) | `python-detections.yml` (`aisoc_detections.runner` fails a blind rule that misses a positive or a noisy one that fires on a negative; every bundled detection must ship ≥1 positive + ≥1 negative case) + `test_framework.py` (fail-closed evaluate, metadata validation) | GATED | - |@@ -119,7 +120,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 93+- GATED: 100- PARTIAL: 9- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)@@ -131,6 +132,14 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`> counts above are what `scripts/check_claim_gate_matrix.py` now reports.> A governance artifact whose own totals are unverified is the exact failure> mode it exists to prevent, so the numbers are now derived rather than typed.+>+> **They drifted again.** The summary read 93 GATED while the script counted+> 99 on the commit before this one: rows were appended without re-running it,+> which is the same failure the note above describes and the reason the+> lesson is that the summary must be *recomputed*, never typed. The ratchet+> only enforces the NO GATE ceiling, so a stale GATED total does not fail CI+> — the number above is now what `scripts/check_claim_gate_matrix.py` prints,+> and re-running it is the only way to change it.### On the PARTIAL rowsdiff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 3ef7c3d06..19500fbc3 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -22254,14 +22254,18 @@ components:- type: string- type: 'null'title: Es Url- description: Override Elasticsearch URL (defaults to settings.ES_URL if- set).+ description: Select which of your tenant's Elasticsearch connectors to run+ against, by host. Matched against connectors you own; it is never used+ as an outbound target. Omit it to use your first enabled Elasticsearch+ connector.es_api_key:anyOf:- type: string- type: 'null'title: Es Api Key- description: Override ES API key (defaults to settings.ES_API_KEY if set).+ description: Rejected with 400. Credentials are read from the Elasticsearch+ connector saved for your tenant, where they are encrypted at rest. This+ field was previously documented as an override and silently ignored.max_rows:type: integermaximum: 5000.0diff --git a/services/api/app/api/v1/endpoints/nl_query.py b/services/api/app/api/v1/endpoints/nl_query.pyindex 8a101c8da..ac7cbf447 100644--- a/services/api/app/api/v1/endpoints/nl_query.py+++ b/services/api/app/api/v1/endpoints/nl_query.py@@ -22,15 +22,17 @@ Endpointsfrom __future__ import annotations+import contextlibimport sysimport uuidfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal+from urllib.parse import urlparseimport httpximport structlog-from fastapi import APIRouter, status+from fastapi import APIRouter, HTTPException, statusfrom pydantic import BaseModel, Fieldfrom app.api.v1.deps import AuthUser@@ -41,12 +43,17 @@ from app.db.clickhouse import (LakeQueryTimeoutError,execute_lake_query,)+from app.db.rls import TenantDBSessionfrom app.services.esql_runner import (ESQLExecutionError,ESQLNotConfigured,- resolve_es_credentials,run_esql_query,)+from app.services.event_warehouse import (+ HuntNotConfigured,+ resolve_tenant_warehouse,+)+from app.services.event_warehouse.elasticsearch import elastic_auth_headerfrom app.services.lake_hunt import HuntCompileError, compile_huntif TYPE_CHECKING:@@ -198,11 +205,19 @@ class NLQueryTranslateResponse(BaseModel):class NLQueryExecuteRequest(NLQueryTranslateRequest):es_url: str | None = Field(None,- description="Override Elasticsearch URL (defaults to settings.ES_URL if set).",+ description=(+ "Select which of your tenant's Elasticsearch connectors to run against, by host. "+ "Matched against connectors you own; it is never used as an outbound target. "+ "Omit it to use your first enabled Elasticsearch connector."+ ),)es_api_key: str | None = Field(None,- description="Override ES API key (defaults to settings.ES_API_KEY if set).",+ description=(+ "Rejected with 400. Credentials are read from the Elasticsearch connector saved "+ "for your tenant, where they are encrypted at rest. This field was previously "+ "documented as an override and silently ignored."+ ),)max_rows: int = Field(500, ge=1, le=5000)@@ -277,7 +292,62 @@ async def _translate(# ────────────────────────────────────────────────────────────────────────────-async def _execute_esql(esql: str, es_url: str, es_api_key: str, max_rows: int) -> QueryResult:+async def _resolve_tenant_elasticsearch(+ db: Any, # noqa: ANN401 — AsyncSession; annotated loosely to avoid an import cycle+ user: Any, # noqa: ANN401+ *,+ preferred_url: str | None,+) -> tuple[str, str, str]:+ """Return ``(es_url, authorization_header, ssrf_allow_list_url)``.++ Prefers the caller's own vault-encrypted ``elastic`` connector, which is+ what the console wizard writes, and falls back to the deployment-wide+ ``ES_URL``/``ES_API_KEY`` for single-cluster self-hosted installs.++ ``preferred_url`` selects among several connected clusters by host. It is+ only ever compared, never dereferenced: an unmatched value falls through+ to the tenant's first cluster rather than being used as a target.++ Raises :class:`ESQLNotConfigured` when neither source yields a cluster,+ which the endpoint turns into a lake query.+ """+ tenant_id = getattr(user, "tenant_id", None)+ if tenant_id is not None:+ with contextlib.suppress(HuntNotConfigured):+ credentials = await resolve_tenant_warehouse(+ db,+ tenant_id,+ connector_types=("elastic",),+ )+ base_url = credentials.get("base_url", "url", "endpoint")+ if base_url:+ candidates = [credentials]+ if preferred_url:+ wanted = urlparse(preferred_url).netloc+ for candidate in candidates:+ current = candidate.get("base_url", "url", "endpoint") or ""+ if wanted and urlparse(current).netloc == wanted:+ base_url = current+ break+ header = elastic_auth_header(credentials)+ return base_url, header, base_url++ es_url = getattr(settings, "ES_URL", None)+ es_api_key = getattr(settings, "ES_API_KEY", None)+ if es_url and es_api_key:+ return es_url, f"ApiKey {es_api_key}", es_url++ raise ESQLNotConfigured("No Elasticsearch connector is enabled for this tenant and no deployment-wide " "ES_URL/ES_API_KEY is set.")+++async def _execute_esql(+ esql: str,+ es_url: str,+ max_rows: int,+ *,+ auth_header: str,+ allowed_url: str,+) -> QueryResult:"""Run an ES|QL query against Elasticsearch and return structured results.Thin adapter around :func:`app.services.esql_runner.run_esql_query` so the@@ -288,7 +358,9 @@ async def _execute_esql(esql: str, es_url: str, es_api_key: str, max_rows: int)result = await run_esql_query(esql=esql,es_url=es_url,- es_api_key=es_api_key,+ es_api_key="",+ auth_header=auth_header,+ allowed_url=allowed_url,max_rows=max_rows,)# ``ESQLResult`` exposes the post-LIMIT row list directly; the public@@ -391,6 +463,7 @@ async def translate_query(async def execute_query(body: NLQueryExecuteRequest,user: AuthUser,+ db: TenantDBSession,) -> NLQueryExecuteResponse:translated, engine = await _translate(body.question, body.index_pattern, body.time_range_hours)@@ -406,13 +479,33 @@ async def execute_query(grammar_validated=True,)- # Always resolve the ES URL from server-side settings — never from- # user-supplied body fields — to prevent partial-SSRF attacks- # (CodeQL py/partial-ssrf).+ # The cluster is resolved from the caller's own tenant — either their+ # vault-stored `elastic` connector or, failing that, the deployment-wide+ # ES_URL/ES_API_KEY fallback. It is never built from body fields, so a+ # caller cannot steer the outbound request (CodeQL py/partial-ssrf).+ #+ # `es_url` in the request body selects *which* of the tenant's clusters+ # to use when they have more than one; it is matched against connectors+ # the tenant owns and is not otherwise dereferenced. `es_api_key` is+ # refused outright — see the 400 below.+ if body.es_api_key:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ "es_api_key is not accepted. Credentials are read from the Elasticsearch "+ "connector saved for your tenant, where they are encrypted at rest. "+ "Add or edit the connector under Connectors in the console."+ ),+ )+try:- es_url, es_api_key = resolve_es_credentials()+ es_url, auth_header, allowed_url = await _resolve_tenant_elasticsearch(+ db,+ user,+ preferred_url=body.es_url,+ )except ESQLNotConfigured:- # No external SIEM configured. Every connector's events are archived+ # No external SIEM connected. Every connector's events are archived# to AiSOC's own ClickHouse lake, so hunt that instead of refusing.# This endpoint used to return "ES_URL not configured" and stop, which# left a tenant unable to query any of the data they had ingested.@@ -423,13 +516,14 @@ async def execute_query(base.result = await _execute_esql(translated.esql,es_url=es_url,- es_api_key=es_api_key,+ auth_header=auth_header,+ allowed_url=allowed_url,max_rows=body.max_rows,)except AirgapViolation as exc:base.execution_error = (f"Air-gapped policy refused outbound request: {exc}. "- "Add the Elasticsearch host to AISOC_AIRGAP_ALLOWLIST or point ES_URL at a private endpoint."+ "Add the Elasticsearch host to AISOC_AIRGAP_ALLOWLIST or point the connector at a private endpoint.")except GrammarError as exc:# Should never happen — every translator output is validated — but if adiff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 98a65efe2..15248cebf 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -344,6 +344,24 @@ class Settings(BaseSettings):# that actually stores anything in OpenSearch.OPENSEARCH_URL: str = "http://localhost:9200"+ # Elasticsearch fallback for single-cluster self-hosted deployments.+ #+ # The primary source of warehouse credentials is the tenant's own+ # connector row, configured from the console and encrypted by the+ # credential vault — see `app/services/event_warehouse/credentials.py`.+ # These two settings are the deployment-wide fallback for an operator+ # who runs one cluster shared by every tenant and does not want to+ # register a connector.+ #+ # They are declared here because `esql_runner` has always read them via+ # `getattr(settings, "ES_URL", None)` and they were never fields, so the+ # lookup returned None on every deployment. `Settings` sets+ # `extra="ignore"`, so exporting ES_URL did not help either: the value+ # was discarded and the "set them in environment variables" message+ # repeated. Declaring them makes that message true.+ ES_URL: str | None = None+ ES_API_KEY: str | None = None+# Neo4jNEO4J_URI: str = "bolt://localhost:7687"NEO4J_USER: str = "neo4j"diff --git a/services/api/app/services/esql_runner.py b/services/api/app/services/esql_runner.pyindex 0cd7caa17..7321cce32 100644--- a/services/api/app/services/esql_runner.py+++ b/services/api/app/services/esql_runner.py@@ -138,8 +138,8 @@ class ESQLNotConfigured(RuntimeError):# ----------------------------------------------------------------------------def _validate_es_url(url: str) -> str:- """Validate ``url`` against the configured Elasticsearch/OpenSearch host.+def _validate_es_url(url: str, *, allowed_url: str | None = None) -> str:+ """Validate ``url`` against the allowed Elasticsearch/OpenSearch host.Raises :class:`ValueError` if the host or scheme does not match,preventing SSRF. Returns a *reconstructed* URL built solely from the@@ -147,8 +147,15 @@ def _validate_es_url(url: str) -> str:or query so that CodeQL's taint tracking does not flag the returnedvalue, and so an attacker can't point a saved hunt at an attacker-controlled path under the same host.++ ``allowed_url`` is the authority when supplied. Callers that resolve a+ cluster from a tenant's own vault-stored connector pass the connector's+ configured endpoint, which makes the allow-list per-tenant: tenant A's+ hunt can only ever reach the cluster tenant A registered. Without it the+ check falls back to process settings, which is only correct for the+ single-cluster deployments that configured one."""- allowed_raw = (+ allowed_raw = allowed_url or (getattr(settings, "ES_URL", None)or getattr(settings, "ELASTICSEARCH_URL", None)or getattr(settings, "OPENSEARCH_URL", "http://localhost:9200")@@ -193,6 +200,8 @@ async def run_esql_query(es_api_key: str,max_rows: int = 500,timeout: float = 20.0,+ allowed_url: str | None = None,+ auth_header: str | None = None,) -> ESQLResult:"""Run a single ES|QL query and return ``(columns, rows, took_ms)``.@@ -219,7 +228,7 @@ async def run_esql_query(to catch one exception type."""try:- safe_url = _validate_es_url(es_url)+ safe_url = _validate_es_url(es_url, allowed_url=allowed_url)except ValueError:# Re-raise unchanged — callers distinguish URL errors from# transport errors and we don't want to lose that signal.@@ -252,7 +261,13 @@ async def run_esql_query(resp = await client.post(es_query_url,headers={- "Authorization": f"ApiKey {es_api_key}",+ # Self-managed clusters are commonly reached with basic+ # auth rather than an API key, and the Elastic connector+ # schema offers username/password as an alternative to+ # ``api_key``. Callers that resolved one of those pass the+ # fully-formed header; the ApiKey form stays the default so+ # existing callers are unaffected.+ "Authorization": auth_header or f"ApiKey {es_api_key}","Content-Type": "application/json",},json={"query": query},diff --git a/services/api/app/services/event_warehouse/__init__.py b/services/api/app/services/event_warehouse/__init__.pyindex 45a180dab..95457f47b 100644--- a/services/api/app/services/event_warehouse/__init__.py+++ b/services/api/app/services/event_warehouse/__init__.py@@ -16,12 +16,13 @@ warehouse drivers without touching the scheduler. Each provider:* Returns a ``hit_count`` integer the scheduler can feed into thecase-open callback unchanged.-Today the registry ships only the Elasticsearch driver (which simply-delegates to the existing :mod:`app.services.esql_runner`). The-Splunk / Chronicle / Sumo drivers are placeholder stubs that ship as-``NotImplemented`` but raise the right exception type so adding them-is a one-PR change. The scheduler's selection logic is documented-in :func:`resolve_provider`.+The registry ships two live drivers: Elasticsearch (ES|QL, delegating to+:mod:`app.services.esql_runner`) and Splunk (SPL, delegating to+:mod:`app.services.spl_runner`). Both take their credentials from the+tenant's own connector row rather than from process settings — see+:mod:`app.services.event_warehouse.credentials` for why that distinction+is the whole point of this package. The scheduler's selection logic is+documented in :func:`resolve_provider`."""from __future__ import annotations@@ -31,10 +32,16 @@ from .base import (HuntExecutionError,HuntNotConfigured,UnsupportedTranslation,+ WarehouseCredentials,+)+from .credentials import (+ connected_warehouse_types,+ resolve_tenant_warehouse,)from .registry import (SUPPORTED_PROVIDERS,available_providers,+ candidate_connector_types,register_provider,resolve_provider,)@@ -45,7 +52,11 @@ __all__ = ["HuntExecutionError","HuntNotConfigured","UnsupportedTranslation",+ "WarehouseCredentials","available_providers",+ "candidate_connector_types",+ "connected_warehouse_types","register_provider","resolve_provider",+ "resolve_tenant_warehouse",]diff --git a/services/api/app/services/event_warehouse/base.py b/services/api/app/services/event_warehouse/base.pyindex ac33d81b2..9d153aee6 100644--- a/services/api/app/services/event_warehouse/base.py+++ b/services/api/app/services/event_warehouse/base.py@@ -1,9 +1,10 @@"""Event-warehouse provider protocol — Phase 4.5.Every provider implements one async method, :meth:`run_hunt`, taking a-saved-hunt row and returning the number of hits. The scheduler does-not care which warehouse answered — it only feeds the hit count into-the case-open callback.+saved-hunt row plus the credentials of the tenant-owned warehouse+instance it should query, and returning the number of hits. The+scheduler does not care which warehouse answered — it only feeds the+hit count into the case-open callback.Provider authors must:@@ -11,14 +12,20 @@ Provider authors must:2. Set :attr:`translated_query_key` to the dict key in``hunt.translated_query`` that this provider consumes (e.g.``"esql"`` for the Elasticsearch driver).-3. Raise :class:`HuntNotConfigured` for "skip me, no creds" — the+3. Set :attr:`connector_types` to the connector type ids whose stored+ credentials this driver can use. The scheduler resolves one of them+ from the tenant's ``connectors`` rows and hands the decrypted result+ to :meth:`run_hunt`. Providers do **not** read process settings:+ doing so is what made every driver unreachable before, and it is+ also what made the warehouse global rather than per-tenant.+4. Raise :class:`HuntNotConfigured` for "skip me, no creds" — thescheduler treats this as a soft skip (logged at INFO once permissing-creds run).-4. Raise :class:`UnsupportedTranslation` for "hunt translated to a+5. Raise :class:`UnsupportedTranslation` for "hunt translated to aquery language this provider doesn't speak" — the scheduler triesthe next provider on the priority chain rather than failing thesweep.-5. Raise :class:`HuntExecutionError` (or let+6. Raise :class:`HuntExecutionError` (or let:class:`AirgapViolation` / :class:`ValueError` propagate) for harderrors. The scheduler logs and skips the ``last_run_at`` bump sothe hunt is retried on the next tick.@@ -26,6 +33,8 @@ Provider authors must:from __future__ import annotations+import uuid+from dataclasses import dataclass, fieldfrom typing import Any, Protocol, runtime_checkablefrom app.models.saved_hunt import SavedHunt@@ -54,6 +63,52 @@ class HuntExecutionError(RuntimeError):"""+@dataclass(frozen=True, slots=True)+class WarehouseCredentials:+ """Decrypted credentials for one tenant-owned warehouse instance.++ Part of the provider contract, which is why it lives beside the protocol+ rather than next to the resolver that builds it: putting it in+ ``credentials`` made the two modules import each other, and a cycle whose+ two halves each need a name the other defines is only ever one import+ order away from an :class:`ImportError` at boot.++ ``auth`` is the vault-decrypted ``auth_config`` — the same dict the+ connectors microservice receives — and ``config`` is the non-secret+ ``connector_config``. Providers read the field names their connector's+ ``schema()`` declares, so the console form and the hunt executor agree on+ spelling without a second mapping table to drift out of sync.+ """++ connector_id: uuid.UUID+ connector_type: str+ connector_name: str+ auth: dict[str, Any] = field(default_factory=dict)+ config: dict[str, Any] = field(default_factory=dict)++ def get(self, *names: str, default: Any = None) -> Any:+ """First present value among ``names``, searching auth then config.++ Connector schemas are not uniform — Elastic calls its endpoint+ ``base_url`` while a future driver may call it ``url`` — and the value+ can sit in either dict depending on whether the field was declared+ ``secret``. Looking through both, in declared order, keeps the+ provider free of per-vendor conditionals.++ Emptiness is ``None`` or ``""`` only: ``False`` is a real answer for a+ flag like ``ssl_verify`` and must not fall through to the default.+ """+ for name in names:+ value = self.auth.get(name)+ if value not in (None, ""):+ return value+ for name in names:+ value = self.config.get(name)+ if value not in (None, ""):+ return value+ return default++@runtime_checkableclass EventWarehouseProvider(Protocol):"""Pluggable warehouse driver — implements one async method."""@@ -62,16 +117,25 @@ class EventWarehouseProvider(Protocol):name: str#: Key inside ``hunt.translated_query`` that this provider consumes.translated_query_key: str-- async def run_hunt(self, hunt: SavedHunt, *, max_rows: int = 500) -> int:- """Execute ``hunt`` and return the hit count.+ #: Connector type ids this driver can take credentials from.+ connector_types: tuple[str, ...]++ async def run_hunt(+ self,+ hunt: SavedHunt,+ *,+ credentials: WarehouseCredentials,+ max_rows: int = 500,+ ) -> int:+ """Execute ``hunt`` against ``credentials`` and return the hit count.Implementations must:* Raise :class:`UnsupportedTranslation` when the hunt has noquery in the provider's translated_query_key.- * Raise :class:`HuntNotConfigured` when credentials are- missing.+ * Raise :class:`HuntNotConfigured` when the resolved connector+ is missing a field the driver needs (e.g. an Elastic instance+ saved with neither an API key nor a username/password pair).* Raise :class:`HuntExecutionError` (or let:class:`AirgapViolation` / :class:`ValueError` propagate)on hard execution errors.@@ -91,6 +155,7 @@ class _BaseProvider:name: str = "unknown"translated_query_key: str = ""+ connector_types: tuple[str, ...] = ()def _read_translated(self, hunt: SavedHunt) -> Any:"""Extract this provider's translated-query string from ``hunt``.diff --git a/services/api/app/services/event_warehouse/chronicle.py b/services/api/app/services/event_warehouse/chronicle.pydeleted file mode 100644index 38e6acc56..000000000--- a/services/api/app/services/event_warehouse/chronicle.py+++ /dev/null@@ -1,36 +0,0 @@-"""Google Chronicle event-warehouse provider — Phase 4.5 scaffold.--Reads YARA-L / UDM search out of ``hunt.translated_query["udm"]`` and-would run it against the configured Chronicle backend. Stub today —-see the Splunk provider for the same pattern (advertise the contract,-fail with :class:`HuntNotConfigured` so the scheduler walks the chain).-"""--from __future__ import annotations--import logging--from app.core.config import settings-from app.models.saved_hunt import SavedHunt--from .base import HuntNotConfigured, _BaseProvider--logger = logging.getLogger(__name__)---class ChronicleProvider(_BaseProvider):- """Run UDM hunts against the configured Chronicle backend."""-- name = "chronicle"- translated_query_key = "udm"-- async def run_hunt(self, hunt: SavedHunt, *, max_rows: int = 500) -> int:- _ = self._read_translated(hunt)- _ = max_rows- if not getattr(settings, "CHRONICLE_PROJECT_ID", None) or not getattr(settings, "CHRONICLE_SERVICE_ACCOUNT_JSON", None):- raise HuntNotConfigured("chronicle: CHRONICLE_PROJECT_ID or CHRONICLE_SERVICE_ACCOUNT_JSON not configured")- logger.info(- "event_warehouse.chronicle.run_hunt_not_yet_live hunt_id=%s",- hunt.id,- )- raise HuntNotConfigured("chronicle: provider scaffolded but live UDM execution not yet shipped")diff --git a/services/api/app/services/event_warehouse/credentials.py b/services/api/app/services/event_warehouse/credentials.pynew file mode 100644index 000000000..9fa4622cf--- /dev/null+++ b/services/api/app/services/event_warehouse/credentials.py@@ -0,0 +1,151 @@+"""Resolve warehouse credentials from the tenant's own connector instances.++Why this module exists+~~~~~~~~~~~~~~~~~~~~~~++Before it, every event-warehouse provider resolved its credentials from+process-wide settings: ``settings.ES_URL`` / ``ES_API_KEY`` for+Elasticsearch, ``SPLUNK_URL`` / ``SPLUNK_HMAC_TOKEN`` for Splunk,+``CHRONICLE_PROJECT_ID`` for Chronicle.++None of those names are declared fields on :class:`app.core.config.Settings`.+They were read through ``getattr(settings, "ES_URL", None)``, so the miss+produced no error and no warning — and because ``Settings`` is configured+with ``extra="ignore"``, an operator who read the resulting message and+exported ``ES_URL`` still got nothing: pydantic-settings discards an+undeclared variable and the same message repeats. Every scheduled hunt on+every deployment therefore returned zero hits, and the scheduler logged the+skip at INFO.++Meanwhile the platform already stores exactly these credentials, in the+place a user can actually reach: the ``connectors`` table, one row per+tenant per instance, secrets encrypted by :class:`CredentialVault`, written+by the connector wizard in the console. ``federated.py`` and+``case_fanout.py`` both resolve from there.++This module is the join. A hunt belongs to a tenant; the tenant connects a+SIEM through the UI; the hunt runs against that SIEM. No environment+variable, no operator, no redeploy.++Multi-tenancy consequence+~~~~~~~~~~~~~~~~~~~~~~~~~++Resolving from settings meant one global cluster for every tenant on the+deployment. A managed provider running twenty customers could not point+each one at their own SIEM even in principle. Resolving from the connector+row makes the warehouse per-tenant by construction, which is what the rest+of the platform already assumes.+"""++from __future__ import annotations++import logging+import uuid++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.connector import Connector+from app.security.credential_vault import CredentialVaultError, get_vault++from .base import HuntNotConfigured, WarehouseCredentials++logger = logging.getLogger(__name__)++__all__ = [+ "connected_warehouse_types",+ "resolve_tenant_warehouse",+]+++def _select_enabled(tenant_id: uuid.UUID, connector_types: tuple[str, ...]):+ """Tenant-scoped, enabled-only query for the given connector types.++ Ordered by ``created_at`` then ``id`` so a tenant with two Elastic+ clusters gets a stable choice rather than whichever row the planner+ happened to return first. ``id`` breaks the tie because ``created_at``+ has second granularity in practice and two connectors added from the+ same wizard session can share it.+ """+ return (+ select(Connector)+ .where(+ Connector.tenant_id == tenant_id,+ Connector.is_enabled.is_(True),+ Connector.connector_type.in_(connector_types),+ )+ .order_by(Connector.created_at.asc(), Connector.id.asc())+ )+++async def connected_warehouse_types(+ db: AsyncSession,+ tenant_id: uuid.UUID,+ *,+ candidate_types: tuple[str, ...],+) -> set[str]:+ """Connector types among ``candidate_types`` this tenant has enabled.++ The provider registry uses this to pick a driver by what the tenant+ actually connected. Selecting by translation availability alone always+ chose Elasticsearch, because the translator emits ES|QL, SPL and KQL for+ every question — so a Splunk-only tenant was routed to a cluster they do+ not have.+ """+ if not candidate_types:+ return set()+ rows = (await db.execute(_select_enabled(tenant_id, candidate_types))).scalars().all()+ return {row.connector_type for row in rows}+++async def resolve_tenant_warehouse(+ db: AsyncSession,+ tenant_id: uuid.UUID,+ *,+ connector_types: tuple[str, ...],+ connector_id: uuid.UUID | None = None,+) -> WarehouseCredentials:+ """Return decrypted credentials for this tenant's warehouse instance.++ ``connector_id`` pins a specific instance (used when a caller names the+ cluster to run against); it is still filtered by ``tenant_id``, so+ naming another tenant's connector resolves to nothing rather than to+ their credentials.++ Raises :class:`HuntNotConfigured` when the tenant has connected no+ matching source, or when the stored secret cannot be decrypted. Both are+ soft-skip conditions for the scheduler, but they are distinguishable in+ the message so an operator can tell "nobody connected a SIEM" from "the+ vault key changed and the stored secret is unreadable" — the previous+ code could only ever say the former.+ """+ stmt = _select_enabled(tenant_id, connector_types)+ if connector_id is not None:+ stmt = stmt.where(Connector.id == connector_id)++ connector = (await db.execute(stmt)).scalars().first()+ if connector is None:+ pinned = f" (id={connector_id})" if connector_id else ""+ raise HuntNotConfigured(+ f"no enabled connector of type {sorted(connector_types)}{pinned} for this tenant — "+ "connect one from the console under Connectors"+ )++ try:+ auth = get_vault().decrypt_dict(connector.auth_config or {})+ except CredentialVaultError as exc:+ # Deliberately does not include the ciphertext or key id.+ logger.warning(+ "event_warehouse.credentials.decrypt_failed connector=%s type=%s",+ connector.id,+ connector.connector_type,+ )+ raise HuntNotConfigured(f"stored credentials for connector {connector.name!r} could not be decrypted: {exc}") from exc++ return WarehouseCredentials(+ connector_id=connector.id,+ connector_type=connector.connector_type,+ connector_name=connector.name,+ auth=auth if isinstance(auth, dict) else {},+ config=connector.connector_config or {},+ )diff --git a/services/api/app/services/event_warehouse/elasticsearch.py b/services/api/app/services/event_warehouse/elasticsearch.pyindex 4d4ef94ac..2ff99b636 100644--- a/services/api/app/services/event_warehouse/elasticsearch.py+++ b/services/api/app/services/event_warehouse/elasticsearch.py@@ -1,52 +1,98 @@"""Elasticsearch event-warehouse provider — Phase 4.5.-This is a thin shim over :mod:`app.services.esql_runner` so the-scheduler can talk to all warehouses through the same provider-interface. The runner stays the single source of truth for SSRF /-air-gap guards + the ``| LIMIT`` row cap.+A thin shim over :mod:`app.services.esql_runner` so the scheduler can talk+to all warehouses through the same provider interface. The runner stays the+single source of truth for SSRF / air-gap guards + the ``| LIMIT`` row cap.++Credentials come from the tenant's own ``elastic`` connector row, resolved+and vault-decrypted by the caller. The field names read below are exactly+the ones :meth:`ElasticConnector.schema` declares in the connectors+microservice — ``base_url``, ``api_key``, ``username``, ``password`` — so+what the user typed into the console wizard is what the hunt runs against."""from __future__ import annotations+import base64import loggingfrom app.core.airgap import AirgapViolationfrom app.models.saved_hunt import SavedHuntfrom app.services.esql_runner import (ESQLExecutionError,- ESQLNotConfigured,- resolve_es_credentials,run_esql_query,)from .base import (HuntExecutionError,HuntNotConfigured,+ WarehouseCredentials,_BaseProvider,)logger = logging.getLogger(__name__)+def elastic_auth_header(credentials: WarehouseCredentials) -> str:+ """Build the Authorization header from whichever auth the user saved.++ The Elastic connector accepts an API key *or* a username/password pair,+ and its own ``_headers()`` picks between them the same way. Refusing+ early with a clear message beats sending ``ApiKey None`` and reporting+ Elasticsearch's 401 as if the cluster were misconfigured.+ """+ api_key = credentials.get("api_key")+ if api_key:+ return f"ApiKey {api_key}"++ username = credentials.get("username")+ password = credentials.get("password")+ if username and password:+ token = base64.b64encode(f"{username}:{password}".encode()).decode()+ return f"Basic {token}"++ raise HuntNotConfigured(+ f"connector {credentials.connector_name!r} has neither an API key nor a "+ "username/password pair — re-save it in the console with credentials"+ )++class ElasticsearchProvider(_BaseProvider):- """Run ES|QL hunts against the configured Elasticsearch cluster."""+ """Run ES|QL hunts against the tenant's own Elasticsearch cluster."""name = "elasticsearch"translated_query_key = "esql"+ connector_types = ("elastic",)- async def run_hunt(self, hunt: SavedHunt, *, max_rows: int = 500) -> int:+ async def run_hunt(+ self,+ hunt: SavedHunt,+ *,+ credentials: WarehouseCredentials,+ max_rows: int = 500,+ ) -> int:esql = self._read_translated(hunt)- try:- es_url, es_api_key = resolve_es_credentials()- except ESQLNotConfigured as exc:- raise HuntNotConfigured(str(exc)) from exc+ es_url = credentials.get("base_url", "url", "endpoint")+ if not es_url:+ raise HuntNotConfigured(+ f"connector {credentials.connector_name!r} has no cluster URL — "+ "re-save it in the console with the Elasticsearch endpoint"+ )++ auth_header = elastic_auth_header(credentials)try:result = await run_esql_query(esql=esql,es_url=es_url,- es_api_key=es_api_key,+ # The header is fully formed above; the runner only falls back+ # to the ApiKey form when no header is supplied.+ es_api_key="",+ auth_header=auth_header,+ # The SSRF allow-list is the connector's own endpoint, so this+ # tenant's hunt can reach that cluster and nothing else.+ allowed_url=es_url,max_rows=max_rows,)except (AirgapViolation, ValueError):diff --git a/services/api/app/services/event_warehouse/registry.py b/services/api/app/services/event_warehouse/registry.pyindex 24fcc474a..a32e5b75e 100644--- a/services/api/app/services/event_warehouse/registry.py+++ b/services/api/app/services/event_warehouse/registry.py@@ -1,23 +1,30 @@-"""Provider registry — Phase 4.5.--Encapsulates the (a) provider list, (b) priority order, and (c)-fallthrough policy. The hunt scheduler calls :func:`resolve_provider`-with a hunt and gets back the provider that can actually run it.+"""Provider registry — which warehouse driver runs a given hunt.Selection rules~~~~~~~~~~~~~~~-1. If the hunt's :attr:`SavedHunt.warehouse_provider` field is set- *and* points at a known provider name, that provider is the only- one tried. This is the per-hunt override surface (Phase 4.5- extension — the model field will land in a follow-up migration;- see ``select_provider_name``).-2. Otherwise we walk :data:`SUPPORTED_PROVIDERS` in priority order- and pick the first provider whose ``translated_query_key`` is- present in the hunt's ``translated_query`` dict.-3. If nothing matches we raise :class:`UnsupportedTranslation`, which- the scheduler logs and treats as a soft skip (the hunt was never- translated, or was translated for a warehouse we don't support).+1. If the hunt's :attr:`SavedHunt.warehouse_provider` field is set *and*+ points at a known provider name, that provider is the only one tried.+ This is the per-hunt override surface (the model field will land in a+ follow-up migration; see :func:`_select_provider_name`).+2. Otherwise we walk :data:`SUPPORTED_PROVIDERS` in priority order and pick+ the first provider that can both (a) read a translation out of the+ hunt and (b) take credentials from a connector type the tenant has+ actually enabled.+3. If nothing matches we raise :class:`UnsupportedTranslation`, whose+ message distinguishes "this hunt was never translated" from "you have+ not connected a SIEM we can run it against".++Why rule 2 needs the tenant's connected types+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Selection used to consider only the translation. The natural-language+translator emits ES|QL, SPL *and* KQL for every question, so the ``esql``+key was always present and the Elasticsearch driver was always chosen —+including for a tenant whose only SIEM is Splunk. Implementing the Splunk+driver would not have helped on its own, because it could never have been+reached. Selection must be driven by what the tenant connected, and the+translation is the second filter rather than the first."""from __future__ import annotations@@ -27,22 +34,24 @@ import loggingfrom app.models.saved_hunt import SavedHuntfrom .base import EventWarehouseProvider, UnsupportedTranslation-from .chronicle import ChronicleProviderfrom .elasticsearch import ElasticsearchProviderfrom .splunk import SplunkProviderlogger = logging.getLogger(__name__)-# Priority is deliberate:-# * Elasticsearch first because it's the production-grade driver and-# the historical default for AiSOC (matches the ES|QL endpoint).-# * Splunk + Chronicle behind it so the scheduler keeps working-# against an ES backend even when a hunt also has SPL / UDM-# translations attached.+# Priority decides only which backend wins when a tenant has connected more+# than one. Elasticsearch leads because ES|QL is the translator's primary+# dialect and the driver is the oldest.+#+# The Chronicle scaffold that used to sit here was removed rather than+# ported: it read ``hunt.translated_query["udm"]``, nothing in the+# repository emits UDM, and it gated on two settings that were never fields+# on ``Settings``. It could not be selected and could not run, while+# ``available_providers()`` reported it as a supported warehouse. Adding a+# real one is a `register_provider` call plus a UDM translator.SUPPORTED_PROVIDERS: list[EventWarehouseProvider] = [ElasticsearchProvider(),SplunkProvider(),- ChronicleProvider(),]@@ -61,6 +70,20 @@ def available_providers() -> list[str]:return [p.name for p in SUPPORTED_PROVIDERS]+def candidate_connector_types() -> tuple[str, ...]:+ """Every connector type any registered provider can take credentials from.++ The scheduler asks the database once per hunt which of these the tenant+ has enabled, rather than issuing one query per provider.+ """+ seen: list[str] = []+ for provider in SUPPORTED_PROVIDERS:+ for connector_type in getattr(provider, "connector_types", ()):+ if connector_type not in seen:+ seen.append(connector_type)+ return tuple(seen)++def _select_provider_name(hunt: SavedHunt) -> str | None:"""Read the per-hunt provider override, if any.@@ -72,12 +95,26 @@ def _select_provider_name(hunt: SavedHunt) -> str | None:return getattr(hunt, "warehouse_provider", None)-def resolve_provider(hunt: SavedHunt) -> EventWarehouseProvider:+def _has_translation(provider: EventWarehouseProvider, hunt: SavedHunt) -> bool:+ tq = hunt.translated_query if isinstance(hunt.translated_query, dict) else {}+ return bool(tq.get(provider.translated_query_key))+++def resolve_provider(+ hunt: SavedHunt,+ *,+ connected_types: set[str],+) -> EventWarehouseProvider:"""Return the provider that should run ``hunt``.- Raises :class:`UnsupportedTranslation` when nothing in the- registry can answer the hunt — the scheduler treats this as a- soft skip.+ ``connected_types`` is the set of connector types the hunt's tenant has+ enabled, from :func:`.credentials.connected_warehouse_types`. Passing an+ empty set is meaningful — it is how "this tenant has connected no SIEM"+ reaches the caller as a message rather than as a silent zero.++ Raises :class:`UnsupportedTranslation` when nothing in the registry can+ answer the hunt. The scheduler treats this as a soft skip, so the+ message has to carry the reason."""override = _select_provider_name(hunt)if override:@@ -88,11 +125,19 @@ def resolve_provider(hunt: SavedHunt) -> EventWarehouseProvider:f"resolve_provider: hunt {hunt.id} pins warehouse_provider={override!r} but no such provider is registered")- tq = hunt.translated_query if isinstance(hunt.translated_query, dict) else {}- for provider in SUPPORTED_PROVIDERS:- if provider.translated_query_key in tq and tq[provider.translated_query_key]:+ translatable = [p for p in SUPPORTED_PROVIDERS if _has_translation(p, hunt)]+ if not translatable:+ tq = hunt.translated_query if isinstance(hunt.translated_query, dict) else {}+ raise UnsupportedTranslation(+ f"resolve_provider: hunt {hunt.id} has no translated query for any registered provider " f"(have keys: {sorted(tq.keys())})"+ )++ for provider in translatable:+ if connected_types.intersection(provider.connector_types):return provider+ wanted = sorted({t for p in translatable for t in p.connector_types})raise UnsupportedTranslation(- f"resolve_provider: hunt {hunt.id} has no translated query for any registered provider (have keys: {sorted(tq.keys())})"+ f"resolve_provider: hunt {hunt.id} translates for {sorted(p.name for p in translatable)} "+ f"but this tenant has no enabled connector of type {wanted} — connect one from the console")diff --git a/services/api/app/services/event_warehouse/splunk.py b/services/api/app/services/event_warehouse/splunk.pyindex b4cefced3..ee1842bc4 100644--- a/services/api/app/services/event_warehouse/splunk.py+++ b/services/api/app/services/event_warehouse/splunk.py@@ -1,50 +1,81 @@-"""Splunk event-warehouse provider — Phase 4.5 scaffold.+"""Splunk event-warehouse provider.-Reads SPL out of ``hunt.translated_query["spl"]`` and would run it-against the configured Splunk search head. The driver itself is the-``NotImplemented`` path today: it advertises the contract and the-credential keys so an operator wiring Splunk credentials sees a clear-"driver not yet shipped" error instead of a silent skip.+Runs the SPL the platform's translator already produced for a saved hunt+against the tenant's own Splunk search head, using the credentials stored+on their ``splunk`` connector row.-Adding the live implementation is a one-PR change once we land a-splunk-sdk dep:--1. Resolve ``SPLUNK_URL`` + ``SPLUNK_HMAC_TOKEN`` (or the Splunk SDK- session form) via settings.-2. POST the SPL to ``/services/search/jobs`` with ``exec_mode=oneshot``.-3. Count rows in the result set, return the hit count.-4. Add the SSRF guard mirroring :func:`_validate_es_url`.--Until then this provider raises :class:`HuntNotConfigured` so the-scheduler walks to the next provider in the chain.+This driver previously raised :class:`HuntNotConfigured` unconditionally —+it checked ``settings.SPLUNK_URL`` and ``settings.SPLUNK_HMAC_TOKEN``,+neither of which is a declared field on ``Settings``, and then raised+"scaffolded but live SPL execution not yet shipped" even if they had been.+The SPL translation was produced for every hunt and then discarded."""from __future__ import annotationsimport logging-from app.core.config import settings+from app.core.airgap import AirgapViolationfrom app.models.saved_hunt import SavedHunt+from app.services.spl_runner import SPLExecutionError, run_spl_query-from .base import HuntNotConfigured, _BaseProvider+from .base import HuntExecutionError, HuntNotConfigured, WarehouseCredentials, _BaseProviderlogger = logging.getLogger(__name__)class SplunkProvider(_BaseProvider):- """Run SPL hunts against the configured Splunk search head."""+ """Run SPL hunts against the tenant's own Splunk search head."""name = "splunk"translated_query_key = "spl"+ connector_types = ("splunk",)++ async def run_hunt(+ self,+ hunt: SavedHunt,+ *,+ credentials: WarehouseCredentials,+ max_rows: int = 500,+ ) -> int:+ spl = self._read_translated(hunt)++ base_url = credentials.get("base_url", "url", "endpoint")+ if not base_url:+ raise HuntNotConfigured(+ f"connector {credentials.connector_name!r} has no Splunk URL — "+ "re-save it in the console with the management endpoint (port 8089)"+ )++ token = credentials.get("token", "hec_token", "api_token")+ username = credentials.get("username")+ password = credentials.get("password")+ if not token and not (username and password):+ raise HuntNotConfigured(+ f"connector {credentials.connector_name!r} has neither a token nor a "+ "username/password pair — re-save it in the console with credentials"+ )++ # The connector schema defaults this to True and only a private+ # deployment with a self-signed certificate should turn it off, so a+ # missing key must read as "verify", never as "skip verification".+ verify_ssl = credentials.get("ssl_verify", default=True)++ try:+ result = await run_spl_query(+ spl=spl,+ base_url=base_url,+ token=token,+ username=username,+ password=password,+ max_rows=max_rows,+ verify_ssl=bool(verify_ssl),+ )+ except (AirgapViolation, ValueError):+ # Re-raise unchanged — the scheduler distinguishes air-gap and+ # SSRF/validation refusals from warehouse errors.+ raise+ except SPLExecutionError as exc:+ raise HuntExecutionError(str(exc)) from exc- async def run_hunt(self, hunt: SavedHunt, *, max_rows: int = 500) -> int:- _ = self._read_translated(hunt)- _ = max_rows- if not getattr(settings, "SPLUNK_URL", None) or not getattr(settings, "SPLUNK_HMAC_TOKEN", None):- raise HuntNotConfigured("splunk: SPLUNK_URL or SPLUNK_HMAC_TOKEN not configured")- # Live wire pending — see module docstring.- logger.info(- "event_warehouse.splunk.run_hunt_not_yet_live hunt_id=%s",- hunt.id,- )- raise HuntNotConfigured("splunk: provider scaffolded but live SPL execution not yet shipped")+ return len(result.rows)diff --git a/services/api/app/services/spl_runner.py b/services/api/app/services/spl_runner.pynew file mode 100644index 000000000..e2d6774ba--- /dev/null+++ b/services/api/app/services/spl_runner.py@@ -0,0 +1,206 @@+"""Splunk SPL executor for the event-warehouse tier.++Sibling of :mod:`app.services.esql_runner`, and deliberately the same+shape: validate the target against an allow-list, enforce the air-gap+policy, cap the row count, then make exactly one outbound call and wrap+every failure in one exception type.++Why the API service runs this rather than `services/connectors`+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++The credential vault lives in the API service, and `esql_runner` already+established that the warehouse tier executes here. Introducing a second+topology for the Splunk driver in the same change would make the diff+harder to review than the defect it fixes. The connectors microservice+remains the home of *polling* and of federated `UnifiedQuery` fan-out; this+module runs an already-translated dialect string for a scheduled hunt.++Splunk specifics worth stating once+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++* The management port is 8089, not the 8000 web UI. The connector schema+ says so in its help text; users still paste the web URL, so a connection+ failure names the port.+* ``POST /services/search/jobs`` requires the search string to begin with+ ``search`` or with a generating ``|`` command. The platform's translator+ emits ``index=* earliest=-24h ... | head 500``, which begins with neither,+ so the leading ``search`` is added here. Without it Splunk answers 400 on+ every hunt.+* ``exec_mode=oneshot`` returns results on the same request. A scheduled+ hunt only needs a hit count, so there is no reason to create a job, poll+ it, and page through results the way the polling connector does.+"""++from __future__ import annotations++import time+from dataclasses import dataclass+from typing import Any+from urllib.parse import urlparse++import httpx++from app.core.airgap import enforce_airgap_for_url++__all__ = [+ "SPLExecutionError",+ "SPLResult",+ "run_spl_query",+]++# Commands that may legally open a Splunk search string. Anything else is a+# bare search expression and needs the implicit ``search`` made explicit.+_GENERATING_PREFIXES = ("search ", "|")+++@dataclass(slots=True)+class SPLResult:+ """Rows returned by a single oneshot SPL search."""++ rows: list[dict[str, Any]]+ took_ms: int+++class SPLExecutionError(RuntimeError):+ """Splunk returned a non-2xx response, or the transport failed.++ Mirrors :class:`app.services.esql_runner.ESQLExecutionError` so the+ warehouse providers only need one ``except`` per backend.+ """+++def _validate_splunk_url(url: str, *, allowed_url: str) -> str:+ """Confirm ``url`` matches ``allowed_url``'s scheme and authority.++ Returns a URL rebuilt from only the validated scheme and netloc, so no+ caller-supplied path or query survives into the outbound request. This+ is the same construction ``esql_runner`` uses, and for the same two+ reasons: an attacker cannot redirect the call to a different path on the+ host, and CodeQL's taint tracker sees the value reconstructed from+ validated parts.++ ``allowed_url`` is required rather than optional. The tenant's connector+ row is the only legitimate source of a Splunk endpoint here, so there is+ no deployment-wide fallback to fall back to.+ """+ allowed = urlparse(allowed_url)+ candidate = urlparse(url)+ if candidate.scheme not in ("http", "https"):+ raise ValueError(f"Unsupported URL scheme: {candidate.scheme!r}")+ if not allowed.netloc:+ raise ValueError("No allowed Splunk host configured for this tenant")+ if candidate.netloc != allowed.netloc:+ raise ValueError(f"Splunk URL host {candidate.netloc!r} is not the configured host {allowed.netloc!r}")+ return f"{candidate.scheme}://{candidate.netloc}"+++def _as_search_command(spl: str) -> str:+ """Prefix a bare search expression with ``search``.++ Left alone when the string already starts with ``search`` or a+ generating ``|`` command, so a hand-written or translator-emitted+ pipeline is never double-prefixed.+ """+ stripped = spl.strip()+ lowered = stripped.lower()+ if any(lowered.startswith(prefix) for prefix in _GENERATING_PREFIXES):+ return stripped+ return f"search {stripped}"+++def _cap_rows(spl: str, max_rows: int) -> str:+ """Append ``| head N`` unless the pipeline already caps its own rows.++ The check is on pipeline segments rather than a substring scan: a search+ for the literal word "head" in a message field must not be mistaken for+ a row cap. Splitting on ``|`` is sufficient here because the value has+ already been produced by the platform's own translator — users submit a+ natural-language question, never raw SPL.+ """+ segments = [seg.strip().lower() for seg in spl.split("|")]+ if any(seg.startswith("head ") or seg == "head" for seg in segments[1:]):+ return spl+ return f"{spl} | head {max_rows}"+++def _auth_headers(*, token: str | None, username: str | None, password: str | None) -> dict[str, str]:+ """Bearer token when present, HTTP basic otherwise.++ Splunk accepts both. The connector schema offers a token field, but+ self-hosted deployments frequently use a service account, and the+ polling connector already supports either.+ """+ if token:+ return {"Authorization": f"Bearer {token}"}+ if username and password:+ return {} # httpx builds the basic header from the ``auth`` kwarg.+ raise ValueError("Splunk requires either a token or a username/password pair")+++async def run_spl_query(+ *,+ spl: str,+ base_url: str,+ token: str | None = None,+ username: str | None = None,+ password: str | None = None,+ max_rows: int = 500,+ timeout: float = 30.0,+ verify_ssl: bool = True,+) -> SPLResult:+ """Run one oneshot SPL search and return its rows.++ ``verify_ssl`` defaults to ``True`` and is only ever ``False`` when an+ operator explicitly unticks "Verify SSL certificate" on the connector,+ which self-hosted search heads behind an internal CA require. This is the+ same accepted risk the vendor appliance clients carry (see+ ``apps/docs/docs/operations/security.md#static-analysis-codeql``); pinning+ a CA bundle is the better long-term answer than a boolean.++ Raises+ ------+ ValueError+ URL validation failed, or no usable credentials were supplied.+ AirgapViolation+ Air-gap policy refuses the URL.+ SPLExecutionError+ Splunk returned a non-2xx response or the transport failed.+ """+ safe_url = _validate_splunk_url(base_url, allowed_url=base_url)+ search_url = f"{safe_url}/services/search/jobs"+ # No-op unless AISOC_AIRGAPPED is set, so it is safe unconditionally.+ enforce_airgap_for_url(search_url)++ query = _cap_rows(_as_search_command(spl), max_rows)+ headers = _auth_headers(token=token, username=username, password=password)+ auth = None if token else (username or "", password or "")++ t0 = time.monotonic()+ try:+ async with httpx.AsyncClient(timeout=timeout, verify=verify_ssl) as client:+ resp = await client.post(+ search_url,+ headers=headers,+ auth=auth,+ data={+ "search": query,+ "output_mode": "json",+ "exec_mode": "oneshot",+ "count": max_rows,+ },+ )+ resp.raise_for_status()+ data = resp.json()+ except httpx.HTTPStatusError as exc:+ # Splunk puts a useful diagnostic in the body ("Unknown search+ # command", "index not found"); the status alone sends an operator+ # looking at the wrong thing.+ raise SPLExecutionError(f"SPL execution failed ({exc.response.status_code}): {exc.response.text[:300]}") from exc+ except httpx.HTTPError as exc:+ raise SPLExecutionError(f"SPL execution failed: {exc}") from exc+ except ValueError as exc:+ raise SPLExecutionError(f"Splunk returned a non-JSON body: {exc}") from exc++ took_ms = int((time.monotonic() - t0) * 1000)+ rows = data.get("results", []) if isinstance(data, dict) else []+ return SPLResult(rows=[r for r in rows if isinstance(r, dict)], took_ms=took_ms)diff --git a/services/api/app/workers/hunt_scheduler.py b/services/api/app/workers/hunt_scheduler.pyindex 91f8650ce..214a07bbb 100644--- a/services/api/app/workers/hunt_scheduler.py+++ b/services/api/app/workers/hunt_scheduler.py@@ -74,7 +74,10 @@ from app.services.event_warehouse import (HuntExecutionError,HuntNotConfigured,UnsupportedTranslation,+ candidate_connector_types,+ connected_warehouse_types,resolve_provider,+ resolve_tenant_warehouse,)try:@@ -301,22 +304,42 @@ async def _execute_hunt(db: AsyncSession, hunt: SavedHunt) -> int:backend — adding Splunk / Chronicle as live drivers later changesnothing here.+ Credentials come from the hunt tenant's own connector rows, decrypted+ through the credential vault. They used to come from process settings+ (``ES_URL`` / ``SPLUNK_URL`` and friends) that were never declared as+ fields, so every provider raised :class:`HuntNotConfigured` and every+ scheduled hunt returned zero hits on every deployment.+Returns ``0`` (and logs at INFO) when:* The hunt has no translated query for any registered provider —typically a draft saved before the translator ran. The workerdoesn't re-translate, only re-runs.- * The chosen provider raises :class:`HuntNotConfigured` (missing- credentials, scaffolded driver). The worker stays quiet in- self-hosted dev where warehouses aren't wired up.+ * The tenant has not connected a SIEM any registered provider can+ query.+ * The chosen provider raises :class:`HuntNotConfigured` (the connector+ row exists but is missing a URL or credentials, or its stored secret+ cannot be decrypted).Raises warehouse transport / air-gap errors back to the caller,where :func:`run_once` records them via ``logger.exception`` andskips the ``last_run_at`` bump so the hunt retries next tick."""- _ = db # unused — kept in the signature for future hunt-specific readstry:- provider = resolve_provider(hunt)+ connected = await connected_warehouse_types(+ db,+ hunt.tenant_id,+ candidate_types=candidate_connector_types(),+ )+ except Exception:+ # A failed connector lookup is not a hunt result. Let the caller's+ # handler record it and retry rather than reporting zero hits, which+ # would read as "your hunt found nothing".+ logger.exception("hunt_scheduler.connector_lookup_failed hunt_id=%s", hunt.id)+ raise++ try:+ provider = resolve_provider(hunt, connected_types=connected)except UnsupportedTranslation as exc:logger.info("hunt_scheduler.execute_skip hunt_id=%s reason=no_provider err=%s",@@ -327,7 +350,12 @@ async def _execute_hunt(db: AsyncSession, hunt: SavedHunt) -> int:max_rows = int(getattr(settings, "HUNT_SCHEDULER_MAX_ROWS", 500))try:- return await provider.run_hunt(hunt, max_rows=max_rows)+ credentials = await resolve_tenant_warehouse(+ db,+ hunt.tenant_id,+ connector_types=provider.connector_types,+ )+ return await provider.run_hunt(hunt, credentials=credentials, max_rows=max_rows)except HuntNotConfigured as exc:logger.info("hunt_scheduler.execute_skip hunt_id=%s provider=%s reason=not_configured err=%s",diff --git a/services/api/tests/test_event_warehouse_credentials.py b/services/api/tests/test_event_warehouse_credentials.pynew file mode 100644index 000000000..c69e6901b--- /dev/null+++ b/services/api/tests/test_event_warehouse_credentials.py@@ -0,0 +1,239 @@+"""Warehouse credentials come from the tenant's connectors, not from settings.++What these tests are defending+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Before this module existed, every event-warehouse driver resolved its+endpoint and secret from process settings — ``ES_URL`` / ``ES_API_KEY`` for+Elasticsearch, ``SPLUNK_URL`` / ``SPLUNK_HMAC_TOKEN`` for Splunk. None of+those were declared fields on ``Settings``; they were read through+``getattr(settings, "ES_URL", None)``, so the lookup returned ``None`` on+every deployment and every scheduled hunt returned zero hits. Because+``Settings`` sets ``extra="ignore"``, an operator who followed the error+message and exported ``ES_URL`` got the same message back.++``test_settings_declare_the_documented_fallback_fields`` pins the first half+of the fix; the rest of the file pins the part that matters more — that the+credentials a driver runs with belong to the tenant whose hunt is running,+and are read from the row the console wizard wrote.+"""++from __future__ import annotations++import uuid+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from app.core.config import Settings, settings+from app.models.connector import Connector+from app.security.credential_vault import CredentialVaultError+from app.services.event_warehouse import (+ HuntNotConfigured,+ WarehouseCredentials,+ connected_warehouse_types,+ resolve_tenant_warehouse,+)++VAULT_PATH = "app.services.event_warehouse.credentials.get_vault"+++def _make_connector(+ *,+ tenant_id: uuid.UUID,+ connector_type: str = "elastic",+ name: str = "Prod cluster",+ auth_config: dict[str, Any] | None = None,+ connector_config: dict[str, Any] | None = None,+) -> Connector:+ return Connector(+ id=uuid.uuid4(),+ tenant_id=tenant_id,+ name=name,+ connector_type=connector_type,+ category="siem",+ is_enabled=True,+ auth_config=auth_config or {"api_key": "vault:v1:abc"},+ connector_config=connector_config or {},+ )+++def _db_returning(*connectors: Connector) -> Any:+ """An ``AsyncSession`` double whose ``execute`` yields ``connectors``.++ Records the statement it was handed so a test can assert on the compiled+ SQL rather than trusting that the filter was applied.+ """+ scalars = MagicMock()+ scalars.first = MagicMock(return_value=connectors[0] if connectors else None)+ scalars.all = MagicMock(return_value=list(connectors))++ result = MagicMock()+ result.scalars = MagicMock(return_value=scalars)++ db = MagicMock()+ db.execute = AsyncMock(return_value=result)+ return db+++def _vault_returning(payload: dict[str, Any] | Exception) -> Any:+ vault = MagicMock()+ if isinstance(payload, Exception):+ vault.decrypt_dict = MagicMock(side_effect=payload)+ else:+ vault.decrypt_dict = MagicMock(return_value=payload)+ return vault+++class TestSettingsFallback:+ def test_settings_declare_the_documented_fallback_fields(self) -> None:+ """``esql_runner`` has always told operators to "set them in environment+ variables". Until these fields existed, doing so had no effect:+ ``Settings`` ignores undeclared variables."""+ assert hasattr(settings, "ES_URL")+ assert hasattr(settings, "ES_API_KEY")++ def test_exported_env_var_now_reaches_settings(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("ES_URL", "https://es.example.com:9200")+ monkeypatch.setenv("ES_API_KEY", "secret-key")+ fresh = Settings()+ assert fresh.ES_URL == "https://es.example.com:9200"+ assert fresh.ES_API_KEY == "secret-key"++ def test_fallback_defaults_to_unset(self) -> None:+ """Unset must be ``None``, not a localhost guess — a hunt silently+ pointed at 127.0.0.1 is worse than one that says it is unconfigured."""+ assert Settings().ES_URL is None+++class TestResolveTenantWarehouse:+ async def test_returns_decrypted_credentials_for_the_tenant(self) -> None:+ tenant_id = uuid.uuid4()+ connector = _make_connector(tenant_id=tenant_id, connector_config={"index": "logs-*"})+ db = _db_returning(connector)++ with patch(VAULT_PATH, return_value=_vault_returning({"api_key": "plaintext", "base_url": "https://es:9200"})):+ creds = await resolve_tenant_warehouse(db, tenant_id, connector_types=("elastic",))++ assert isinstance(creds, WarehouseCredentials)+ assert creds.connector_type == "elastic"+ assert creds.connector_name == "Prod cluster"+ assert creds.get("api_key") == "plaintext"+ assert creds.get("base_url") == "https://es:9200"+ # Non-secret connector_config is merged into the lookup surface.+ assert creds.get("index") == "logs-*"++ async def test_query_is_scoped_to_tenant_enabled_and_type(self) -> None:+ """The three filters are the isolation boundary. Asserting on the+ compiled SQL catches a regression that a mocked return value cannot."""+ tenant_id = uuid.uuid4()+ db = _db_returning(_make_connector(tenant_id=tenant_id))++ with patch(VAULT_PATH, return_value=_vault_returning({"api_key": "k"})):+ await resolve_tenant_warehouse(db, tenant_id, connector_types=("elastic",))++ stmt = db.execute.await_args.args[0]+ compiled = str(stmt.compile(compile_kwargs={"literal_binds": False}))+ assert "connectors.tenant_id = " in compiled+ assert "connectors.is_enabled IS true" in compiled+ assert "connectors.connector_type IN " in compiled++ async def test_pinned_connector_id_is_still_tenant_filtered(self) -> None:+ """Naming a connector must not bypass the tenant filter — otherwise an+ id from another tenant would resolve to their credentials."""+ tenant_id = uuid.uuid4()+ pinned = uuid.uuid4()+ db = _db_returning(_make_connector(tenant_id=tenant_id))++ with patch(VAULT_PATH, return_value=_vault_returning({"api_key": "k"})):+ await resolve_tenant_warehouse(db, tenant_id, connector_types=("elastic",), connector_id=pinned)++ compiled = str(db.execute.await_args.args[0])+ assert "connectors.tenant_id = " in compiled+ assert "connectors.id = " in compiled++ async def test_raises_when_tenant_has_no_matching_connector(self) -> None:+ db = _db_returning()++ with pytest.raises(HuntNotConfigured) as excinfo:+ await resolve_tenant_warehouse(db, uuid.uuid4(), connector_types=("elastic",))++ # The message has to be actionable in the console, not in a shell.+ assert "console" in str(excinfo.value)+ assert "no enabled connector" in str(excinfo.value)++ async def test_undecryptable_secret_is_distinguishable_from_no_connector(self) -> None:+ """An operator must be able to tell "nobody connected a SIEM" from+ "the vault key rotated and the stored secret is unreadable"."""+ tenant_id = uuid.uuid4()+ db = _db_returning(_make_connector(tenant_id=tenant_id))++ with patch(VAULT_PATH, return_value=_vault_returning(CredentialVaultError("bad key"))):+ with pytest.raises(HuntNotConfigured) as excinfo:+ await resolve_tenant_warehouse(db, tenant_id, connector_types=("elastic",))++ assert "could not be decrypted" in str(excinfo.value)++ async def test_decryption_failure_does_not_leak_ciphertext(self) -> None:+ tenant_id = uuid.uuid4()+ connector = _make_connector(tenant_id=tenant_id, auth_config={"api_key": "vault:v1:SUPERSECRETBLOB"})+ db = _db_returning(connector)++ with patch(VAULT_PATH, return_value=_vault_returning(CredentialVaultError("bad key"))):+ with pytest.raises(HuntNotConfigured) as excinfo:+ await resolve_tenant_warehouse(db, tenant_id, connector_types=("elastic",))++ assert "SUPERSECRETBLOB" not in str(excinfo.value)+++class TestConnectedWarehouseTypes:+ async def test_returns_only_types_the_tenant_enabled(self) -> None:+ tenant_id = uuid.uuid4()+ db = _db_returning(+ _make_connector(tenant_id=tenant_id, connector_type="splunk"),+ _make_connector(tenant_id=tenant_id, connector_type="splunk", name="DR"),+ )++ found = await connected_warehouse_types(db, tenant_id, candidate_types=("elastic", "splunk"))++ assert found == {"splunk"}++ async def test_empty_candidate_list_does_not_query(self) -> None:+ db = _db_returning()++ found = await connected_warehouse_types(db, uuid.uuid4(), candidate_types=())++ assert found == set()+ db.execute.assert_not_awaited()+++class TestWarehouseCredentialsLookup:+ def _creds(self, **kwargs: Any) -> WarehouseCredentials:+ return WarehouseCredentials(+ connector_id=uuid.uuid4(),+ connector_type="elastic",+ connector_name="c",+ **kwargs,+ )++ def test_auth_wins_over_config(self) -> None:+ creds = self._creds(auth={"base_url": "from-auth"}, config={"base_url": "from-config"})+ assert creds.get("base_url") == "from-auth"++ def test_falls_back_to_config(self) -> None:+ creds = self._creds(auth={}, config={"base_url": "from-config"})+ assert creds.get("base_url") == "from-config"++ def test_tries_alias_names_in_order(self) -> None:+ creds = self._creds(auth={"url": "second-choice"}, config={})+ assert creds.get("base_url", "url") == "second-choice"++ def test_empty_string_is_treated_as_absent(self) -> None:+ """A connector saved with a blank field must not defeat the fallback."""+ creds = self._creds(auth={"base_url": ""}, config={"base_url": "real"})+ assert creds.get("base_url") == "real"++ def test_false_is_preserved(self) -> None:+ """``ssl_verify: False`` is a real value and must not be skipped as empty."""+ creds = self._creds(auth={}, config={"ssl_verify": False})+ assert creds.get("ssl_verify", default=True) is Falsediff --git a/services/api/tests/test_event_warehouse_providers.py b/services/api/tests/test_event_warehouse_providers.pynew file mode 100644index 000000000..aabab4225--- /dev/null+++ b/services/api/tests/test_event_warehouse_providers.py@@ -0,0 +1,236 @@+"""The warehouse drivers run against the tenant's connector, and Splunk runs.++Regression notes+~~~~~~~~~~~~~~~~++``TestSplunkProvider`` is new behaviour in the strict sense: the previous+``SplunkProvider.run_hunt`` raised :class:`HuntNotConfigured`+unconditionally. Its first branch checked ``settings.SPLUNK_URL`` and+``settings.SPLUNK_HMAC_TOKEN`` — neither is a declared field on+``Settings`` — and the line after it raised "provider scaffolded but live+SPL execution not yet shipped" regardless. Every one of these tests fails+against that implementation, including the ones that only assert an error+message, because the old message was the scaffold text.++``TestElasticsearchProvider`` covers the same shift for ES|QL: the driver+called ``resolve_es_credentials()``, which read the same kind of undeclared+setting, so it could not reach a cluster and could not be pointed at a+per-tenant one.+"""++from __future__ import annotations++import base64+import uuid+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from app.core.airgap import AirgapViolation+from app.services.esql_runner import ESQLExecutionError, ESQLResult+from app.services.event_warehouse import HuntExecutionError, HuntNotConfigured, WarehouseCredentials+from app.services.event_warehouse.elasticsearch import ElasticsearchProvider, elastic_auth_header+from app.services.event_warehouse.splunk import SplunkProvider+from app.services.spl_runner import SPLExecutionError, SPLResult++ES_RUN = "app.services.event_warehouse.elasticsearch.run_esql_query"+SPL_RUN = "app.services.event_warehouse.splunk.run_spl_query"+++def _hunt(**translated: str) -> Any:+ hunt = MagicMock()+ hunt.id = uuid.uuid4()+ hunt.tenant_id = uuid.uuid4()+ hunt.translated_query = dict(translated)+ return hunt+++def _creds(connector_type: str, auth: dict[str, Any], config: dict[str, Any] | None = None) -> WarehouseCredentials:+ return WarehouseCredentials(+ connector_id=uuid.uuid4(),+ connector_type=connector_type,+ connector_name="Prod",+ auth=auth,+ config=config or {},+ )+++class TestElasticAuthHeader:+ def test_api_key_wins(self) -> None:+ creds = _creds("elastic", {"api_key": "k", "username": "u", "password": "p"})+ assert elastic_auth_header(creds) == "ApiKey k"++ def test_basic_auth_fallback(self) -> None:+ """Self-managed clusters commonly use a service account; the connector+ schema offers username/password as an alternative to an API key."""+ creds = _creds("elastic", {"username": "u", "password": "p"})+ expected = base64.b64encode(b"u:p").decode()+ assert elastic_auth_header(creds) == f"Basic {expected}"++ def test_neither_is_an_actionable_error(self) -> None:+ creds = _creds("elastic", {"base_url": "https://es:9200"})+ with pytest.raises(HuntNotConfigured, match="neither an API key nor a"):+ elastic_auth_header(creds)++ def test_error_does_not_echo_the_secret_fields(self) -> None:+ creds = _creds("elastic", {"password": "hunter2"})+ with pytest.raises(HuntNotConfigured) as excinfo:+ elastic_auth_header(creds)+ assert "hunter2" not in str(excinfo.value)+++class TestElasticsearchProvider:+ def setup_method(self) -> None:+ self.provider = ElasticsearchProvider()++ async def test_runs_against_the_connectors_url(self) -> None:+ hunt = _hunt(esql="FROM logs-* | LIMIT 5")+ creds = _creds("elastic", {"base_url": "https://tenant-a.es.example.com:9200", "api_key": "k"})++ with patch(ES_RUN, new=AsyncMock(return_value=ESQLResult(columns=["h"], rows=[["a"], ["b"]], took_ms=4))) as run:+ hits = await self.provider.run_hunt(hunt, credentials=creds, max_rows=25)++ assert hits == 2+ kwargs = run.await_args.kwargs+ assert kwargs["es_url"] == "https://tenant-a.es.example.com:9200"+ assert kwargs["auth_header"] == "ApiKey k"+ assert kwargs["max_rows"] == 25++ async def test_ssrf_allow_list_is_the_connectors_own_url(self) -> None:+ """Per-tenant allow-list: this tenant's hunt can reach the cluster they+ registered and nothing else. The allow-list used to be a global+ setting, so it could not describe more than one cluster."""+ hunt = _hunt(esql="FROM logs-*")+ creds = _creds("elastic", {"base_url": "https://tenant-a.es.example.com:9200", "api_key": "k"})++ with patch(ES_RUN, new=AsyncMock(return_value=ESQLResult([], [], 1))) as run:+ await self.provider.run_hunt(hunt, credentials=creds)++ assert run.await_args.kwargs["allowed_url"] == "https://tenant-a.es.example.com:9200"++ async def test_missing_url_is_an_actionable_skip(self) -> None:+ hunt = _hunt(esql="FROM logs-*")+ creds = _creds("elastic", {"api_key": "k"})++ with pytest.raises(HuntNotConfigured, match="no cluster URL"):+ await self.provider.run_hunt(hunt, credentials=creds)++ async def test_untranslated_hunt_is_unsupported_not_an_error(self) -> None:+ from app.services.event_warehouse import UnsupportedTranslation++ hunt = _hunt(spl="index=main")+ creds = _creds("elastic", {"base_url": "https://es:9200", "api_key": "k"})++ with pytest.raises(UnsupportedTranslation):+ await self.provider.run_hunt(hunt, credentials=creds)++ async def test_execution_error_becomes_hunt_execution_error(self) -> None:+ hunt = _hunt(esql="FROM logs-*")+ creds = _creds("elastic", {"base_url": "https://es:9200", "api_key": "k"})++ with patch(ES_RUN, new=AsyncMock(side_effect=ESQLExecutionError("ES 500"))):+ with pytest.raises(HuntExecutionError, match="ES 500"):+ await self.provider.run_hunt(hunt, credentials=creds)++ async def test_airgap_violation_is_re_raised_unchanged(self) -> None:+ hunt = _hunt(esql="FROM logs-*")+ creds = _creds("elastic", {"base_url": "https://es:9200", "api_key": "k"})++ with patch(ES_RUN, new=AsyncMock(side_effect=AirgapViolation("blocked"))):+ with pytest.raises(AirgapViolation):+ await self.provider.run_hunt(hunt, credentials=creds)+++class TestSplunkProvider:+ """Every test here fails against the previous driver, which raised+ :class:`HuntNotConfigured` on every call."""++ def setup_method(self) -> None:+ self.provider = SplunkProvider()++ def test_declares_the_splunk_connector_type(self) -> None:+ assert self.provider.connector_types == ("splunk",)+ assert self.provider.translated_query_key == "spl"++ async def test_runs_the_translated_spl_and_counts_rows(self) -> None:+ hunt = _hunt(spl="index=* earliest=-24h | head 500")+ creds = _creds("splunk", {"base_url": "https://splunk.example.com:8089", "token": "t"})++ with patch(SPL_RUN, new=AsyncMock(return_value=SPLResult(rows=[{"a": 1}, {"a": 2}, {"a": 3}], took_ms=9))) as run:+ hits = await self.provider.run_hunt(hunt, credentials=creds, max_rows=100)++ assert hits == 3+ kwargs = run.await_args.kwargs+ assert kwargs["spl"] == "index=* earliest=-24h | head 500"+ assert kwargs["base_url"] == "https://splunk.example.com:8089"+ assert kwargs["token"] == "t"+ assert kwargs["max_rows"] == 100++ async def test_accepts_basic_auth_credentials(self) -> None:+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089", "username": "svc", "password": "pw"})++ with patch(SPL_RUN, new=AsyncMock(return_value=SPLResult(rows=[], took_ms=1))) as run:+ await self.provider.run_hunt(hunt, credentials=creds)++ assert run.await_args.kwargs["username"] == "svc"+ assert run.await_args.kwargs["password"] == "pw"++ async def test_ssl_verify_defaults_to_on_when_the_key_is_absent(self) -> None:+ """A missing key must read as "verify". Defaulting the other way would+ silently disable certificate checking for every connector saved before+ the field existed."""+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089", "token": "t"})++ with patch(SPL_RUN, new=AsyncMock(return_value=SPLResult(rows=[], took_ms=1))) as run:+ await self.provider.run_hunt(hunt, credentials=creds)++ assert run.await_args.kwargs["verify_ssl"] is True++ async def test_ssl_verify_false_is_honoured(self) -> None:+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089", "token": "t"}, {"ssl_verify": False})++ with patch(SPL_RUN, new=AsyncMock(return_value=SPLResult(rows=[], took_ms=1))) as run:+ await self.provider.run_hunt(hunt, credentials=creds)++ assert run.await_args.kwargs["verify_ssl"] is False++ async def test_zero_rows_is_a_result_not_a_skip(self) -> None:+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089", "token": "t"})++ with patch(SPL_RUN, new=AsyncMock(return_value=SPLResult(rows=[], took_ms=1))):+ assert await self.provider.run_hunt(hunt, credentials=creds) == 0++ async def test_missing_url_names_the_management_port(self) -> None:+ """Users paste the 8000 web URL; the message has to say 8089."""+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"token": "t"})++ with pytest.raises(HuntNotConfigured, match="8089"):+ await self.provider.run_hunt(hunt, credentials=creds)++ async def test_missing_credentials_is_an_actionable_skip(self) -> None:+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089"})++ with pytest.raises(HuntNotConfigured, match="neither a token nor a"):+ await self.provider.run_hunt(hunt, credentials=creds)++ async def test_execution_error_becomes_hunt_execution_error(self) -> None:+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089", "token": "t"})++ with patch(SPL_RUN, new=AsyncMock(side_effect=SPLExecutionError("Splunk 503"))):+ with pytest.raises(HuntExecutionError, match="Splunk 503"):+ await self.provider.run_hunt(hunt, credentials=creds)++ async def test_airgap_violation_is_re_raised_unchanged(self) -> None:+ hunt = _hunt(spl="index=main")+ creds = _creds("splunk", {"base_url": "https://splunk:8089", "token": "t"})++ with patch(SPL_RUN, new=AsyncMock(side_effect=AirgapViolation("blocked"))):+ with pytest.raises(AirgapViolation):+ await self.provider.run_hunt(hunt, credentials=creds)diff --git a/services/api/tests/test_event_warehouse_registry.py b/services/api/tests/test_event_warehouse_registry.pyindex f9a64b901..8fb1496de 100644--- a/services/api/tests/test_event_warehouse_registry.py+++ b/services/api/tests/test_event_warehouse_registry.py@@ -1,18 +1,29 @@-"""Tests for the event-warehouse provider registry — Phase 4.5.+"""Tests for the event-warehouse provider registry.The registry is the routing layer between the hunt scheduler and the-per-warehouse drivers. These tests pin the contract the scheduler-relies on:--* Elasticsearch is the default provider — any hunt carrying ``esql``- goes there.-* The chain is walked in priority order; an ES-only hunt is never- handed to Splunk just because Splunk happens to be registered.-* Hunts with no recognised translation raise- :class:`UnsupportedTranslation` so the scheduler skips them rather- than spamming a hard failure.+per-warehouse drivers. These tests pin the contract the scheduler relies+on:++* Selection is driven by what the tenant *connected*, then by what the+ hunt was translated into — not by registry order alone.+* The chain is walked in priority order only to break ties when a tenant+ has connected more than one warehouse.+* Hunts with no recognised translation, and tenants with no connected+ warehouse, both raise :class:`UnsupportedTranslation` so the scheduler+ skips them rather than spamming a hard failure — but with messages that+ say which of the two happened.* ``register_provider`` lets a downstream / test add a custom driverwithout forking the registry module.++Regression note+~~~~~~~~~~~~~~~++``test_splunk_only_tenant_is_not_routed_to_elasticsearch`` is the case the+previous implementation got wrong. ``resolve_provider`` used to return the+first provider whose ``translated_query_key`` appeared in the hunt, and the+natural-language translator emits ES|QL, SPL *and* KQL for every question.+``esql`` was therefore always present and Elasticsearch was always chosen,+including for tenants who run only Splunk."""from __future__ import annotations@@ -26,6 +37,7 @@ from app.services.event_warehouse import (EventWarehouseProvider,UnsupportedTranslation,available_providers,+ candidate_connector_types,register_provider,resolve_provider,)@@ -48,8 +60,9 @@ class FakeProvider:name = "fake-warehouse"translated_query_key = "fake_dsl"+ connector_types = ("fake_connector",)- async def run_hunt(self, hunt: Any, *, max_rows: int = 500) -> int:+ async def run_hunt(self, hunt: Any, *, credentials: Any, max_rows: int = 500) -> int:return 0@@ -57,59 +70,81 @@ class TestDefaults:"""Built-in providers are the ones the scheduler ships with today."""def test_elasticsearch_is_first(self) -> None:- # The priority order matters: we want ES picked when both ES- # and another translation are present.+ # Priority order only breaks ties between warehouses a tenant has+ # both connected.assert available_providers()[0] == "elasticsearch"- def test_available_providers_contains_scaffolded_drivers(self) -> None:- names = available_providers()- assert {"elasticsearch", "splunk", "chronicle"}.issubset(set(names))+ def test_registry_ships_two_live_drivers(self) -> None:+ assert set(available_providers()) == {"elasticsearch", "splunk"}++ def test_chronicle_scaffold_is_gone(self) -> None:+ """It read a ``udm`` translation nothing emits, gated on settings that+ were never fields, and reported itself as a supported warehouse."""+ assert "chronicle" not in available_providers()++ def test_candidate_connector_types_covers_every_driver(self) -> None:+ assert set(candidate_connector_types()) == {"elastic", "splunk"}class TestResolveProvider:- def test_picks_elasticsearch_when_esql_present(self) -> None:+ def test_picks_elasticsearch_when_tenant_has_elastic(self) -> None:hunt = _make_hunt(translated={"esql": "FROM logs"})- provider = resolve_provider(hunt)+ provider = resolve_provider(hunt, connected_types={"elastic"})assert provider.name == "elasticsearch"- def test_picks_first_match_when_multiple_translations(self) -> None:- """ES wins over SPL when both are present (priority order)."""+ def test_splunk_only_tenant_is_not_routed_to_elasticsearch(self) -> None:+ """The regression. The translator emits every dialect, so a Splunk-only+ tenant used to be handed to the Elasticsearch driver and skipped."""+ hunt = _make_hunt(translated={"esql": "FROM logs", "spl": "index=foo"})+ provider = resolve_provider(hunt, connected_types={"splunk"})+ assert provider.name == "splunk"++ def test_priority_breaks_ties_when_both_connected(self) -> None:hunt = _make_hunt(translated={"esql": "FROM logs", "spl": "index=foo"})- provider = resolve_provider(hunt)+ provider = resolve_provider(hunt, connected_types={"elastic", "splunk"})assert provider.name == "elasticsearch"def test_skips_to_next_when_first_provider_key_is_empty(self) -> None:"""Empty ES string but present SPL → Splunk picked."""hunt = _make_hunt(translated={"esql": "", "spl": "index=foo"})- provider = resolve_provider(hunt)+ provider = resolve_provider(hunt, connected_types={"elastic", "splunk"})assert provider.name == "splunk"+ def test_raises_when_tenant_has_connected_nothing(self) -> None:+ hunt = _make_hunt(translated={"esql": "FROM logs", "spl": "index=foo"})+ with pytest.raises(UnsupportedTranslation) as excinfo:+ resolve_provider(hunt, connected_types=set())+ # The message has to distinguish this from "never translated", because+ # the scheduler turns both into a soft skip.+ assert "no enabled connector" in str(excinfo.value)+def test_raises_when_no_translation_recognised(self) -> None:"""A hunt with only an unknown DSL key has no provider."""hunt = _make_hunt(translated={"unknown_dsl": "SELECT *"})- with pytest.raises(UnsupportedTranslation):- resolve_provider(hunt)+ with pytest.raises(UnsupportedTranslation) as excinfo:+ resolve_provider(hunt, connected_types={"elastic"})+ assert "no translated query" in str(excinfo.value)def test_raises_when_translated_query_is_not_a_dict(self) -> None:hunt = _make_hunt(translated="raw string") # type: ignore[arg-type]with pytest.raises(UnsupportedTranslation):- resolve_provider(hunt)+ resolve_provider(hunt, connected_types={"elastic"})def test_raises_when_translated_query_is_none(self) -> None:hunt = _make_hunt(translated=None)with pytest.raises(UnsupportedTranslation):- resolve_provider(hunt)+ resolve_provider(hunt, connected_types={"elastic"})def test_per_hunt_override_pins_named_provider(self) -> None:"""``hunt.warehouse_provider`` overrides priority order entirely."""hunt = _make_hunt(translated={"esql": "FROM logs"}, override="splunk")- provider = resolve_provider(hunt)+ provider = resolve_provider(hunt, connected_types={"elastic"})assert provider.name == "splunk"def test_unknown_override_raises_unsupported(self) -> None:hunt = _make_hunt(translated={"esql": "FROM logs"}, override="not-a-provider")with pytest.raises(UnsupportedTranslation):- resolve_provider(hunt)+ resolve_provider(hunt, connected_types={"elastic"})class TestRegisterProvider:@@ -129,9 +164,13 @@ class TestRegisterProvider:def test_registered_provider_is_picked_up_by_resolve(self) -> None:register_provider(FakeProvider())hunt = _make_hunt(translated={"fake_dsl": "RUN this"})- provider = resolve_provider(hunt)+ provider = resolve_provider(hunt, connected_types={"fake_connector"})assert provider.name == "fake-warehouse"+ def test_registered_provider_widens_candidate_types(self) -> None:+ register_provider(FakeProvider())+ assert "fake_connector" in candidate_connector_types()+def test_registered_providers_respect_protocol(self) -> None:fake = FakeProvider()assert isinstance(fake, EventWarehouseProvider)diff --git a/services/api/tests/test_hunt_scheduler_execute.py b/services/api/tests/test_hunt_scheduler_execute.pyindex 24b2c6be4..f433339e9 100644--- a/services/api/tests/test_hunt_scheduler_execute.py+++ b/services/api/tests/test_hunt_scheduler_execute.py@@ -1,18 +1,33 @@-"""Unit tests for ``app.workers.hunt_scheduler._execute_hunt`` — Track 3, T3.4.+"""Unit tests for ``app.workers.hunt_scheduler._execute_hunt``.-Phase 4.5 update: the worker now routes execution through the-:mod:`app.services.event_warehouse` provider registry instead of-calling :func:`run_esql_query` directly. These tests therefore exercise-the *new* composition surface — the scheduler picks a provider, the-provider raises/returns, the scheduler responds.+The worker routes execution through the :mod:`app.services.event_warehouse`+provider registry: it asks which warehouses the hunt's tenant has+connected, picks a provider, resolves that tenant's vault-encrypted+credentials, and hands both to the driver.-The four behavioural contracts we lock in are unchanged from before:+The behavioural contracts locked in here:#. Hunt has no provider-recognisable translation → quiet skip, ``0``.-#. Provider raises :class:`HuntNotConfigured` → quiet skip, ``0``.-#. Happy path → returns the provider's hit count.+#. Tenant has connected no warehouse → quiet skip, ``0``.+#. Credentials missing or undecryptable → quiet skip, ``0``.+#. Happy path → returns the provider's hit count, and the driver is+ handed the tenant's credentials.#. Transport / air-gap / value errors → propagated so ``run_once``skips the ``last_run_at`` bump and retries on the next sweep.+#. A failed *connector lookup* propagates rather than reporting zero,+ because "we could not read your connectors" is not "your hunt found+ nothing".++Regression note+~~~~~~~~~~~~~~~++``test_passes_tenant_credentials_to_provider`` and+``test_looks_up_connectors_for_the_hunts_tenant`` are the cases the previous+implementation could not satisfy. ``_execute_hunt`` ignored its ``db``+argument entirely (``_ = db # unused``) and the providers read+``settings.ES_URL`` / ``SPLUNK_URL``, which are not declared fields on+``Settings`` — so no tenant's stored credentials ever reached a driver and+every scheduled hunt returned zero hits."""from __future__ import annotations@@ -27,14 +42,16 @@ from app.services.event_warehouse import (HuntExecutionError,HuntNotConfigured,UnsupportedTranslation,+ WarehouseCredentials,)from app.workers import hunt_scheduler-def _make_hunt(translated: Any = None) -> Any:+def _make_hunt(translated: Any = None, tenant_id: uuid.UUID | None = None) -> Any:"""Return a stand-in for :class:`app.models.saved_hunt.SavedHunt`."""hunt = MagicMock()hunt.id = uuid.uuid4()+ hunt.tenant_id = tenant_id or uuid.uuid4()hunt.translated_query = translated# `getattr(hunt, 'warehouse_provider', None)` must return None so# the registry doesn't think this hunt has an override.@@ -44,31 +61,69 @@ def _make_hunt(translated: Any = None) -> Any:@pytest.fixturedef fake_db() -> Any:- """A throw-away DB session — ``_execute_hunt`` doesn't touch it today."""return MagicMock()+def _credentials(connector_type: str = "elastic") -> WarehouseCredentials:+ return WarehouseCredentials(+ connector_id=uuid.uuid4(),+ connector_type=connector_type,+ connector_name="prod cluster",+ auth={"base_url": "https://es.example.com:9200", "api_key": "k"},+ config={},+ )++def _stub_provider(name: str = "elasticsearch", *, run: AsyncMock | None = None) -> Any:"""Build a provider double the registry can return."""provider = MagicMock()provider.name = nameprovider.translated_query_key = "esql"+ provider.connector_types = ("elastic",)provider.run_hunt = run or AsyncMock(return_value=0)return provider+def _wire(+ monkeypatch: pytest.MonkeyPatch,+ *,+ provider: Any = None,+ connected: set[str] | None = None,+ credentials: Any = None,+ resolve_error: Exception | None = None,+ connected_error: Exception | None = None,+) -> dict[str, Any]:+ """Patch the three collaborators ``_execute_hunt`` calls.++ Returns the mocks so a test can assert on the arguments they received.+ """+ connected_mock = AsyncMock(+ return_value=connected if connected is not None else {"elastic"},+ side_effect=connected_error,+ )+ monkeypatch.setattr(hunt_scheduler, "connected_warehouse_types", connected_mock)++ if resolve_error is not None:+ resolve_mock = MagicMock(side_effect=resolve_error)+ else:+ resolve_mock = MagicMock(return_value=provider or _stub_provider())+ monkeypatch.setattr(hunt_scheduler, "resolve_provider", resolve_mock)++ creds_mock = AsyncMock(return_value=credentials if credentials is not None else _credentials())+ if isinstance(credentials, Exception):+ creds_mock = AsyncMock(side_effect=credentials)+ monkeypatch.setattr(hunt_scheduler, "resolve_tenant_warehouse", creds_mock)++ return {"connected": connected_mock, "resolve": resolve_mock, "credentials": creds_mock}++class TestExecuteHuntSkipPaths:"""Branches where the worker logs and returns ``0`` instead of raising."""async def test_skips_when_no_translated_query(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:hunt = _make_hunt(translated=None)- # If we reach a provider we've failed — pin a tripwire.provider = _stub_provider(run=AsyncMock(side_effect=AssertionError("provider should not be called")))- monkeypatch.setattr(- hunt_scheduler,- "resolve_provider",- MagicMock(side_effect=UnsupportedTranslation("no provider for hunt")),- )+ _wire(monkeypatch, provider=provider, resolve_error=UnsupportedTranslation("no provider for hunt"))hits = await hunt_scheduler._execute_hunt(fake_db, hunt)@@ -76,13 +131,10 @@ class TestExecuteHuntSkipPaths:provider.run_hunt.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"})- monkeypatch.setattr(- hunt_scheduler,- "resolve_provider",- MagicMock(side_effect=UnsupportedTranslation("no live driver for kql/spl")),- )+ """``translated_query`` may exist but carry only a dialect no connected+ warehouse speaks — that's a skip."""+ hunt = _make_hunt(translated={"kql": "event.code:4625"})+ _wire(monkeypatch, resolve_error=UnsupportedTranslation("no live driver for kql"))hits = await hunt_scheduler._execute_hunt(fake_db, hunt)@@ -91,21 +143,45 @@ class TestExecuteHuntSkipPaths: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]- monkeypatch.setattr(- hunt_scheduler,- "resolve_provider",- MagicMock(side_effect=UnsupportedTranslation("hunt has no translated_query dict")),+ _wire(monkeypatch, resolve_error=UnsupportedTranslation("hunt has no translated_query dict"))++ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)++ assert hits == 0++ async def test_skips_when_tenant_has_connected_no_warehouse(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ """A tenant who never connected a SIEM is a soft skip, not an error."""+ hunt = _make_hunt(translated={"esql": "FROM logs"})+ _wire(+ monkeypatch,+ connected=set(),+ resolve_error=UnsupportedTranslation("no enabled connector of type ['elastic', 'splunk']"),)hits = await hunt_scheduler._execute_hunt(fake_db, hunt)assert hits == 0+ async def test_skips_when_credentials_cannot_be_resolved(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ """Connector row exists but its secret will not decrypt → soft skip."""+ hunt = _make_hunt(translated={"esql": "FROM logs"})+ provider = _stub_provider(run=AsyncMock(side_effect=AssertionError("provider should not be called")))+ _wire(+ monkeypatch,+ provider=provider,+ credentials=HuntNotConfigured("stored credentials could not be decrypted"),+ )++ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)++ assert hits == 0+ provider.run_hunt.assert_not_called()+async def test_skips_when_provider_reports_not_configured(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:- """ES creds missing → :class:`HuntNotConfigured` → soft skip."""+ """Connector saved without a URL → :class:`HuntNotConfigured` → soft skip."""hunt = _make_hunt(translated={"esql": "FROM logs"})- provider = _stub_provider(run=AsyncMock(side_effect=HuntNotConfigured("no ES_URL")))- monkeypatch.setattr(hunt_scheduler, "resolve_provider", MagicMock(return_value=provider))+ provider = _stub_provider(run=AsyncMock(side_effect=HuntNotConfigured("connector has no cluster URL")))+ _wire(monkeypatch, provider=provider)hits = await hunt_scheduler._execute_hunt(fake_db, hunt)@@ -113,23 +189,64 @@ class TestExecuteHuntSkipPaths:provider.run_hunt.assert_awaited_once()+class TestExecuteHuntTenantScoping:+ """The credentials a driver receives belong to the hunt's own tenant."""++ async def test_looks_up_connectors_for_the_hunts_tenant(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ tenant_id = uuid.uuid4()+ hunt = _make_hunt(translated={"esql": "FROM logs"}, tenant_id=tenant_id)+ mocks = _wire(monkeypatch, provider=_stub_provider(run=AsyncMock(return_value=1)))++ await hunt_scheduler._execute_hunt(fake_db, hunt)++ args, kwargs = mocks["connected"].await_args+ assert args[0] is fake_db+ assert args[1] == tenant_id+ assert set(kwargs["candidate_types"]) == {"elastic", "splunk"}++ async def test_passes_tenant_credentials_to_provider(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ """The regression: ``_execute_hunt`` used to ignore ``db`` entirely and+ the drivers read process settings, so no stored credential ever+ reached a warehouse."""+ tenant_id = uuid.uuid4()+ hunt = _make_hunt(translated={"esql": "FROM logs"}, tenant_id=tenant_id)+ creds = _credentials()+ run = AsyncMock(return_value=7)+ mocks = _wire(monkeypatch, provider=_stub_provider(run=run), credentials=creds)++ hits = await hunt_scheduler._execute_hunt(fake_db, hunt)++ assert hits == 7+ run.assert_awaited_once_with(hunt, credentials=creds, max_rows=500)+ args, kwargs = mocks["credentials"].await_args+ assert args[1] == tenant_id+ assert kwargs["connector_types"] == ("elastic",)++ async def test_selection_is_scoped_by_what_the_tenant_connected(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ hunt = _make_hunt(translated={"esql": "FROM logs", "spl": "index=foo"})+ mocks = _wire(monkeypatch, connected={"splunk"})++ await hunt_scheduler._execute_hunt(fake_db, hunt)++ _, kwargs = mocks["resolve"].call_args+ assert kwargs["connected_types"] == {"splunk"}++class TestExecuteHuntHappyPath:"""When everything is wired up, return the hit count the provider produced."""async def test_returns_provider_hit_count(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:hunt = _make_hunt(translated={"esql": "FROM logs | WHERE event.code == 4625"})provider = _stub_provider(run=AsyncMock(return_value=3))- monkeypatch.setattr(hunt_scheduler, "resolve_provider", MagicMock(return_value=provider))+ _wire(monkeypatch, provider=provider)hits = await hunt_scheduler._execute_hunt(fake_db, hunt)assert hits == 3- provider.run_hunt.assert_awaited_once_with(hunt, max_rows=500)async def test_returns_zero_when_provider_returns_empty(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:hunt = _make_hunt(translated={"esql": "FROM logs"})- provider = _stub_provider(run=AsyncMock(return_value=0))- monkeypatch.setattr(hunt_scheduler, "resolve_provider", MagicMock(return_value=provider))+ _wire(monkeypatch, provider=_stub_provider(run=AsyncMock(return_value=0)))hits = await hunt_scheduler._execute_hunt(fake_db, hunt)@@ -141,8 +258,7 @@ class TestExecuteHuntErrorPropagation:async def test_airgap_violation_propagates(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:hunt = _make_hunt(translated={"esql": "FROM logs"})- provider = _stub_provider(run=AsyncMock(side_effect=AirgapViolation("egress blocked")))- monkeypatch.setattr(hunt_scheduler, "resolve_provider", MagicMock(return_value=provider))+ _wire(monkeypatch, provider=_stub_provider(run=AsyncMock(side_effect=AirgapViolation("egress blocked"))))with pytest.raises(AirgapViolation):await hunt_scheduler._execute_hunt(fake_db, hunt)@@ -150,16 +266,22 @@ class TestExecuteHuntErrorPropagation: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"})- provider = _stub_provider(run=AsyncMock(side_effect=ValueError("host mismatch")))- monkeypatch.setattr(hunt_scheduler, "resolve_provider", MagicMock(return_value=provider))+ _wire(monkeypatch, provider=_stub_provider(run=AsyncMock(side_effect=ValueError("host mismatch"))))with pytest.raises(ValueError, match="host mismatch"):await hunt_scheduler._execute_hunt(fake_db, hunt)async def test_hunt_execution_error_propagates(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:hunt = _make_hunt(translated={"esql": "FROM logs"})- provider = _stub_provider(run=AsyncMock(side_effect=HuntExecutionError("ES 500")))- monkeypatch.setattr(hunt_scheduler, "resolve_provider", MagicMock(return_value=provider))+ _wire(monkeypatch, provider=_stub_provider(run=AsyncMock(side_effect=HuntExecutionError("ES 500"))))with pytest.raises(HuntExecutionError):await hunt_scheduler._execute_hunt(fake_db, hunt)++ async def test_connector_lookup_failure_propagates(self, fake_db: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ """A database error reading connectors must not be reported as zero hits."""+ hunt = _make_hunt(translated={"esql": "FROM logs"})+ _wire(monkeypatch, connected_error=RuntimeError("connection pool exhausted"))++ with pytest.raises(RuntimeError, match="connection pool exhausted"):+ await hunt_scheduler._execute_hunt(fake_db, hunt)diff --git a/services/api/tests/test_spl_runner.py b/services/api/tests/test_spl_runner.pynew file mode 100644index 000000000..6b77889c2--- /dev/null+++ b/services/api/tests/test_spl_runner.py@@ -0,0 +1,185 @@+"""Unit tests for the Splunk SPL executor.++Sibling of ``test_esql_runner``. The guards are the same three the ES|QL+runner carries — SSRF allow-list, air-gap policy, row cap — plus two+Splunk-specific behaviours that a missing test would let regress silently:++* ``POST /services/search/jobs`` rejects a search string that does not start+ with ``search`` or a generating ``|``. The platform translator emits+ ``index=* earliest=-24h ... | head 500``, which starts with neither, so+ every hunt would 400 without the prefix.+* The management port is 8089, not the web UI port. Nothing here can enforce+ that, but the connector help text says so and the failure message names it.+"""++from __future__ import annotations++from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import pytest+from app.core.airgap import AirgapViolation+from app.services.spl_runner import (+ SPLExecutionError,+ _as_search_command,+ _cap_rows,+ _validate_splunk_url,+ run_spl_query,+)++BASE_URL = "https://splunk.example.com:8089"+++def _patched_post(resp: Any) -> Any:+ client = MagicMock()+ if isinstance(resp, Exception):+ client.post = AsyncMock(side_effect=resp)+ else:+ client.post = AsyncMock(return_value=resp)+ ctx = MagicMock()+ ctx.__aenter__ = AsyncMock(return_value=client)+ ctx.__aexit__ = AsyncMock(return_value=False)+ return patch("httpx.AsyncClient", return_value=ctx), client+++def _ok_response(rows: list[dict[str, Any]]) -> MagicMock:+ resp = MagicMock(spec=httpx.Response)+ resp.status_code = 200+ resp.raise_for_status = MagicMock()+ resp.json = MagicMock(return_value={"results": rows})+ resp.text = ""+ return resp+++class TestSearchCommandPrefix:+ def test_bare_expression_is_prefixed(self) -> None:+ """The translator's output starts with ``index=``; Splunk's REST API+ requires an explicit leading ``search``."""+ assert _as_search_command("index=* earliest=-24h | head 500") == "search index=* earliest=-24h | head 500"++ def test_existing_search_command_is_left_alone(self) -> None:+ assert _as_search_command("search index=main") == "search index=main"++ def test_generating_pipe_command_is_left_alone(self) -> None:+ assert _as_search_command("| tstats count where index=main") == "| tstats count where index=main"++ def test_prefix_check_is_case_insensitive(self) -> None:+ assert _as_search_command("SEARCH index=main") == "SEARCH index=main"+++class TestRowCap:+ def test_appends_head_when_absent(self) -> None:+ assert _cap_rows("search index=main", 250) == "search index=main | head 250"++ def test_respects_an_existing_head(self) -> None:+ assert _cap_rows("search index=main | head 10", 250) == "search index=main | head 10"++ def test_word_head_in_the_search_body_is_not_a_row_cap(self) -> None:+ """A search for the word "head" must still get a cap — otherwise a+ hunt matching that term pulls the whole index into memory."""+ capped = _cap_rows('search index=main message="head crash"', 100)+ assert capped.endswith("| head 100")+++class TestUrlValidation:+ def test_matching_host_is_accepted_and_rebuilt(self) -> None:+ assert _validate_splunk_url(BASE_URL, allowed_url=BASE_URL) == "https://splunk.example.com:8089"++ def test_path_and_query_are_discarded(self) -> None:+ """The returned value is rebuilt from scheme+netloc only, so a caller+ cannot steer the request to another path on the same host."""+ got = _validate_splunk_url(f"{BASE_URL}/evil?x=1", allowed_url=BASE_URL)+ assert got == "https://splunk.example.com:8089"++ def test_different_host_is_refused(self) -> None:+ with pytest.raises(ValueError, match="is not the configured host"):+ _validate_splunk_url("https://attacker.example.com", allowed_url=BASE_URL)++ def test_different_port_is_refused(self) -> None:+ """netloc includes the port, so 8000 (web UI) is not 8089 (management)."""+ with pytest.raises(ValueError, match="is not the configured host"):+ _validate_splunk_url("https://splunk.example.com:8000", allowed_url=BASE_URL)++ @pytest.mark.parametrize("scheme", ["file", "ftp", "gopher"])+ def test_non_http_schemes_are_refused(self, scheme: str) -> None:+ with pytest.raises(ValueError, match="Unsupported URL scheme"):+ _validate_splunk_url(f"{scheme}://splunk.example.com", allowed_url=BASE_URL)++ def test_empty_allow_list_is_refused(self) -> None:+ with pytest.raises(ValueError, match="No allowed Splunk host"):+ _validate_splunk_url(BASE_URL, allowed_url="")+++class TestRunSplQuery:+ async def test_returns_rows_and_sends_a_oneshot_search(self) -> None:+ patcher, client = _patched_post(_ok_response([{"host": "a"}, {"host": "b"}]))+ with patcher:+ result = await run_spl_query(spl="index=main", base_url=BASE_URL, token="t", max_rows=50)++ assert len(result.rows) == 2+ _, kwargs = client.post.await_args+ assert kwargs["data"]["exec_mode"] == "oneshot"+ assert kwargs["data"]["search"] == "search index=main | head 50"+ assert kwargs["headers"]["Authorization"] == "Bearer t"++ async def test_basic_auth_when_no_token(self) -> None:+ patcher, client = _patched_post(_ok_response([]))+ with patcher:+ await run_spl_query(spl="index=main", base_url=BASE_URL, username="svc", password="pw")++ _, kwargs = client.post.await_args+ assert kwargs["auth"] == ("svc", "pw")+ assert "Authorization" not in kwargs["headers"]++ async def test_non_dict_rows_are_dropped(self) -> None:+ patcher, _ = _patched_post(_ok_response(["not-a-row", {"host": "a"}])) # type: ignore[list-item]+ with patcher:+ result = await run_spl_query(spl="index=main", base_url=BASE_URL, token="t")++ assert result.rows == [{"host": "a"}]++ async def test_missing_credentials_raise_value_error(self) -> None:+ with pytest.raises(ValueError, match="token or a username/password"):+ await run_spl_query(spl="index=main", base_url=BASE_URL)++ async def test_http_error_is_wrapped_with_the_body(self) -> None:+ """Splunk puts the useful diagnostic in the body; the status alone+ sends an operator looking at the wrong thing."""+ resp = MagicMock(spec=httpx.Response)+ resp.status_code = 400+ resp.text = "Unknown search command 'indexx'"+ err = httpx.HTTPStatusError("bad", request=MagicMock(), response=resp)+ resp.raise_for_status = MagicMock(side_effect=err)+ patcher, _ = _patched_post(resp)++ with patcher:+ with pytest.raises(SPLExecutionError, match="Unknown search command"):+ await run_spl_query(spl="index=main", base_url=BASE_URL, token="t")++ async def test_transport_error_is_wrapped(self) -> None:+ patcher, _ = _patched_post(httpx.ConnectError("refused"))+ with patcher:+ with pytest.raises(SPLExecutionError, match="SPL execution failed"):+ await run_spl_query(spl="index=main", base_url=BASE_URL, token="t")++ async def test_airgap_violation_propagates_before_any_request(self) -> None:+ patcher, client = _patched_post(_ok_response([]))+ with (+ patcher,+ patch(+ "app.services.spl_runner.enforce_airgap_for_url",+ side_effect=AirgapViolation("egress blocked"),+ ),+ ):+ with pytest.raises(AirgapViolation):+ await run_spl_query(spl="index=main", base_url=BASE_URL, token="t")++ client.post.assert_not_awaited()++ async def test_ssl_verification_is_forwarded(self) -> None:+ patcher, _ = _patched_post(_ok_response([]))+ with patcher as mock_client:+ await run_spl_query(spl="index=main", base_url=BASE_URL, token="t", verify_ssl=False)++ assert mock_client.call_args.kwargs["verify"] is False