: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add lacework inventory, entity, account and policy tables (#113900)
Tom Owers7609433b443d
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.mdindex 4a47eb4a1e5d..e66b8fc7ebb2 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@@ -4921,14 +4921,14 @@ Note: Kustomer's ReadMe-hosted reference blocks machine-readable spec fetches (s## Lacework — gaps-Today (10): `agent_info`, `alerts`, `audit_logs`, `compliance_evaluations_aws`, `compliance_evaluations_azure`, `compliance_evaluations_gcp`, `compliance_evaluations_k8s`, `entities_machines`, `vulnerabilities_containers`, `vulnerabilities_hosts`+Today (17): `agent_info`, `alerts`, `audit_logs`, `cloud_accounts`, `compliance_evaluations_aws`, `compliance_evaluations_azure`, `compliance_evaluations_gcp`, `compliance_evaluations_k8s`, `entities_containers`, `entities_images`, `entities_machines`, `inventory_aws`, `inventory_azure`, `inventory_gcp`, `policies`, `vulnerabilities_containers`, `vulnerabilities_hosts`Diffed against: <https://api.lacework.net/api/v2/docs/lacework-api-v2.0.yaml>-- [ ] `GET /api/v2/Policies (and /Policies/search)` — lookup resolving the policyId carried on every synced alert and compliance evaluation (high)-- [ ] `POST /api/v2/Inventory/search` — the full cloud resource inventory that compliance evaluations are scored against (high)-- [ ] `POST /api/v2/Entities/Containers/search and /Entities/Images/search` — container and image inventory needed to join vulnerabilities_containers back to running workloads (high)-- [ ] `GET /api/v2/CloudAccounts (and /CloudAccounts/search)` — lookup resolving cloud account ids on aws/azure/gcp compliance evaluations (high)+- [x] `GET /api/v2/Policies (and /Policies/search)` — lookup resolving the policyId carried on every synced alert and compliance evaluation (high)+- [x] `POST /api/v2/Inventory/search` — the full cloud resource inventory that compliance evaluations are scored against (high)+- [x] `POST /api/v2/Entities/Containers/search and /Entities/Images/search` — container and image inventory needed to join vulnerabilities_containers back to running workloads (high)+- [x] `GET /api/v2/CloudAccounts (and /CloudAccounts/search)` — lookup resolving cloud account ids on aws/azure/gcp compliance evaluations (high)- [ ] `POST /api/v2/CloudActivities/search` — cloud control-plane activity trail, the main behavioral dataset alongside alerts (medium)- [ ] `POST /api/v2/Entities/Packages/search` — installed package inventory that vulnerability findings reference (medium)- [ ] `POST /api/v2/Activities/UserLogins/search` — login activity for identity-risk analysis (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/canonical_descriptions.pyindex 08fb63c4965c..26a6b024b762 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/canonical_descriptions.py@@ -26,6 +26,31 @@ def _compliance_entry(provider: str) -> CanonicalEndpoint:}+_INVENTORY_COLUMNS = {+ "startTime": "When the hourly aggregation period of the collection run started.",+ "endTime": "When the hourly aggregation period of the collection run ended.",+ "urn": "The URN of the resource.",+ "service": "The cloud service the resource belongs to.",+ "status": "The status of the resource.",+ "cloudDetails": "Details of the cloud account or project that owns the resource.",+ "resourceType": "The resource type.",+ "resourceId": "The identifier of the resource.",+ "resourceRegion": "The region the resource belongs to.",+ "resourceConfig": "The configuration of the resource.",+ "resourceTags": "The tags on the resource.",+ "csp": "The cloud provider.",+ "apiKey": "The cloud API call used to collect the resource.",+}+++def _inventory_entry(provider: str) -> CanonicalEndpoint:+ return {+ "description": f"{provider} cloud resource inventory: one row per resource per collection run. Compliance evaluations are scored against these resources.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Inventory",+ "columns": _INVENTORY_COLUMNS,+ }++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"alerts": {"description": "Alerts raised by Lacework FortiCNAPP for potential threats, anomalies, and policy violations across your cloud environments.",@@ -134,4 +159,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"entityType": "The entity type (Machine).",},},+ "entities_containers": {+ "description": "Containers active in your environment: one row per container per hourly aggregation window.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Entities",+ "columns": {+ "startTime": "When the hourly aggregation window started.",+ "endTime": "When the hourly aggregation window ended.",+ "mid": "The identifier of the machine the container runs on.",+ "containerName": "The name of the container.",+ "podName": "The name of the Kubernetes pod the container belongs to.",+ "imageId": "The identifier of the container image. Joins to vulnerabilities_containers and entities_images.",+ "propsContainer": "Properties of the container, such as image repository and tag.",+ "tags": "Tags of the container.",+ },+ },+ "entities_images": {+ "description": "Container images in your environment: one row per image per machine.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Entities",+ "columns": {+ "createdTime": "When the container was created.",+ "mid": "The identifier of the machine the image is on.",+ "imageId": "The identifier of the container image.",+ "repo": "The repository of the image.",+ "tag": "The tag of the image.",+ "size": "The size of the image in bytes.",+ "containerType": "The container runtime type.",+ },+ },+ "inventory_aws": _inventory_entry("AWS"),+ "inventory_azure": _inventory_entry("Azure"),+ "inventory_gcp": _inventory_entry("GCP"),+ "cloud_accounts": {+ "description": "Cloud account integrations configured in Lacework FortiCNAPP. Credentials are removed from the data column.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/CloudAccounts",+ "columns": {+ "intgGuid": "Unique identifier for the integration.",+ "name": "The name of the integration.",+ "type": "The integration type, such as AwsCfg or AzureCfg.",+ "enabled": "1 if the integration is enabled, 0 if it is disabled.",+ "state": "The current state of the integration, such as whether the last check succeeded.",+ "cloudId": "The cloud account identifier.",+ "cloudIdType": "The type of cloud account identifier, such as AWS_ACCOUNT_ID or GCP_PROJECT_ID.",+ "data": "The integration's configuration, without credentials.",+ "isOrg": "1 if the integration belongs to an organization-level account, else 0.",+ "props": "The integration's properties.",+ "createdOrUpdatedBy": "The user who created or last updated the integration.",+ "createdOrUpdatedTime": "When the integration was created or last updated.",+ },+ },+ "policies": {+ "description": "Policies registered in Lacework FortiCNAPP. Alerts reference a policy by policyId.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Policies",+ "columns": {+ "policyId": "Unique identifier for the policy.",+ "policyType": "The policy type, such as Violation.",+ "queryId": "The identifier of the query the policy runs.",+ "title": "The title of the policy.",+ "enabled": "Whether the policy is enabled.",+ "description": "The description of the policy.",+ "remediation": "How to remediate events the policy triggers.",+ "severity": "The severity of events the policy triggers.",+ "limit": "The maximum number of records each policy run returns.",+ "evalFrequency": "How often the policy runs (deprecated).",+ "alertEnabled": "Whether the policy sends alerts when it triggers.",+ "alertProfile": "The alert profile used when the policy triggers.",+ "tags": "The tags of the policy.",+ "evaluatorId": "The evaluator identifier of the policy.",+ "owner": "The user who created the policy.",+ "lastUpdateTime": "When the policy was last updated.",+ "lastUpdateUser": "The user who last updated the policy.",+ "exceptionConfiguration": "The configuration of policy exceptions, where applicable.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.pyindex 927958beada9..67ac7d05cecd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.py@@ -272,9 +272,37 @@ def _first_page_request(body: dict[str, Any] = {"timeFilter": {"startTime": start, "endTime": end}}if config.dataset:body["dataset"] = config.dataset+ if config.csp:+ body["csp"] = config.cspreturn "POST", f"{api_base_url}{config.path}", body+def _redact_row(config: LaceworkEndpointConfig, row: dict[str, Any]) -> dict[str, Any]:+ nested = row.get("data")+ if not config.redacted_data_keys or not isinstance(nested, dict):+ return row+ return {**row, "data": {k: v for k, v in nested.items() if k not in config.redacted_data_keys}}+++def _get_unwindowed_rows(+ client: LaceworkClient,+ config: LaceworkEndpointConfig,+ api_base_url: str,+ account_name: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ url: str | None = f"{api_base_url}{config.path}"+ while url is not None:+ data = client.fetch(config.method, url)+ rows = data.get("data") or []+ url = ((data.get("paging") or {}).get("urls") or {}).get("nextPage")+ if url is not None and not _is_same_host(url, account_name):+ logger.warning("Lacework: stopping pagination, next URL host does not match the configured account")+ url = None+ if rows:+ yield [_redact_row(config, row) for row in rows]++def get_rows(account_name: str,key_id: str,@@ -287,10 +315,16 @@ def get_rows() -> Iterator[list[dict[str, Any]]]:config = LACEWORK_ENDPOINTS[endpoint]# One session reused across every page and window so urllib3 keeps the connection alive.- session = make_tracked_session()+ # Endpoints that strip credentials from rows must not have the raw response sampled either: the+ # name-based sample scrubbers don't recognise Lacework's camelCase credential keys.+ session = make_tracked_session(capture=not config.redacted_data_keys)client = LaceworkClient(session, account_name, key_id, secret_key, logger)api_base_url = base_url(account_name)+ if not config.windowed:+ yield from _get_unwindowed_rows(client, config, api_base_url, account_name, logger)+ return+now = datetime.now(UTC)start: datetime | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.pyindex 497b0470402f..86b8028a6072 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.py@@ -1,6 +1,8 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -13,7 +15,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:}-@dataclass+@frozenclass LaceworkEndpointConfig:name: str# Path relative to https://{account}.lacework.net/api/v2, e.g. "/Alerts" or@@ -39,6 +41,12 @@ class LaceworkEndpointConfig:default_lookback_days: int = 90# Required `dataset` body param for /Configs/ComplianceEvaluations/search.dataset: Optional[str] = None+ # Required `csp` body param for /Inventory/search.+ csp: Optional[str] = None+ # False for plain list endpoints that take no time range and return the whole collection.+ windowed: bool = True+ # Keys removed from each row's nested `data` object before it is yielded.+ redacted_data_keys: tuple[str, ...] = ()description: Optional[str] = None@@ -58,6 +66,26 @@ def _compliance_endpoint(name: str, dataset: str, provider: str) -> LaceworkEndp)+def _inventory_endpoint(name: str, csp: str, provider: str) -> LaceworkEndpointConfig:+ # One row per resource per daily collection run, with no unique id, so inventory syncs+ # append-only on the collection's startTime.+ return LaceworkEndpointConfig(+ name=name,+ path="/Inventory/search",+ csp=csp,+ time_filter_field="startTime",+ incremental_fields=[_datetime_incremental_field("startTime")],+ supports_append=True,+ partition_key="startTime",+ window_days=1,+ default_lookback_days=7,+ description=(+ f"{provider} cloud resource inventory, one row per resource per collection run. "+ "Syncs the last 7 days on first sync or full refresh"+ ),+ )++LACEWORK_ENDPOINTS: dict[str, LaceworkEndpointConfig] = {"alerts": LaceworkEndpointConfig(name="alerts",@@ -144,6 +172,56 @@ LACEWORK_ENDPOINTS: dict[str, LaceworkEndpointConfig] = {"Syncs the last 30 days on first sync or full refresh"),),+ "entities_containers": LaceworkEndpointConfig(+ name="entities_containers",+ path="/Entities/Containers/search",+ time_filter_field="startTime",+ incremental_fields=[_datetime_incremental_field("startTime")],+ supports_append=True,+ partition_key="startTime",+ # Rows are hourly aggregates per container, so volume grows fast: 1-day windows keep+ # each request under the 500k-row cap.+ window_days=1,+ default_lookback_days=7,+ description=(+ "Active containers, one row per container per hourly aggregation window. "+ "Syncs the last 7 days on first sync or full refresh"+ ),+ ),+ "entities_images": LaceworkEndpointConfig(+ name="entities_images",+ path="/Entities/Images/search",+ time_filter_field="createdTime",+ incremental_fields=[_datetime_incremental_field("createdTime")],+ supports_append=True,+ partition_key="createdTime",+ window_days=1,+ default_lookback_days=30,+ description=(+ "Container images, one row per image per machine. Syncs the last 30 days on first sync or full refresh"+ ),+ ),+ "inventory_aws": _inventory_endpoint("inventory_aws", "AWS", "AWS"),+ "inventory_azure": _inventory_endpoint("inventory_azure", "Azure", "Azure"),+ "inventory_gcp": _inventory_endpoint("inventory_gcp", "GCP", "GCP"),+ "cloud_accounts": LaceworkEndpointConfig(+ name="cloud_accounts",+ path="/CloudAccounts",+ method="GET",+ windowed=False,+ primary_keys=["intgGuid"],+ # The integration config can carry the cloud credentials Lacework was given.+ redacted_data_keys=("credentials", "accessKeyCredentials", "crossAccountCredentials"),+ description="Cloud account integrations (AWS, Azure, GCP, OCI). Full refresh only",+ ),+ "policies": LaceworkEndpointConfig(+ name="policies",+ path="/Policies",+ method="GET",+ windowed=False,+ primary_keys=["policyId"],+ description="Lacework policies, keyed by the policyId that alerts reference. Full refresh only",+ ),}ENDPOINTS = tuple(LACEWORK_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.pyindex 2dec63e13caa..6718e997209a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py@@ -177,19 +177,33 @@ class TestValidateCredentials:class TestGetRowsWindowing:+ @parameterized.expand(+ [+ (+ "compliance",+ "compliance_evaluations_aws",+ "/Configs/ComplianceEvaluations/search",+ "dataset",+ "AwsCompliance",+ ),+ ("inventory", "inventory_gcp", "/Inventory/search", "csp", "GCP"),+ ]+ )@time_machine.travel("2026-06-15T12:00:00Z", tick=False)- def test_compliance_search_includes_dataset(self) -> None:+ def test_search_includes_required_body_param(+ self, _name: str, endpoint: str, path: str, param: str, value: str+ ) -> None:session = _FakeSession([_FakeResponse(200, {"data": [], "paging": {}})])_collect_rows(session,- "compliance_evaluations_aws",+ endpoint,should_use_incremental_field=True,db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),)_method, url, body, _headers = session.data_calls[0]- assert url.endswith("/api/v2/Configs/ComplianceEvaluations/search")- assert body is not None and body["dataset"] == "AwsCompliance"+ assert url.endswith(f"/api/v2{path}")+ assert body is not None and body[param] == value@time_machine.travel("2026-06-15T12:00:00Z", tick=False)def test_full_refresh_uses_default_lookback(self) -> None:@@ -206,6 +220,69 @@ class TestGetRowsWindowing:}+class TestGetRowsUnwindowed:+ def test_list_endpoint_pages_without_time_range_and_strips_credentials(self) -> None:+ next_url = "https://mycompany.lacework.net/api/v2/CloudAccounts/page2"+ session = _FakeSession(+ [+ _FakeResponse(+ 200,+ {+ "data": [+ {+ "intgGuid": "A",+ "data": {+ "awsAccountId": "123",+ "crossAccountCredentials": {"externalId": "x", "roleArn": "arn"},+ },+ }+ ],+ "paging": {"urls": {"nextPage": next_url}},+ },+ ),+ _FakeResponse(+ 200,+ {"data": [{"intgGuid": "B", "data": {"credentials": {"clientSecret": "s"}, "tenantId": "t"}}]},+ ),+ ]+ )+ manager = _FakeResumableManager()+ rows = _collect_rows(session, "cloud_accounts", manager=manager)++ assert rows == [+ {"intgGuid": "A", "data": {"awsAccountId": "123"}},+ {"intgGuid": "B", "data": {"tenantId": "t"}},+ ]+ assert [(m, u, b) for m, u, b, _h in session.data_calls] == [+ ("GET", "https://mycompany.lacework.net/api/v2/CloudAccounts", None),+ ("GET", next_url, None),+ ]+ assert manager.saved == []++ @parameterized.expand(+ [+ ("credential_endpoint", "cloud_accounts", False),+ ("plain_endpoint", "policies", True),+ ]+ )+ def test_data_session_capture_follows_credential_redaction(self, _name: str, endpoint: str, captured: bool) -> None:+ session = _FakeSession([_FakeResponse(200, {"data": []})])+ with patch(f"{_LACEWORK_MODULE}.make_tracked_session", return_value=session) as mock_make:+ list(+ get_rows(+ account_name="mycompany",+ key_id="KEY_ID",+ secret_key="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ data_session_calls = [c for c in mock_make.call_args_list if not c.kwargs.get("redact_values")]+ assert [c.kwargs.get("capture", True) for c in data_session_calls] == [captured]++class TestGetRowsPagination:@time_machine.travel("2026-06-15T12:00:00Z", tick=False)def test_next_page_on_foreign_host_is_not_followed(self) -> None: