Skip to content

Commit f22f9a2

Browse files
Add keep metadata check to esql schema test
1 parent 793ecfe commit f22f9a2

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

detection_rules/rule.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -990,12 +990,25 @@ def validates_esql_data(self, data: dict[str, Any], **_: Any) -> None:
990990

991991
# Enforce KEEP command for ESQL rules
992992
# Match | followed by optional whitespace/newlines and then 'keep'
993-
keep_pattern = re.compile(r"\|\s*keep\b", re.IGNORECASE | re.DOTALL)
994-
if not keep_pattern.search(query_lower):
993+
keep_pattern = re.compile(r"\|\s*keep\b\s+([^\|]+)", re.IGNORECASE | re.DOTALL)
994+
keep_match = keep_pattern.search(query_lower)
995+
if not keep_match:
995996
raise EsqlSemanticError(
996997
f"Rule: {data['name']} does not contain a 'keep' command -> Add a 'keep' command to the query."
997998
)
998999

1000+
# Ensure that keep clause includes metadata fields on non-aggregate queries
1001+
aggregate_pattern = re.compile(r"\bstats\b.*\bby\b", re.IGNORECASE | re.DOTALL)
1002+
if not aggregate_pattern.search(query_lower):
1003+
keep_fields = keep_match.group(1)
1004+
required_metadata = {"_id", "_version", "_index"}
1005+
if not required_metadata.issubset(set(map(str.strip, keep_fields.split(",")))):
1006+
raise EsqlSemanticError(
1007+
f"Rule: {data['name']} contains a keep clause without"
1008+
f" metadata fields '_id', '_version', and '_index' ->"
1009+
f" Add '_id, _version, _index' to the keep command."
1010+
)
1011+
9991012

10001013
@dataclass(frozen=True, kw_only=True)
10011014
class ThreatMatchRuleData(QueryRuleData):

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "detection_rules"
3-
version = "1.5.22"
3+
version = "1.5.23"
44
description = "Detection Rules is the home for rules used by Elastic Security. This repository is used for the development, maintenance, testing, validation, and release of rules for Elastic Security’s Detection Engine."
55
readme = "README.md"
66
requires-python = ">=3.12"

0 commit comments

Comments
 (0)