pySigma-backend-sqlite 2.2.0__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pySigma-backend-sqlite
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: pySigma sqlite backend
5
5
  License-Expression: LGPL-3.0-only
6
6
  License-File: LICENSE
@@ -12,7 +12,7 @@ Classifier: Programming Language :: Python :: 3.12
12
12
  Classifier: Programming Language :: Python :: 3.13
13
13
  Classifier: Programming Language :: Python :: 3.14
14
14
  Classifier: Programming Language :: Python :: 3.15
15
- Requires-Dist: pysigma (>=2.1.0,<3.0)
15
+ Requires-Dist: pysigma (>=2.1.2,<3.0)
16
16
  Project-URL: Repository, https://github.com/SigmaHQ/pySigma-backend-sqlite
17
17
  Description-Content-Type: text/markdown
18
18
 
@@ -35,7 +35,7 @@ Maintained by [wagga](https://github.com/wagga40/).
35
35
  pip install pysigma-backend-sqlite
36
36
  ```
37
37
 
38
- Requires Python 3.11+ and [pySigma](https://github.com/SigmaHQ/pySigma) 2.1.0 or
38
+ Requires Python 3.11+ and [pySigma](https://github.com/SigmaHQ/pySigma) 2.1.2 or
39
39
  newer within the 2.x series. Correlation output needs SQLite 3.38 or newer. Use sigma-cli 4.0 or newer:
40
40
  sigma-cli 3.x requires pySigma 1.x, so alongside it pip installs backend 2.0.0,
41
41
  which has no keyword search.
@@ -98,6 +98,7 @@ option produces a warning so you can check which setting took effect.
98
98
  | `prefilter_bounds` | `true` | Emit Channel/EventID allow-lists for Zircolite storage. Set to `false` for custom collations or event ID coercions |
99
99
  | `text_mode` | `portable` | Use `unicode` for Unicode case folding in detections, grouping and distinct counts |
100
100
  | `presence_field` | none | JSON array column listing the flattened fields present in each source event |
101
+ | `presence_representation` | `field-names-v1` | Use `null-field-names-v1` when `presence_field` lists only the fields stored as NULL |
101
102
  | `sum_mode` | `portable` | Use `exact` to preserve integer window totals beyond SQLite's signed 64-bit range |
102
103
  | `week_mode` | `iso` | ISO week of year (1–53). Use `legacy` for SQLite's Monday-based week 0–53 |
103
104
  | `modifier_mode` | `sigma` | `windash` expands every dash position and `re\|startswith`/`re\|endswith` stay within the field. Use `pysigma` for pySigma's own expansion, as in 2.1 |
@@ -207,7 +208,7 @@ searchable text. See [keyword search](https://github.com/wagga40/pySigma-backend
207
208
  - **Case folding.** Stock BINARY columns compare literal text case-sensitively. SQLite NOCASE columns or `collate_nocase=True` cover ASCII. Set `text_mode="unicode"` and register the runtime helpers for Unicode equality, wildcards, field comparisons and keywords.
208
209
  - **Timestamp parts** use `strftime()` and need ISO-8601 text; a numeric epoch is
209
210
  read as a Julian day. ISO week 53 occurs in some years. Only `week_mode="legacy"` can produce week 0.
210
- - **Field existence.** With `presence_field`, `exists` includes an explicitly null field. The default uses SQL NULL as a proxy for absence.
211
+ - **Field existence.** The default uses SQL NULL as a proxy for absence. With `presence_field`, `exists` also counts an explicitly null field. The column lists every field of the source event, or only the fields stored as NULL with `presence_representation="null-field-names-v1"`. That mode reads the field's own column first and matches listed names ASCII case-insensitively.
211
212
  - **Multi-field `value_count`** counts distinct complete tuples in each window. A NULL component excludes that tuple from the count.
212
213
  - **Unknown columns.** A query naming a column the table lacks fails to prepare.
213
214
  Add missing columns as `NULL` first; see [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md).
@@ -17,7 +17,7 @@ Maintained by [wagga](https://github.com/wagga40/).
17
17
  pip install pysigma-backend-sqlite
18
18
  ```
19
19
 
20
- Requires Python 3.11+ and [pySigma](https://github.com/SigmaHQ/pySigma) 2.1.0 or
20
+ Requires Python 3.11+ and [pySigma](https://github.com/SigmaHQ/pySigma) 2.1.2 or
21
21
  newer within the 2.x series. Correlation output needs SQLite 3.38 or newer. Use sigma-cli 4.0 or newer:
22
22
  sigma-cli 3.x requires pySigma 1.x, so alongside it pip installs backend 2.0.0,
23
23
  which has no keyword search.
@@ -80,6 +80,7 @@ option produces a warning so you can check which setting took effect.
80
80
  | `prefilter_bounds` | `true` | Emit Channel/EventID allow-lists for Zircolite storage. Set to `false` for custom collations or event ID coercions |
81
81
  | `text_mode` | `portable` | Use `unicode` for Unicode case folding in detections, grouping and distinct counts |
82
82
  | `presence_field` | none | JSON array column listing the flattened fields present in each source event |
83
+ | `presence_representation` | `field-names-v1` | Use `null-field-names-v1` when `presence_field` lists only the fields stored as NULL |
83
84
  | `sum_mode` | `portable` | Use `exact` to preserve integer window totals beyond SQLite's signed 64-bit range |
84
85
  | `week_mode` | `iso` | ISO week of year (1–53). Use `legacy` for SQLite's Monday-based week 0–53 |
85
86
  | `modifier_mode` | `sigma` | `windash` expands every dash position and `re\|startswith`/`re\|endswith` stay within the field. Use `pysigma` for pySigma's own expansion, as in 2.1 |
@@ -189,7 +190,7 @@ searchable text. See [keyword search](https://github.com/wagga40/pySigma-backend
189
190
  - **Case folding.** Stock BINARY columns compare literal text case-sensitively. SQLite NOCASE columns or `collate_nocase=True` cover ASCII. Set `text_mode="unicode"` and register the runtime helpers for Unicode equality, wildcards, field comparisons and keywords.
190
191
  - **Timestamp parts** use `strftime()` and need ISO-8601 text; a numeric epoch is
191
192
  read as a Julian day. ISO week 53 occurs in some years. Only `week_mode="legacy"` can produce week 0.
192
- - **Field existence.** With `presence_field`, `exists` includes an explicitly null field. The default uses SQL NULL as a proxy for absence.
193
+ - **Field existence.** The default uses SQL NULL as a proxy for absence. With `presence_field`, `exists` also counts an explicitly null field. The column lists every field of the source event, or only the fields stored as NULL with `presence_representation="null-field-names-v1"`. That mode reads the field's own column first and matches listed names ASCII case-insensitively.
193
194
  - **Multi-field `value_count`** counts distinct complete tuples in each window. A NULL component excludes that tuple from the count.
194
195
  - **Unknown columns.** A query naming a column the table lacks fails to prepare.
195
196
  Add missing columns as `NULL` first; see [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md).
@@ -1,8 +1,8 @@
1
1
  [project]
2
2
  name = "pySigma-backend-sqlite"
3
- version = "2.2.0"
3
+ version = "2.3.0"
4
4
  requires-python = ">=3.11,<4.0"
5
- dependencies = ["pysigma>=2.1.0,<3.0"]
5
+ dependencies = ["pysigma>=2.1.2,<3.0"]
6
6
  description = "pySigma sqlite backend"
7
7
  readme = "README.md"
8
8
  authors = [
@@ -16,7 +16,7 @@ from .correlation import (
16
16
  quote,
17
17
  restore_text,
18
18
  )
19
- from .strict import PRESENCE_REPRESENTATION
19
+ from .strict import NULL_PRESENCE_REPRESENTATION, PRESENCE_REPRESENTATIONS
20
20
  from .strict import register_sqlite_functions as register_sqlite_functions
21
21
 
22
22
  _NAME = rf"(?:{BARE_NAME}|`(?:[^`]|``)+`)"
@@ -122,9 +122,13 @@ def validate_fulltext(connection, requirements):
122
122
 
123
123
 
124
124
  def validate_presence(connection, requirements):
125
- """Check every source row carries a JSON array of mapped field names before widening."""
125
+ """Check every source row carries a JSON array of mapped field names before widening.
126
+
127
+ In null-field-names-v1, a NULL row is an empty list.
128
+ """
126
129
  if not isinstance(requirements, list) or not requirements:
127
130
  raise ValueError("Invalid presence requirements")
131
+ representations = {}
128
132
  for item in requirements:
129
133
  if (
130
134
  not isinstance(item, dict)
@@ -134,10 +138,20 @@ def validate_presence(connection, requirements):
134
138
  or not isinstance(item["field"], str)
135
139
  or not item["field"]
136
140
  or "\x00" in item["field"]
137
- or item["representation"] != PRESENCE_REPRESENTATION
141
+ or item["representation"] not in PRESENCE_REPRESENTATIONS
138
142
  ):
139
143
  raise ValueError("Invalid presence requirement")
144
+ name = (_identifier(item["table"]), _identifier(item["field"]))
145
+ if (
146
+ representations.setdefault(name, item["representation"])
147
+ != item["representation"]
148
+ ):
149
+ raise ValueError(
150
+ f"Conflicting presence representations for {item['table']}.{item['field']}"
151
+ )
152
+ for item in requirements:
140
153
  table, field = item["table"], item["field"]
154
+ nullable = item["representation"] == NULL_PRESENCE_REPRESENTATION
141
155
  try:
142
156
  if _identifier(field) not in _columns(connection, table):
143
157
  raise ValueError(
@@ -145,12 +159,17 @@ def validate_presence(connection, requirements):
145
159
  )
146
160
  column = quote(field)
147
161
  cursor = connection.execute(
148
- f"SELECT CASE WHEN typeof({column})='text' THEN {column} END FROM {table}"
162
+ f"SELECT {column} IS NULL, "
163
+ f"CASE WHEN typeof({column})='text' THEN {column} END FROM {table}"
149
164
  )
150
165
  try:
151
- for (source,) in cursor:
166
+ for null, source in cursor:
167
+ if null and nullable:
168
+ continue
152
169
  if source is None:
153
- raise ValueError("expected TEXT")
170
+ raise ValueError(
171
+ "expected TEXT" + (" or NULL" if nullable else "")
172
+ )
154
173
  keys = json.loads(_result_text(source))
155
174
  if not isinstance(keys, list) or any(
156
175
  not isinstance(key, str) or not key or "\x00" in key
@@ -53,7 +53,15 @@ from .correlation import (
53
53
  quote,
54
54
  )
55
55
  from .modifiers import BoundedRegex, SQLiteModifiers
56
- from .strict import PRESENCE_REPRESENTATION
56
+ from .strict import (
57
+ NULL_PRESENCE_REPRESENTATION,
58
+ PRESENCE_REPRESENTATION,
59
+ PRESENCE_REPRESENTATIONS,
60
+ )
61
+
62
+ _PRESENCE_REPRESENTATION_ERROR = (
63
+ f"presence_representation must be {' or '.join(PRESENCE_REPRESENTATIONS)}"
64
+ )
57
65
 
58
66
  _SQLITE_KEYWORDS = set(
59
67
  "ABORT ACTION ADD AFTER ALL ALTER ALWAYS ANALYZE AND AS ASC ATTACH AUTOINCREMENT BEFORE BEGIN BETWEEN BY CASCADE CASE CAST CHECK COLLATE COLUMN COMMIT CONFLICT CONSTRAINT CREATE CROSS CURRENT CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP DATABASE DEFAULT DEFERRABLE DEFERRED DELETE DESC DETACH DISTINCT DO DROP EACH ELSE END ESCAPE EXCEPT EXCLUDE EXCLUSIVE EXISTS EXPLAIN FAIL FILTER FIRST FOLLOWING FOR FOREIGN FROM FULL GENERATED GLOB GROUP GROUPS HAVING IF IGNORE IMMEDIATE IN INDEX INDEXED INITIALLY INNER INSERT INSTEAD INTERSECT INTO IS ISNULL JOIN KEY LAST LEFT LIKE LIMIT MATCH MATERIALIZED NATURAL NO NOT NOTHING NOTNULL NULL NULLS OF OFFSET ON OR ORDER OTHERS OUTER OVER PARTITION PLAN PRAGMA PRECEDING PRIMARY QUERY RAISE RANGE RECURSIVE REFERENCES REGEXP REINDEX RELEASE RENAME REPLACE RESTRICT RETURNING RIGHT ROLLBACK ROW ROWS SAVEPOINT SELECT SET TABLE TEMP TEMPORARY THEN TIES TO TRANSACTION TRIGGER UNBOUNDED UNION UNIQUE UPDATE USING VACUUM VALUES VIEW VIRTUAL WHEN WHERE WINDOW WITH WITHOUT".split()
@@ -253,6 +261,7 @@ class sqliteBackend(TextQueryBackend):
253
261
  text_mode = "portable"
254
262
  sum_mode = "portable"
255
263
  presence_field: str | None = None
264
+ presence_representation = PRESENCE_REPRESENTATION
256
265
  fulltext_field: str | None = None
257
266
  timestamp_seconds_expression = (
258
267
  "ROUND((julianday({field}) - 2440587.5) * 86400000) / 1000.0"
@@ -280,6 +289,7 @@ class sqliteBackend(TextQueryBackend):
280
289
  "text_mode",
281
290
  "sum_mode",
282
291
  "presence_field",
292
+ "presence_representation",
283
293
  }
284
294
  for key in options.keys() - configurable:
285
295
  close = get_close_matches(key, configurable, n=1, cutoff=0.8)
@@ -312,6 +322,8 @@ class sqliteBackend(TextQueryBackend):
312
322
  # Skip the replay of windash and re|startswith/endswith. pySigma's own
313
323
  # expansion then stands, as in 2.1 releases of this backend.
314
324
  self.backend_processing_pipeline = ProcessingPipeline()
325
+ if self.presence_representation not in PRESENCE_REPRESENTATIONS:
326
+ raise ValueError(_PRESENCE_REPRESENTATION_ERROR)
315
327
  if self.text_mode not in ("portable", "unicode"):
316
328
  raise ValueError("text_mode must be portable or unicode")
317
329
  if self.sum_mode not in ("portable", "exact"):
@@ -358,10 +370,18 @@ class sqliteBackend(TextQueryBackend):
358
370
  )
359
371
  return field
360
372
 
373
+ def resolve_presence_representation(self, processing_state):
374
+ representation = (processing_state or {}).get(
375
+ "presence_representation", self.presence_representation
376
+ )
377
+ if representation not in PRESENCE_REPRESENTATIONS:
378
+ raise SigmaFeatureNotSupportedByBackendError(_PRESENCE_REPRESENTATION_ERROR)
379
+ return representation
380
+
361
381
  def execution_contract(self, states, *, fulltext=False, extra_functions=()):
362
382
  """Derive the smallest supported schema for these retained predicates and stages."""
363
383
  functions = set(extra_functions)
364
- presence = set()
384
+ presence = {}
365
385
  uses_regex = False
366
386
  strict = (
367
387
  self.text_mode == "unicode"
@@ -377,7 +397,16 @@ class sqliteBackend(TextQueryBackend):
377
397
  strict |= getattr(state, "sqlite_strict_regex", False)
378
398
  source = getattr(state, "sqlite_presence_source", None)
379
399
  if source is not None:
380
- presence.add(source)
400
+ table, field, representation = source
401
+ if (
402
+ presence.setdefault((table, field), representation)
403
+ != representation
404
+ ):
405
+ raise SigmaFeatureNotSupportedByBackendError(
406
+ f"Presence column {field!r} of {table} is read with both "
407
+ f"{PRESENCE_REPRESENTATION} and {NULL_PRESENCE_REPRESENTATION}; "
408
+ "use one presence_representation per column"
409
+ )
381
410
  if uses_regex and (strict or presence or functions - {CIDR_FUNCTION}):
382
411
  functions.add("regexp")
383
412
  contract = {"version": 3 if fulltext else 2}
@@ -387,12 +416,8 @@ class sqliteBackend(TextQueryBackend):
387
416
  if presence:
388
417
  contract["version"] = 5
389
418
  contract["presence"] = [
390
- {
391
- "table": table,
392
- "field": field,
393
- "representation": PRESENCE_REPRESENTATION,
394
- }
395
- for table, field in sorted(presence)
419
+ {"table": table, "field": field, "representation": representation}
420
+ for (table, field), representation in sorted(presence.items())
396
421
  ]
397
422
  return contract
398
423
 
@@ -407,35 +432,56 @@ class sqliteBackend(TextQueryBackend):
407
432
  field = self.resolve_presence_field(state.processing_state)
408
433
  if field is None:
409
434
  return super().convert_condition_field_eq_val_exists(cond, state)
435
+ representation = self.resolve_presence_representation(state.processing_state)
410
436
  table = self.resolve_table(state.processing_state)
411
- state.sqlite_presence_source = (table, field)
412
- # Read the validated array with scalar functions. Tables elsewhere on the
413
- # connection may shadow either of SQLite's JSON virtual tables.
414
- source = f"{table}.{quote(field)}"
437
+ state.sqlite_presence_source = (table, field, representation)
415
438
  table_name = (
416
439
  (state.processing_state.get("table") or self.table)
417
440
  .rsplit(".", 1)[-1]
418
441
  .lower()
419
442
  )
420
443
  alias = "field_names" if table_name == "presence_keys" else "presence_keys"
421
- negation = "" if cond.value.exists else "NOT "
444
+ source = f"{table}.{quote(field)}"
445
+ if representation == PRESENCE_REPRESENTATION:
446
+ negation = "" if cond.value.exists else "NOT "
447
+ return negation + self._presence_lookup(source, alias, cond.field)
448
+ # The array lists only fields the source carried as null. Every other
449
+ # present field has a value in its own column.
450
+ lookup = self._presence_lookup(source, alias, cond.field, nocase=True)
451
+ column = self.escape_and_quote_field(cond.field)
452
+ if cond.value.exists:
453
+ return f"({self.field_exists_expression.format(field=column)} OR {lookup})"
454
+ # A NULL array lists nothing. COALESCE keeps NOT from turning it into NULL.
455
+ absent = self.field_not_exists_expression.format(field=column)
456
+ return f"({absent} AND NOT {self.null_safe_expression.format(expr=lookup)})"
457
+
458
+ @staticmethod
459
+ def _presence_lookup(source, alias, name, nocase=False):
460
+ """True when the JSON array in source lists name, as BINARY or ASCII NOCASE text."""
461
+ # Read the validated array with scalar functions. Tables elsewhere on the
462
+ # connection may shadow either of SQLite's JSON virtual tables.
422
463
  walk = (
423
464
  f"EXISTS (WITH RECURSIVE {alias}(i, key) AS ("
424
465
  f"SELECT 0, json_extract({source}, '$[0]') UNION ALL "
425
466
  f"SELECT i+1, json_extract({source}, '$[' || (i+1) || ']') "
426
467
  f"FROM {alias} WHERE key IS NOT NULL) "
427
- f"SELECT 1 FROM {alias} WHERE key = {literal(cond.field)} COLLATE BINARY)"
468
+ f"SELECT 1 FROM {alias} WHERE key = {literal(name)} "
469
+ f"COLLATE {'NOCASE' if nocase else 'BINARY'})"
428
470
  )
429
- if not set(cond.field) - {" ", ","}:
471
+ if not set(name) - {" ", ","}:
430
472
  # Such a name could span the separator between two elements.
431
- return negation + walk
473
+ return walk
432
474
  # Each extraction re-reads the array from its start. Without a backslash,
433
475
  # every quote in the validated array delimits an element, so the quoted
434
476
  # name occurs exactly when one element equals it.
435
- name = literal(json.dumps(cond.field, ensure_ascii=False))
477
+ haystack, needle = source, literal(json.dumps(name, ensure_ascii=False))
478
+ if nocase:
479
+ # Stock lower() folds ASCII only, as NOCASE and SQLite's column-name
480
+ # resolution do. Folding both sides keeps the two paths in agreement.
481
+ haystack, needle = f"lower({source})", f"lower({needle})"
436
482
  return (
437
- f"{negation}(CASE WHEN instr({source}, '\\') = 0 "
438
- f"THEN instr({source}, {name}) > 0 ELSE {walk} END)"
483
+ f"(CASE WHEN instr({source}, '\\') = 0 "
484
+ f"THEN instr({haystack}, {needle}) > 0 ELSE {walk} END)"
439
485
  )
440
486
 
441
487
  @staticmethod
@@ -513,7 +559,12 @@ class sqliteBackend(TextQueryBackend):
513
559
  presence = self.resolve_presence_field(state.processing_state)
514
560
  if presence is not None:
515
561
  fields.add(presence)
516
- continue
562
+ representation = self.resolve_presence_representation(
563
+ state.processing_state
564
+ )
565
+ # Only the null-name list leaves present values to the column.
566
+ if representation == PRESENCE_REPRESENTATION:
567
+ continue
517
568
  if cond.field:
518
569
  fields.add(cond.field)
519
570
  if isinstance(cond.value, SigmaFieldReference):
@@ -11,7 +11,10 @@ from itertools import accumulate
11
11
 
12
12
  from .cidr import register_cidr
13
13
 
14
+ # Every field the source event carried, or only those it carried as null.
14
15
  PRESENCE_REPRESENTATION = "field-names-v1"
16
+ NULL_PRESENCE_REPRESENTATION = "null-field-names-v1"
17
+ PRESENCE_REPRESENTATIONS = (PRESENCE_REPRESENTATION, NULL_PRESENCE_REPRESENTATION)
15
18
 
16
19
 
17
20
  @lru_cache(maxsize=1024)