Repository navigation
Expand file tree
/
Copy pathtest_esql_parser.py
More file actions
704 lines (615 loc) · 32.5 KB
/
Copy pathtest_esql_parser.py
File metadata and controls
704 lines (615 loc) · 32.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License
# 2.0; you may not use this file except in compliance with the Elastic License
# 2.0.
"""ES|QL parser validation unit tests (no remote cluster)."""
from __future__ import annotations
import re
from copy import deepcopy
import pytest
from detection_rules.esql import (
collect_index_field_schemas,
collect_lookup_index_field_schemas,
get_esql_lookup_join_targets,
index_patterns_match,
infer_packages_from_indices,
lookup_index_uses_ecs,
normalize_dataset_package,
)
from detection_rules.esql_errors import EsqlSchemaError, EsqlUnknownIndexError
from detection_rules.index_mappings import (
assert_known_esql_indices,
collect_known_esql_index_patterns,
integration_stream_keys,
)
from detection_rules.rule import get_unique_query_fields
from detection_rules.rule_loader import RuleCollection
from detection_rules.utils import get_path, load_rule_contents
def _sample_rule() -> dict:
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
return deepcopy(load_rule_contents(file_path)[0])
class TestEsqlOfflineSchemaFailures:
"""Queries that must fail offline validation with allow_missing=False."""
def test_unknown_index_raises_offline(self) -> None:
"""Parity with remote test_esql_endpoint_unknown_index."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.fake-* METADATA _id, _version, _index
| WHERE event.code in ("malicious_file", "memory_signature", "shellcode_thread")
| KEEP host.id, rule.name, event.code, _id, _version, _index
"""
with pytest.raises(EsqlUnknownIndexError, match=re.escape("logs-endpoint.fake")):
RuleCollection().load_dict(rule)
def test_stream_keys_cover_metrics_and_traces(self) -> None:
"""Fleet streams are known as logs, metrics, and traces index patterns."""
patterns = collect_known_esql_index_patterns({"system-cpu"}, [])
assert "logs-system.cpu*" in patterns
assert "metrics-system.cpu*" in patterns
assert "traces-system.cpu*" in patterns
assert assert_known_esql_indices(["metrics-system.cpu-*"], {"system-cpu"})
assert assert_known_esql_indices(["metrics-system.cpu-default"], {"system-cpu"})
assert assert_known_esql_indices(["packetbeat-*"], set())
def test_one_unknown_index_among_known_still_raises(self) -> None:
"""Every FROM index must match a known pattern."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-*, logs-endpoint.fake-* METADATA _id, _version, _index
| WHERE host.name == "workstation"
| KEEP host.name, _id, _version, _index
"""
with pytest.raises(EsqlUnknownIndexError, match=re.escape("logs-endpoint.fake")):
RuleCollection().load_dict(rule)
def test_unknown_dataset_package_does_not_raise_manifest_error(self) -> None:
"""A data_stream.dataset value outside the manifests must not raise ValueError."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE data_stream.dataset == "notapkg.stream"
| KEEP host.name, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_custom_rules_dir_skips_unknown_index(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Custom and customized prebuilt rules may use data streams outside Fleet manifests."""
monkeypatch.setattr("detection_rules.index_mappings.CUSTOM_RULES_DIR", "custom-rules-dir")
rule = _sample_rule()
rule["metadata"]["integration"] = []
rule["rule"]["query"] = """
FROM logs-acme.private-* METADATA _id, _version, _index
| WHERE host.name == "workstation"
| KEEP host.name, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_older_grammar_reparse_uses_detection_rules_syntax_error(self) -> None:
"""A reparse for an older stack grammar raises detection_rules EsqlSyntaxError."""
import esql
from detection_rules.esql_errors import EsqlSyntaxError
rule = _sample_rule()
rule["metadata"]["min_stack_version"] = "8.19.0"
rule["metadata"]["integration"] = ["endpoint"]
# Map-form COMPLETION parses on 9.3+ grammars and is rejected by the 8.19 grammar.
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| COMPLETION triage_result = "x" WITH { "inference_id": "model" }
| KEEP triage_result, _id, _version, _index
"""
with pytest.raises(EsqlSyntaxError, match=r"COMPLETION|mismatched") as caught:
RuleCollection().load_dict(rule)
assert not isinstance(caught.value, esql.EsqlSyntaxError)
def test_unknown_field_raises_schema_error(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE totally.made_up.field == "x"
| KEEP totally.made_up.field, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError, match=re.escape("totally.made_up.field")):
RuleCollection().load_dict(rule)
def test_keep_only_unknown_field_raises_schema_error(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| KEEP totally_unknown_keep_field, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError, match="totally_unknown_keep_field"):
RuleCollection().load_dict(rule)
def test_required_fields_use_integration_types(self) -> None:
"""Integration fields keep their package type after offline validation."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["aws"]
rule["rule"]["query"] = """
FROM logs-aws.cloudtrail-* METADATA _id, _version, _index
| WHERE aws.cloudtrail.user_identity.type == "IAMUser"
| KEEP aws.cloudtrail.user_identity.type, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
fields = loaded.contents.data.get_required_fields([]) or []
typed = {item["name"]: item["type"] for item in fields}
assert typed["aws.cloudtrail.user_identity.type"] == "keyword"
def test_package_covered_index_does_not_accept_undeclared_ecs_field(self) -> None:
"""Fleet-covered indices do not inherit the full ECS schema."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE faas.trigger.type == "http"
| KEEP faas.trigger.type, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError, match=re.escape("faas.trigger.type")):
RuleCollection().load_dict(rule)
def test_field_from_unrelated_package_raises_schema_error(self) -> None:
"""Endpoint-only package plan must reject azure-only fields."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE azure.signinlogs.properties.session_id == "abc"
| KEEP azure.signinlogs.properties.session_id, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError, match=re.escape("azure.signinlogs.properties.session_id")):
RuleCollection().load_dict(rule)
def test_field_outside_index_stream_raises_schema_error(self) -> None:
"""billing index must not validate cloudtrail-only fields (stream filter)."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["aws"]
rule["rule"]["query"] = """
FROM logs-aws.billing-* METADATA _id, _version, _index
| WHERE aws.cloudtrail.user_identity.type == "IAMUser"
| KEEP aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError):
RuleCollection().load_dict(rule)
def test_combined_from_unions_sibling_stream_fields(self) -> None:
"""One FROM of several indices still sees fields from any of those indices."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["aws"]
rule["rule"]["query"] = """
FROM logs-aws.cloudtrail-*, logs-aws.billing-* METADATA _id, _version, _index
| WHERE aws.cloudtrail.user_identity.type == "IAMUser"
| KEEP aws.cloudtrail.user_identity.type, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_subquery_does_not_see_sibling_stream_fields(self) -> None:
"""A field present on one subquery source is unknown inside the other."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["aws"]
rule["rule"]["query"] = """
FROM
(FROM logs-aws.cloudtrail-* | KEEP aws.cloudtrail.user_identity.type),
(FROM logs-aws.billing-* | WHERE aws.cloudtrail.user_identity.type == "IAMUser" | KEEP host.name)
| STATS count = COUNT(*) BY host.name
| KEEP count, host.name
"""
with pytest.raises(EsqlSchemaError, match=re.escape("aws.cloudtrail.user_identity.type")):
RuleCollection().load_dict(rule)
def test_uncovered_index_does_not_attach_ecs_to_sibling_subquery(self) -> None:
"""Full ECS stays on the uncovered FROM. A package stream beside it does not inherit it."""
from esql.versions import Version
from detection_rules.config import load_current_package_version
if Version.parse(load_current_package_version()) < Version(9, 5):
pytest.skip("Subquery FROM index spans require the 9.5 grammar")
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "9.5.0"
rule["rule"]["query"] = """
FROM
(FROM logs-endpoint.events.process-* | WHERE faas.trigger.type == "http" | KEEP host.name),
(FROM packetbeat-* | KEEP host.name)
| STATS count = COUNT(*) BY host.name
| KEEP count, host.name
"""
with pytest.raises(EsqlSchemaError, match=re.escape("faas.trigger.type")):
RuleCollection().load_dict(rule)
rule["rule"]["query"] = """
FROM
(FROM packetbeat-* | KEEP process.command_line.text),
(FROM logs-endpoint.events.process-* | KEEP host.name)
| STATS count = COUNT(*) BY host.name
| KEEP count, host.name
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_stack_only_schema_keeps_ecs_multi_fields(self) -> None:
"""Beats indices with no Fleet package still accept ECS multi-fields."""
rule = _sample_rule()
rule["metadata"].pop("integration", None)
rule["metadata"]["min_stack_version"] = "9.6.0"
rule["rule"]["query"] = """
FROM packetbeat-* METADATA _id, _version, _index
| KEEP process.command_line.text, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_patch_gated_stream_is_a_known_index(self) -> None:
"""Known-index checks resolve the patch floor, not the .0 stack-map key."""
from detection_rules.integrations import load_integrations_manifests, load_integrations_schemas
schemas = load_integrations_schemas()
if "aadgraphactivitylogs" not in schemas.get("azure", {}).get("1.37.0", {}):
pytest.skip("bundled azure manifests have no patch-gated aadgraphactivitylogs stream")
keys = integration_stream_keys(
["azure"],
[],
load_integrations_manifests(),
schemas,
"8.19.0",
)
assert "azure-aadgraphactivitylogs" in keys
rule = _sample_rule()
rule["metadata"]["integration"] = ["azure"]
rule["metadata"]["min_stack_version"] = "8.19.0"
rule["rule"]["query"] = """
FROM logs-azure.aadgraphactivitylogs-* METADATA _id, _version, _index
| WHERE azure.aadgraphactivitylogs.category == "SignIn"
| KEEP azure.aadgraphactivitylogs.category, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_stack_subquery_does_not_see_sibling_index_fields(self) -> None:
"""Without packages, each subquery still gets only its own FROM index fields."""
rule = _sample_rule()
rule["metadata"].pop("integration", None)
rule["rule"]["query"] = """
FROM
(FROM .alerts-security.* | KEEP host.name),
(FROM auditbeat-* | WHERE kibana.alert.rule.name == "x" | KEEP host.name)
| STATS c = COUNT(*) BY host.name
| KEEP c, host.name
"""
with pytest.raises(EsqlSchemaError, match=re.escape("kibana.alert.rule.name")):
RuleCollection().load_dict(rule)
def test_unique_fields_include_nested_kql(self) -> None:
"""Rule search and packaging see fields that appear only inside KQL()."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "8.16.0"
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE KQL("process.command_line: *whoami*")
| KEEP host.name, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
fields = get_unique_query_fields(loaded)
assert fields is not None
assert "process.command_line" in fields
def test_keyword_compared_to_number_raises_type_mismatch(self) -> None:
"""Parity with remote test_esql_type_mismatch_error (keyword == number)."""
from detection_rules.esql_errors import EsqlTypeMismatchError
rule = _sample_rule()
rule["metadata"]["integration"] = ["aws"]
rule["rule"]["query"] = """
FROM logs-aws.cloudtrail-* METADATA _id, _version, _index
| WHERE aws.cloudtrail.user_identity.type == 5
| KEEP aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlTypeMismatchError):
RuleCollection().load_dict(rule)
def test_long_field_like_string_raises_type_mismatch(self) -> None:
from detection_rules.esql_errors import EsqlTypeMismatchError
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE process.pid LIKE "1*"
| KEEP process.pid, _id, _version, _index
"""
with pytest.raises(EsqlTypeMismatchError):
RuleCollection().load_dict(rule)
def test_long_ordered_against_string_raises_type_mismatch(self) -> None:
from detection_rules.esql_errors import EsqlTypeMismatchError
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE process.pid > "10"
| KEEP process.pid, _id, _version, _index
"""
with pytest.raises(EsqlTypeMismatchError):
RuleCollection().load_dict(rule)
class TestEsqlOfflineSchemaPasses:
"""Queries that must pass once schemas / defined columns are correct."""
def test_nested_kql_uppercase_operators_pass(self) -> None:
"""Nested KQL() must accept uppercase NOT/AND/OR (Kibana parity)."""
rule = _sample_rule()
del rule["metadata"]["integration"]
rule["rule"]["query"] = '''
FROM .alerts-security.* METADATA _id, _version, _index
| WHERE KQL("""NOT kibana.alert.rule.name : never-match-token""")
| KEEP kibana.alert.rule.name, _id, _version, _index
'''
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_nested_kql_unknown_field_raises_schema_error(self) -> None:
"""Nested KQL() payloads must schema-validate against the ValidationTarget."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = '''
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE KQL("""totally.made_up.nested_kql_field : x""")
| KEEP host.name, _id, _version, _index
'''
with pytest.raises(EsqlSchemaError, match="Unknown field"):
RuleCollection().load_dict(rule)
def test_eql_parse_hook_wired(self) -> None:
"""eql_parse hook is installed for nested EQL() (9.7+)."""
from detection_rules.rule import set_esql_config
cfg = set_esql_config("9.5.0")
assert callable(cfg.context.get("kql_parse"))
assert callable(cfg.context.get("eql_parse"))
# Hook accepts a simple event query.
tree = cfg.context["eql_parse"]('process where process.name == "cmd.exe"')
assert tree is not None
def test_set_esql_config_features_map_gates_kql(self) -> None:
"""set_esql_config must put a features dict that verify_features honors."""
import esql
from detection_rules.rule import set_esql_config
cfg = set_esql_config("8.14.0")
flags = cfg.context.get("features")
assert isinstance(flags, dict)
assert flags.get("kql_function") is False
with cfg, esql.Schema({}, allow_missing=True), pytest.raises(esql.EsqlVersionError, match=r"KQL\(\)"):
esql.parse_query('FROM logs-* | WHERE KQL("a:b") | KEEP _id')
cfg_ok = set_esql_config("8.15.0")
assert cfg_ok.context["features"]["kql_function"] is True
with cfg_ok, esql.Schema({}, allow_missing=True):
esql.parse_query('FROM logs-* | WHERE KQL("a:b") | KEEP _id')
def test_completion_query_requires_9_3_grammar(self) -> None:
"""Modern COMPLETION … WITH { } must fail on 8.19 and pass from 9.3."""
import esql
from detection_rules.rule import set_esql_config
query = """
FROM .alerts-security.* METADATA _id, _version, _index
| COMPLETION triage_result = "x" WITH { "inference_id": ".anthropic-claude-4.6-sonnet-completion"}
| KEEP triage_result, _id, _version, _index
"""
with set_esql_config("8.19.0"), esql.Schema({}, allow_missing=True), pytest.raises(esql.EsqlSyntaxError):
esql.parse_query(query)
with set_esql_config("9.3.0"), esql.Schema({}, allow_missing=True):
tree = esql.parse_query(query)
assert any(isinstance(c, esql.ast.CompletionCommand) for c in tree.commands)
def test_ast_reuse_across_same_grammar_targets(self) -> None:
"""validate() must reuse self.ast for the current-package grammar key."""
from detection_rules.rule_validators import ESQLValidator
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE process.name == "cmd.exe"
| KEEP process.name, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
validator = ESQLValidator(loaded.contents.data.query)
first = validator.ast
validator.validate(loaded.contents.data, loaded.contents.metadata)
# Older stack targets use older grammars. ast stays the current-package tree.
assert validator.ast is first
assert validator._parsed_tree is first # noqa: SLF001
def test_alert_index_kibana_alert_fields_pass(self) -> None:
rule = _sample_rule()
del rule["metadata"]["integration"]
rule["rule"]["query"] = """
FROM .alerts-security.* METADATA _id, _version, _index
| WHERE kibana.alert.rule.name IS NOT NULL AND kibana.alert.risk_score > 21
| KEEP kibana.alert.rule.name, kibana.alert.risk_score, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_grok_named_capture_field_passes(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["aws"]
rule["rule"]["query"] = """
FROM logs-aws.cloudtrail-* METADATA _id, _version, _index
| WHERE event.dataset == "aws.cloudtrail"
| GROK aws.cloudtrail.request_parameters "[Cc]ontent=(?<script_b64>[A-Za-z0-9+/=]+)"
| WHERE script_b64 IS NOT NULL
| KEEP script_b64, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert "script_b64" in loaded.contents.data.query
def test_unique_fields_without_min_stack_version(self) -> None:
"""rule-search and packaging must not fail on ES|QL rules with no min_stack_version."""
rule = _sample_rule()
rule["metadata"].pop("min_stack_version", None)
rule["metadata"].pop("min_stack_comments", None)
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE host.name == "workstation"
| KEEP host.name, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert "min_stack_version" not in loaded.contents.metadata.to_dict()
assert get_unique_query_fields(loaded) == ["host.name"]
def test_stack_subquery_field_on_its_own_index(self) -> None:
"""An alert field inside the .alerts-security.* subquery resolves there."""
rule = _sample_rule()
rule["metadata"].pop("integration", None)
rule["metadata"]["min_stack_version"] = "9.6.0"
rule["rule"]["query"] = """
FROM
(FROM .alerts-security.* | WHERE kibana.alert.rule.name == "x" | KEEP host.name),
(FROM auditbeat-* | KEEP host.name)
| STATS c = COUNT(*) BY host.name
| KEEP c, host.name
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_remote_only_multi_index_from_keeps_fields(self) -> None:
"""Per-index schemas match FROM patterns that carry a cluster prefix."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["rule"]["query"] = """
FROM remote:logs-endpoint.events.process-*, remote:logs-endpoint.events.network-* METADATA _id, _version, _index
| WHERE process.pid > 0
| KEEP host.name, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_remote_subquery_keeps_fields_and_isolation(self) -> None:
"""A remote subquery sees its own index fields and not a sibling's."""
rule = _sample_rule()
rule["metadata"].pop("integration", None)
rule["metadata"]["min_stack_version"] = "9.6.0"
rule["rule"]["query"] = """
FROM
(FROM remote:auditbeat-* | WHERE process.pid > 0 | KEEP host.name),
(FROM winlogbeat-* | KEEP host.name)
| STATS c = COUNT(*) BY host.name
| KEEP c, host.name
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
rule["rule"]["query"] = """
FROM
(FROM remote:.alerts-security.* | KEEP host.name),
(FROM remote:auditbeat-* | WHERE kibana.alert.rule.name == "x" | KEEP host.name)
| STATS c = COUNT(*) BY host.name
| KEEP c, host.name
"""
with pytest.raises(EsqlSchemaError, match=re.escape("kibana.alert.rule.name")):
RuleCollection().load_dict(rule)
class TestEsqlCorpusOffline:
"""Re-validate every production ES|QL rule offline (remote replacement path)."""
def test_all_production_esql_rules_validate_offline(self) -> None:
from detection_rules.rule_validators import ESQLValidator
collection = RuleCollection.default()
esql_rules = [r for r in collection.rules if getattr(r.contents.data, "language", None) == "esql"]
assert len(esql_rules) >= 200, f"expected a full ES|QL corpus, got {len(esql_rules)}"
failures: list[str] = []
for rule in esql_rules:
data = rule.contents.data
meta = rule.contents.metadata
name = str(getattr(rule, "path", None) or data.rule_id)
try:
ESQLValidator(data.query).validate(data, meta)
except Exception as exc: # noqa: BLE001 — collect all failures
failures.append(f"{name}: {type(exc).__name__}: {exc}")
assert not failures, "Offline ES|QL validation failures:\n" + "\n".join(failures[:40])
class TestEsqlSchemaHelpers:
def test_googlecloud_aliases_to_gcp(self) -> None:
assert normalize_dataset_package("googlecloud") == "gcp"
assert normalize_dataset_package("gcp") == "gcp"
def test_infer_packages_from_indices(self) -> None:
packages = infer_packages_from_indices(
["logs-aws.cloudtrail-*", "metrics-*", ".alerts-security.*", "logs-googlecloud.audit-*"]
)
assert "aws" in packages
assert "system" in packages
assert "gcp" in packages
assert ".alerts-security.*" not in packages
def test_index_patterns_match_overlapping_globs(self) -> None:
assert index_patterns_match("logs-*-foo", "logs-bar-*")
assert index_patterns_match("endgame-2026", "endgame-*")
assert index_patterns_match("logs-aws.cloudtrail-2026", "logs-aws.cloudtrail-*")
assert not index_patterns_match("logs-a-*", "logs-b-*")
assert not index_patterns_match("a*c", "*b")
def test_wildcard_non_ecs_fields_are_flattened(self) -> None:
"""A concrete index that overlaps a wildcard non-ECS row sees dotted fields."""
fields = collect_index_field_schemas(["endgame-2026"])
assert fields.get("endgame.event_subtype_full") == "keyword"
assert fields.get("endgame.metadata.type") == "keyword"
lookup_fields = collect_lookup_index_field_schemas(["endgame-2026"])["endgame-2026"]
assert lookup_fields.get("endgame.event_subtype_full") == "keyword"
assert lookup_fields.get("endgame.metadata.type") == "keyword"
def test_collect_index_field_schemas_includes_alert_fields(self) -> None:
fields = collect_index_field_schemas([".alerts-security.*"])
assert fields.get("kibana.alert.rule.name") == "keyword"
assert fields.get("kibana.alert.risk_score") == "long"
assert fields.get("kibana.alert.building_block_type") == "keyword"
assert fields.get("kibana.alert.rule.tags") == "keyword"
def test_auto_add_targets_subquery_from_index(self) -> None:
"""Auto-add picks the FROM pattern of the subquery that references the field."""
import esql
from detection_rules.config import load_current_package_version
from detection_rules.rule import set_esql_config
from detection_rules.rule_validators import ESQLValidator
query = """FROM (FROM logs-acme.app-* | KEEP host.name),
(FROM logs-acme.other-* | WHERE acme.other_field == "x" | KEEP host.name)
| STATS c = COUNT(*) BY host.name
| KEEP c, host.name"""
with set_esql_config(load_current_package_version()), esql.Schema({}, allow_missing=True):
tree = esql.parse_query(query)
err = EsqlSchemaError("Error at line:2,column:38\nUnknown field 'acme.other_field'")
assert ESQLValidator.from_index_for_field(tree, "acme.other_field", err) == "logs-acme.other-*"
# Fields only used after the subqueries merge have no FROM scope.
assert ESQLValidator.from_index_for_field(tree, "c", err) is None
class TestEsqlLookupJoin:
"""LOOKUP JOIN schemas are passed via Schema(lookups=), not dumped into FROM."""
def test_extract_lookup_targets(self) -> None:
query = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| LOOKUP JOIN logs-aws.cloudtrail-* ON host.name
| KEEP host.name, _id, _version, _index
"""
assert get_esql_lookup_join_targets(query) == ["logs-aws.cloudtrail-*"]
def test_lookup_index_uses_ecs_for_datastreams_not_named_tables(self) -> None:
assert lookup_index_uses_ecs("logs-aws.cloudtrail-*") is True
assert lookup_index_uses_ecs("threat_list") is False
def test_collect_lookup_index_field_schemas_does_not_dump_endpoint(self) -> None:
fields = collect_lookup_index_field_schemas(["logs-aws.cloudtrail-*"])
aws_fields = fields["logs-aws.cloudtrail-*"]
assert "aws.cloudtrail.flattened.request_parameters.key" in aws_fields
assert "process.Ext.api.name" not in aws_fields
def test_unknown_lookup_index_raises_offline(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "8.16.0"
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| LOOKUP JOIN totally-unknown-lookup-index ON host.name
| KEEP host.name, _id, _version, _index
"""
with pytest.raises(EsqlUnknownIndexError, match="totally-unknown-lookup-index"):
RuleCollection().load_dict(rule)
def test_lookup_join_fields_available_after_join(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "8.16.0"
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| LOOKUP JOIN logs-aws.cloudtrail-* ON host.name
| KEEP host.name, aws.cloudtrail.user_identity.type, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.data.language == "esql"
def test_lookup_join_fields_not_available_before_join(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "8.16.0"
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| WHERE aws.cloudtrail.user_identity.type == "IAMUser"
| LOOKUP JOIN logs-aws.cloudtrail-* ON host.name
| KEEP host.name, aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError, match=re.escape("aws.cloudtrail.user_identity.type")):
RuleCollection().load_dict(rule)
def test_lookup_join_does_not_add_lookup_package_to_from_schema(self) -> None:
"""LOOKUP JOIN must not mutate metadata.integration into extra FROM packages."""
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "8.16.0"
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| LOOKUP JOIN logs-aws.cloudtrail-* ON host.name
| KEEP host.name, aws.cloudtrail.user_identity.type, _id, _version, _index
"""
loaded = RuleCollection().load_dict(rule)
assert loaded.contents.metadata.integration == ["endpoint"]
def test_unknown_field_on_lookup_index_raises_schema_error(self) -> None:
rule = _sample_rule()
rule["metadata"]["integration"] = ["endpoint"]
rule["metadata"]["min_stack_version"] = "8.16.0"
rule["rule"]["query"] = """
FROM logs-endpoint.events.process-* METADATA _id, _version, _index
| LOOKUP JOIN logs-aws.cloudtrail-* ON host.name
| KEEP host.name, totally.made_up.lookup_field, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError, match=re.escape("totally.made_up.lookup_field")):
RuleCollection().load_dict(rule)