Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add logz.io security, audit trail and users tables (#114899)

Tom Owers3a1aedb76a44
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index b1d06fe73368..3e0de0899d3a 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -767,7 +767,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/loops/loops.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index d452e8b1bb40..8957fa67b5ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5273,14 +5273,14 @@ Diffed against: <https://raw.githubusercontent.com/lob/lob-openapi/main/lob-api-
## LogzIO — **thin**
-Today (5): `alerts`, `drop_filters`, `notification_endpoints`, `search_logs`, `triggered_alerts`
+Today (9): `alerts`, `audit_trail`, `drop_filters`, `notification_endpoints`, `search_logs`, `security_events`, `security_rules`, `triggered_alerts`, `users`
Diffed against: <https://docs.logz.io/docs/logz/logz-io-api>
-- [ ] `POST /v2/security/rules/events/search (Fetch security events)` — SIEM detection events — the main analytical output of the security product (high)
-- [ ] `POST /v2/security/rules/search (Retrieve security rules)` — lookup resolving the rule ids on every security event (high)
-- [ ] `GET/POST audit trail (Retrieve audit trail / List account audit trails)` — who changed what in the account, a standard warehouse audit dataset (high)
-- [ ] `GET /v1/user-management/users (Retrieve all users)` — lookup resolving user ids on alerts, audit rows and triggered alerts (high)
+- [x] `POST /v2/security/rules/events/search (Fetch security events)` — SIEM detection events — the main analytical output of the security product (`security_events`)
+- [x] `POST /v2/security/rules/search (Retrieve security rules)` — lookup resolving the rule ids on every security event (`security_rules`)
+- [x] `POST /v1/audit-trail (Retrieve a filtered list of audit trail events)` — who changed what in the account, a standard warehouse audit dataset (`audit_trail`)
+- [x] `GET /v1/user-management (Retrieve all users)` — lookup resolving user ids on alerts, audit rows and triggered alerts (`users`)
- [ ] `POST /v1/security/rules/events/logs/search (Logs that triggered a security event)` — drills a detection down to the underlying log lines (medium)
- [ ] `GET /v1/insights (Get the list of Insights)` — Cognitive Insights findings, an analytical product surface (medium)
- [ ] `POST lookup lists search + lookup list elements search` — literal lookup tables used to enrich logs and alerts (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.py
index b9e9476f900e..4d14e4c1f10f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.py
@@ -52,4 +52,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"active": "Whether the drop filter is currently applied.",
},
},
+ "security_events": {
+ "description": "Cloud SIEM security events, one row per time a security rule's conditions were met. Muted events are included.",
+ "docs_url": "https://api-docs.logz.io/docs/logz/search-security-rules-events",
+ "columns": {
+ "alertEventId": "Unique identifier of the security event.",
+ "alertId": "Identifier of the security rule that triggered the event. Joins to security_rules.id.",
+ "name": "Name of the security rule.",
+ "description": "Explanation of the rule's logic and suggested next steps.",
+ "alertSummary": "The rule's trigger condition.",
+ "eventDate": "When the event triggered, as a Unix timestamp in seconds.",
+ "alertWindowStartDate": "Unix timestamp in seconds of the earliest log that triggered the rule.",
+ "alertWindowEndDate": "Unix timestamp in seconds of the latest log that triggered the rule.",
+ "severity": "Severity of the event: INFO, LOW, MEDIUM, HIGH or SEVERE.",
+ "groupBy": "Field-value pairs the rule used to aggregate the triggering logs.",
+ "hits": "Number of logs that triggered the rule before aggregation.",
+ "isMuted": "Whether the event is muted.",
+ "mitreTags": "MITRE tags that classify the event.",
+ },
+ },
+ "security_rules": {
+ "description": "Cloud SIEM security rule definitions.",
+ "docs_url": "https://api-docs.logz.io/docs/logz/search-account-security-rules",
+ "columns": {
+ "id": "Unique identifier of the security rule.",
+ "title": "Rule title.",
+ "description": "Description of the event the rule detects and suggested next steps.",
+ "enabled": "Whether the rule is active.",
+ "createdAt": "When the rule was created, in UTC.",
+ "createdBy": "Email of the user who created the rule.",
+ "updatedAt": "When the rule was last updated, in UTC.",
+ "updatedBy": "Email of the user who last updated the rule.",
+ "tags": "Tags used to organize the rule.",
+ },
+ },
+ "audit_trail": {
+ "description": "Account audit trail, one row per recorded change or action by a user or API token.",
+ "docs_url": "https://api-docs.logz.io/docs/logz/list-account-audit-trails-filtered",
+ "columns": {
+ "audit_event_id": "Hash of the audit event's content. The API returns no event id, so PostHog derives one.",
+ "auditEventUser": "The user or API token that performed the action.",
+ "date": "When the event happened, as a Unix timestamp.",
+ "auditEventTypeTitle": "Type of the audit event.",
+ "ip": "IP address of the client that made the request.",
+ "geoLocation": "Geographic location of the client that made the request.",
+ "extraDataList": "Fields the event changed, with their old and new values.",
+ },
+ },
+ "users": {
+ "description": "Users of the Logz.io account that owns the API token.",
+ "docs_url": "https://api-docs.logz.io/docs/logz/list-users",
+ "columns": {
+ "id": "Unique identifier of the user.",
+ "username": "Email address the user signs in with.",
+ "fullName": "First and last name of the user.",
+ "accountID": "Logz.io account ID the user belongs to.",
+ "role": "User role: USER_ROLE_READONLY, USER_ROLE_REGULAR or USER_ROLE_ACCOUNT_ADMIN.",
+ "active": "Whether the user is active. False when the user is suspended.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py
index b27d66090389..0f9bac684789 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py
@@ -1,9 +1,11 @@
import json
+import hashlib
import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+import orjson
import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
@@ -22,8 +24,10 @@ REQUEST_TIMEOUT_SECONDS = 60
# Elasticsearch scroll page size. Logz.io caps a single search response and the scroll cursor walks
# the rest; 1000 balances round-trips against per-response memory.
SCROLL_PAGE_SIZE = 1000
-# Body-paginated list endpoints (triggered alerts, drop filters).
+# Body-paginated list endpoints (triggered alerts, drop filters, security rules and events).
PAGE_SIZE = 100
+# The audit trail caps `size` at 500.
+AUDIT_TRAIL_PAGE_SIZE = 500
# Hard cap on body-paginated pages per sync so a mis-terminating cursor can't scan unbounded.
MAX_PAGES = 10_000
# First incremental sync of logs backfills this many days. Logz.io retention is account-bounded, so
@@ -137,6 +141,45 @@ def _select(data: dict[str, Any] | list[dict[str, Any]], selector: str) -> list[
return value if isinstance(value, list) else []
+def _to_epoch_seconds(value: Any) -> int:
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ number = int(value)
+ # The audit trail documents Unix milliseconds but its example shows seconds, so a stored
+ # watermark can be either. No real event predates 1973, which is 1e11 milliseconds.
+ return number // 1000 if number >= 100_000_000_000 else number
+
+
+def _time_range_body(
+ config: LogzIOEndpointConfig, should_use_incremental_field: bool, db_incremental_field_last_value: Any
+) -> dict[str, Any]:
+ """Bound the request to events at or after the watermark, up to now, so page offsets stay stable."""
+ if not (config.incremental_fields and should_use_incremental_field and db_incremental_field_last_value):
+ return {}
+
+ from_seconds = _to_epoch_seconds(db_incremental_field_last_value)
+ to_seconds = int(datetime.now(UTC).timestamp())
+ if config.transport == "offset":
+ return {"fromDate": from_seconds * 1000, "toDate": to_seconds * 1000}
+ return {
+ "filter": {
+ **config.request_body.get("filter", {}),
+ "timeRange": {"fromDate": from_seconds, "toDate": to_seconds},
+ }
+ }
+
+
+def _with_hashed_id(rows: list[dict[str, Any]], key: str) -> list[dict[str, Any]]:
+ for row in rows:
+ row[key] = hashlib.md5(
+ orjson.dumps(row, option=orjson.OPT_SORT_KEYS, default=str), usedforsecurity=False
+ ).hexdigest()
+ return rows
+
+
def _parse_scroll_hits(response: dict[str, Any]) -> list[dict[str, Any]]:
"""Extract and flatten the log documents from a scroll response.
@@ -236,11 +279,12 @@ def _iter_paged_rows(
headers: dict[str, str],
logger: FilteringBoundLogger,
config: LogzIOEndpointConfig,
+ time_range: dict[str, Any],
) -> Iterator[list[dict[str, Any]]]:
url = f"{base_url}{config.path}"
page_number = 1
while page_number <= MAX_PAGES:
- body = {"pagination": {"pageNumber": page_number, "pageSize": PAGE_SIZE}}
+ body = {**config.request_body, **time_range, "pagination": {"pageNumber": page_number, "pageSize": PAGE_SIZE}}
data = _fetch(session, config.method, url, headers, logger, json_body=body)
rows = _select(data, config.data_selector)
if not rows:
@@ -255,6 +299,35 @@ def _iter_paged_rows(
logger.warning(f"Logz.io: hit page cap ({MAX_PAGES}) for {config.name}; stopping pagination")
+def _iter_offset_rows(
+ session: requests.Session,
+ base_url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: LogzIOEndpointConfig,
+ time_range: dict[str, Any],
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{base_url}{config.path}"
+ for page in range(MAX_PAGES):
+ body = {
+ **config.request_body,
+ **time_range,
+ "from": page * AUDIT_TRAIL_PAGE_SIZE,
+ "size": AUDIT_TRAIL_PAGE_SIZE,
+ }
+ data = _fetch(session, config.method, url, headers, logger, json_body=body)
+ rows = _select(data, config.data_selector)
+ if not rows:
+ break
+
+ yield rows
+
+ if len(rows) < AUDIT_TRAIL_PAGE_SIZE:
+ break
+ else:
+ logger.warning(f"Logz.io: hit page cap ({MAX_PAGES}) for {config.name}; stopping pagination")
+
+
def _iter_list_rows(
session: requests.Session,
base_url: str,
@@ -290,10 +363,18 @@ def get_rows(
if config.transport == "scroll":
query_body = _build_log_query(should_use_incremental_field, db_incremental_field_last_value, incremental_field)
yield from _iter_scroll_rows(session, base_url, headers, logger, resumable_source_manager, query_body)
- elif config.transport == "page":
- yield from _iter_paged_rows(session, base_url, headers, logger, config)
+ return
+
+ time_range = _time_range_body(config, should_use_incremental_field, db_incremental_field_last_value)
+ if config.transport == "page":
+ batches = _iter_paged_rows(session, base_url, headers, logger, config, time_range)
+ elif config.transport == "offset":
+ batches = _iter_offset_rows(session, base_url, headers, logger, config, time_range)
else:
- yield from _iter_list_rows(session, base_url, headers, logger, config)
+ batches = _iter_list_rows(session, base_url, headers, logger, config)
+
+ for rows in batches:
+ yield _with_hashed_id(rows, config.primary_keys[0]) if config.hash_primary_key else rows
def logz_io_source(
@@ -321,8 +402,8 @@ def logz_io_source(
incremental_field=incremental_field,
),
primary_keys=endpoint_config.primary_keys,
- # Logs are searched ascending on `@timestamp`; the definition/config endpoints aren't
- # incremental, so asc is a safe default there too.
+ # Logs, security events and the audit trail are requested ascending on their event time;
+ # the definition/config endpoints aren't incremental, so asc is a safe default there too.
sort_mode="asc",
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py
index 78b1bc451ba5..d2d46ad9e2ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import Literal, Optional
+from typing import Any, Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -18,7 +18,7 @@ REGION_BASE_URLS: dict[str, str] = {
DEFAULT_REGION = "us"
-@dataclass
+@dataclass(frozen=True)
class LogzIOEndpointConfig:
name: str
path: str
@@ -26,7 +26,8 @@ class LogzIOEndpointConfig:
# - "scroll": POST /v1/scroll, an Elasticsearch scroll cursor over log documents.
# - "list": a single GET returning a full array (small config/definition snapshots).
# - "page": POST with body-driven page-number pagination.
- transport: Literal["scroll", "list", "page"]
+ # - "offset": POST with body-driven `from`/`size` offset pagination (audit trail).
+ transport: Literal["scroll", "list", "page", "offset"]
method: Literal["GET", "POST"] = "GET"
# Dotted path to the array of rows in the JSON response (e.g. "results"). Empty means the
# response body is itself the array.
@@ -37,13 +38,19 @@ class LogzIOEndpointConfig:
partition_key: Optional[str] = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
should_sync_default: bool = True
+ # Static request body fields (sort order, filters) merged into every paginated request.
+ request_body: dict[str, Any] = field(default_factory=dict)
+ # Set when the API returns no row id: the single primary key column is then filled with a hash
+ # of the row content.
+ hash_primary_key: bool = False
# Only `search_logs` has a genuine server-side time filter: the Elasticsearch DSL `range` query on
# `@timestamp` IS the query, so a mapped `db_incremental_field_last_value` is honored by construction
# (an ignored range filter would break search entirely). The definition/config endpoints
# (alerts, notification_endpoints, drop_filters) return small full-array snapshots with no
-# updated-since filter, so they ship full refresh only.
+# updated-since filter, so they ship full refresh only. `security_events` and `audit_trail` also take a
+# server-side time range on their event timestamp, so they sync incrementally too.
LOGZIO_ENDPOINTS: dict[str, LogzIOEndpointConfig] = {
"search_logs": LogzIOEndpointConfig(
name="search_logs",
@@ -96,6 +103,67 @@ LOGZIO_ENDPOINTS: dict[str, LogzIOEndpointConfig] = {
data_selector="results",
should_sync_default=False,
),
+ # The security endpoints need an API token from a Logz.io Cloud SIEM (security) account.
+ "security_events": LogzIOEndpointConfig(
+ name="security_events",
+ path="/v2/security/rules/events/search",
+ transport="page",
+ method="POST",
+ data_selector="results",
+ primary_keys=["alertEventId"],
+ # Unix seconds of when the rule triggered. Partitioning reads integer keys as Unix seconds.
+ partition_key="eventDate",
+ incremental_fields=[
+ {
+ "label": "eventDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "eventDate",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ request_body={
+ "filter": {"includeMutedEvents": True},
+ "sort": [{"field": "DATE", "descending": False}],
+ },
+ should_sync_default=False,
+ ),
+ "security_rules": LogzIOEndpointConfig(
+ name="security_rules",
+ path="/v2/security/rules/search",
+ transport="page",
+ method="POST",
+ data_selector="results",
+ partition_key="createdAt",
+ request_body={"sort": {"sortByField": "createdAt", "descending": False}},
+ should_sync_default=False,
+ ),
+ "audit_trail": LogzIOEndpointConfig(
+ name="audit_trail",
+ path="/v1/audit-trail",
+ transport="offset",
+ method="POST",
+ data_selector="results",
+ # Audit events carry no id, and `date` is documented as Unix milliseconds, so it can't be a
+ # datetime partition key (integer keys are read as Unix seconds).
+ primary_keys=["audit_event_id"],
+ hash_primary_key=True,
+ incremental_fields=[
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ request_body={"sortDescending": False, "includeFiltersData": False},
+ should_sync_default=False,
+ ),
+ "users": LogzIOEndpointConfig(
+ name="users",
+ path="/v1/user-management",
+ transport="list",
+ method="GET",
+ ),
}
ENDPOINTS = tuple(LOGZIO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.py
index fbd5a2ca600f..dc7ae2dc98bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.py
@@ -3,6 +3,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
+import time_machine
from unittest import mock
import requests
@@ -174,6 +175,90 @@ class TestPagedEndpoints:
assert list(get_rows("token", "us", "triggered_alerts", mock.MagicMock(), manager)) == []
+class TestOffsetEndpoints:
+ @mock.patch(f"{TRANSPORT}.make_tracked_session")
+ def test_audit_trail_walks_offsets_and_derives_distinct_ids(self, mock_session: mock.MagicMock) -> None:
+ full_page = [{"date": 1_700_000_000_000 + i, "auditEventTypeTitle": "Login"} for i in range(500)]
+ mock_session.return_value.request.side_effect = [
+ _resp({"results": full_page}),
+ _resp({"results": [{"date": 1_700_000_001_000, "auditEventTypeTitle": "Login"}]}),
+ ]
+
+ manager = _make_manager()
+ rows = [r for batch in get_rows("token", "us", "audit_trail", mock.MagicMock(), manager) for r in batch]
+
+ assert len({r["audit_event_id"] for r in rows}) == 501
+ offsets = [c.kwargs["json"]["from"] for c in mock_session.return_value.request.call_args_list]
+ assert offsets == [0, 500]
+
+
+class TestIncrementalRequestShaping:
+ @pytest.mark.parametrize(
+ "endpoint, use_incremental, last_value, expected_fields",
+ [
+ (
+ "security_events",
+ True,
+ 1_780_000_000,
+ {
+ "filter": {
+ "includeMutedEvents": True,
+ "timeRange": {"fromDate": 1_780_000_000, "toDate": 1_790_000_000},
+ },
+ "sort": [{"field": "DATE", "descending": False}],
+ },
+ ),
+ (
+ "security_events",
+ False,
+ None,
+ {"filter": {"includeMutedEvents": True}, "sort": [{"field": "DATE", "descending": False}]},
+ ),
+ (
+ "audit_trail",
+ True,
+ 1_780_000_000_000,
+ {"fromDate": 1_780_000_000_000, "toDate": 1_790_000_000_000, "sortDescending": False},
+ ),
+ # A watermark stored in seconds still reaches the API in milliseconds.
+ (
+ "audit_trail",
+ True,
+ 1_780_000_000,
+ {"fromDate": 1_780_000_000_000, "toDate": 1_790_000_000_000, "sortDescending": False},
+ ),
+ ],
+ )
+ @time_machine.travel(datetime.fromtimestamp(1_790_000_000, tz=UTC), tick=False)
+ @mock.patch(f"{TRANSPORT}.make_tracked_session")
+ def test_time_range_in_request_body(
+ self,
+ mock_session: mock.MagicMock,
+ endpoint: str,
+ use_incremental: bool,
+ last_value: int | None,
+ expected_fields: dict[str, Any],
+ ) -> None:
+ mock_session.return_value.request.return_value = _resp({"results": []})
+ manager = _make_manager()
+ list(
+ get_rows(
+ "token",
+ "us",
+ endpoint,
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ body = mock_session.return_value.request.call_args.kwargs["json"]
+ assert {key: body.get(key) for key in expected_fields} == expected_fields
+ if not use_incremental:
+ assert "timeRange" not in body["filter"]
+
+
class TestListEndpoints:
@mock.patch(f"{TRANSPORT}.make_tracked_session")
def test_bare_array_response_is_yielded(self, mock_session: mock.MagicMock) -> None: