Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 44 additions & 46 deletions detection_rules/esql.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,21 @@

from __future__ import annotations

import copy
import functools
import re
from dataclasses import dataclass
from typing import Any, cast

import esql
from semver import Version

from . import ecs
from .config import CUSTOM_RULES_DIR
from .config import CUSTOM_RULES_DIR, load_current_package_version
from .schemas.definitions import (
ESQL_INDEX_PATTERN_REGEX,
)
from .utils import strip_index_expression
from .utils import cached, strip_index_expression

# Legacy / alternate dataset package prefixes → Fleet package names.
DATASET_PACKAGE_ALIASES: dict[str, str] = {
Expand Down Expand Up @@ -58,19 +60,32 @@ class EsqlSourceGroup:


def _parse_for_extraction(query: str) -> Any:
"""Parse under the current package config when the caller did not pass an AST.

No schema is installed, so this only applies grammar, feature, and nested
KQL/EQL hooks. Column checks stay with the validation plan.
"""
from .config import load_current_package_version
"""Parse a query under the current package config when the caller did not pass an AST."""
# no schema is installed, so column checks stay with the validation plan
from .rule import set_esql_config

cfg = set_esql_config(load_current_package_version())
with cfg:
return esql.parse_query(query)


def parse_esql_query(query: str, min_stack_version: str | None = None) -> Any:
"""Parse an ES|QL query for a stack version without checking index fields."""
stack = str(Version.parse(min_stack_version or load_current_package_version(), optional_minor_and_patch=True))
# copy: the tree is shared and esql.analyze() modifies LOOKUP JOIN fields
return copy.deepcopy(_parse_esql_query(query, stack))


@cached
def _parse_esql_query(query: str, stack_version: str) -> Any:
"""Memoized body of `parse_esql_query`."""
# failures are not cached and re-raise
from .rule import set_esql_config

with set_esql_config(stack_version), esql.Schema({}, allow_missing=True):
return esql.parse_query(query)


def get_esql_query_event_dataset_integrations(query: str, tree: Any | None = None) -> list[EventDataset]:
"""Extract event.dataset / data_stream.dataset integrations from an ES|QL query."""
parsed = tree if tree is not None else _parse_for_extraction(query)
Expand Down Expand Up @@ -119,11 +134,8 @@ def local_esql_index(source: str) -> str:


def index_patterns_match(left: str, right: str) -> bool:
"""Return True when some index name can match both patterns.

``*`` is any sequence and ``?`` is one character. Overlapping globs such as
``logs-*-foo`` and ``logs-bar-*`` match.
"""
"""Return True when some index name can match both patterns."""
# `*` is any sequence and `?` is one character, so `logs-*-foo` and `logs-bar-*` overlap
if left == right:
return True
return _index_patterns_overlap(left, right)
Expand Down Expand Up @@ -179,13 +191,12 @@ def infer_packages_from_indices(indices: list[str]) -> list[str]:
return packages


@cached
def collect_index_field_schemas(indices: list[str]) -> dict[str, Any]:
"""Merge non-ECS / custom field schemas for the given FROM indices.

Mirrors remote `prepare_mappings` so offline validation includes alert fields
(`kibana.alert.*`), integration gaps tracked in `non-ecs-schema.json`, and
custom index schemas.
"""
"""Merge the non-ECS, alert, endpoint and custom field schemas for FROM indices."""
# mirrors remote `prepare_mappings`, so offline validation also sees `kibana.alert.*` fields,
# integration gaps tracked in `non-ecs-schema.json` and custom index schemas
# cached: the returned dict is shared, so callers must treat it as read-only
fields: dict[str, Any] = {}
non_ecs = ecs.get_non_ecs_schema()
for index in indices:
Expand All @@ -198,12 +209,10 @@ def collect_index_field_schemas(indices: list[str]) -> dict[str, Any]:


def collect_lookup_index_field_schemas(indices: list[str]) -> dict[str, dict[str, Any]]:
"""Per-LOOKUP-JOIN-target field maps (no blanket endpoint union).

Named lookup tables only receive custom / non-ECS fields that match that
index. Fleet datastreams used as lookup targets still get their matching
non-ECS rows here; ECS and package streams are merged by the validator.
"""
"""Get the non-ECS and custom field schemas for each LOOKUP JOIN target."""
# unlike `collect_index_field_schemas`, the endpoint schemas are not unioned in, so a named
# lookup table only gets the fields that match it. ECS and package stream fields are merged
# in by the validator
non_ecs = ecs.get_non_ecs_schema()
result: dict[str, dict[str, Any]] = {}
for index in indices:
Expand Down Expand Up @@ -250,12 +259,10 @@ def collect_package_fields_for_indices(
*,
allow_fallback: bool = True,
) -> dict[str, Any]:
"""Collect package fields, restricted to streams that match FROM indices.

When *integration* is set, returns that stream only if it matches. When unset,
unions matching streams. If no stream matches (should be rare), falls back to
all streams so broad patterns are not under-validated.
"""
"""Collect the package fields from streams that match the FROM indices."""
# with `integration` set, only that stream is returned, and only if it matches. Otherwise the
# matching streams are unioned, and when none match (rare) `allow_fallback` unions every
# stream so broad patterns are not under-validated
if integration is not None:
if integration not in package_schema:
return {}
Expand Down Expand Up @@ -297,11 +304,7 @@ def split_esql_source_list(sources: str) -> list[str]:


def get_esql_query_source_groups(query: str, tree: Any | None = None) -> list[EsqlSourceGroup]:
"""Group FROM/TS clauses by index patterns using the ES|QL AST (with rewrite spans).

One parse yields indices for schema selection and character spans for remote
index rewriting — no separate regex pass. Unparseable fragments return [].
"""
"""Group FROM/TS clauses and their spans by index patterns."""
try:
parsed = tree if tree is not None else _parse_for_extraction(query)
except Exception: # noqa: BLE001 — incomplete fragments have no FROM groups
Expand All @@ -313,11 +316,8 @@ def get_esql_query_source_groups(query: str, tree: Any | None = None) -> list[Es


def get_esql_query_indices(query: str, tree: Any | None = None) -> list[str]:
"""Extract unique FROM/TS index patterns via the ES|QL AST (CCS prefix stripped).

Call with ``tree=`` after the offline allow_missing parse so schema planning
reuses that AST instead of parsing again.
"""
"""Extract unique FROM/TS index patterns with any cluster prefix removed."""
# pass `tree=` from an earlier parse so schema planning does not parse the query again
indices: list[str] = []
for _, index in get_esql_query_source_patterns(query, tree=tree):
if index not in indices:
Expand All @@ -326,11 +326,9 @@ def get_esql_query_indices(query: str, tree: Any | None = None) -> list[str]:


def get_esql_query_source_patterns(query: str, tree: Any | None = None) -> list[tuple[str, str]]:
"""Extract unique FROM/TS sources as (pattern as written, local index pattern) pairs.

The written form keeps any `cluster:` prefix and `::` selector, which is what the parser
matches when it narrows a multi-index schema to one FROM. The local pattern drops both.
"""
"""Extract unique FROM/TS sources as (pattern as written, local index pattern) pairs."""
# the written form keeps any `cluster:` prefix and `::` selector, which is what the parser
# matches when it narrows a multi-index schema to one FROM. The local pattern drops both
try:
parsed = tree if tree is not None else _parse_for_extraction(query)
except Exception: # noqa: BLE001 — incomplete fragments yield no sources
Expand Down
4 changes: 2 additions & 2 deletions detection_rules/integrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -658,15 +658,15 @@ def get_integration_schema_fields(
# Resolves against the bundled integration-manifests / integration-schemas via memoized helpers
# keyed on hashable args. The returned schema is memoized and shared, so callers must treat it
# as read-only.
package_version, notice = _latest_compatible_version_from_etc(package, integration, str(min_stack))
package_version, notice = latest_compatible_version_from_etc(package, integration, str(min_stack))
notify_user_if_update_available(data, list(notice), integration)

integration_schema = _integration_schema(package, package_version, integration)
return integration_schema, package_version


@cached
def _latest_compatible_version_from_etc(
def latest_compatible_version_from_etc(
package: str, integration: str, stack_version: str
) -> tuple[str, tuple[str, ...]]:
"""Memoized `find_latest_compatible_version` against the bundled manifests and schemas."""
Expand Down
10 changes: 3 additions & 7 deletions detection_rules/rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
get_esql_query_event_dataset_integrations,
get_esql_query_index_datasets,
normalize_dataset_package,
parse_esql_query,
)
from .esql_errors import EsqlSemanticError, public_esql_error
from .integrations import (
Expand Down Expand Up @@ -1094,8 +1095,6 @@ def validates_esql_data(self, data: dict[str, Any], **_: Any) -> None:
bypass_metadata = os.environ.get("DR_BYPASS_ESQL_METADATA_VALIDATION") is not None
bypass_keep = os.environ.get("DR_BYPASS_ESQL_KEEP_VALIDATION") is not None

cfg = set_esql_config(load_current_package_version())

def reject_incomplete_keeps(tree: Any) -> None:
"""Require metadata columns on every KEEP of a non-aggregating query."""
if esql.has_aggregating_stats(tree):
Expand All @@ -1113,8 +1112,7 @@ def reject_incomplete_keeps(tree: Any) -> None:
)

try:
with cfg, esql.Schema({}, allow_missing=True):
tree = esql.parse_query(data["query"])
tree = parse_esql_query(data["query"])
if not bypass_metadata and not bypass_keep:
esql.validate_detection_rule_query(tree, name=data["name"])
reject_incomplete_keeps(tree)
Expand Down Expand Up @@ -2240,9 +2238,7 @@ def get_unique_query_fields(rule: TOMLRule) -> list[str] | None:

if not isinstance(query, str):
raise TypeError("ES|QL rule query must be a string")
cfg = set_esql_config(min_stack_version)
with cfg, esql.Schema({}, allow_missing=True):
tree = esql.parse_query(query)
tree = parse_esql_query(query, min_stack_version)
from .rule_validators import ESQLValidator

names = set(esql.get_unique_fields(tree))
Expand Down
Loading
Loading