: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): implement lacework import source (#71347)
Tom Owers4f51fe89cf40
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 20de9e93f080..4a9f8df8441c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -293,6 +293,7 @@ the row lists both.| koyeb | HTTP | requests | ✅ || kong_konnect | HTTP | requests | ✅ || kubecost | HTTP | requests | ✅ |+| lacework | HTTP | requests | ✅ || lago | HTTP | requests | ✅ || lambda_labs | HTTP | requests | ✅ || langfuse | HTTP | requests | ✅ |@@ -764,7 +765,6 @@ doesn't conflict with concurrent PRs.- knock- koyeb- kyve-- lacework- lambda_labs- langsmith- leexidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex bb85d4272e44..54bb5981c8d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2399,7 +2399,9 @@ class KustomerSourceConfig(config.Config):@config.configclass LaceworkSourceConfig(config.Config):- pass+ account_name: str+ key_id: str+ secret_key: str@config.configdiff --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.pynew file mode 100644index 000000000000..08fb63c4965c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/canonical_descriptions.py@@ -0,0 +1,137 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+ CanonicalEndpoint,+)++_COMPLIANCE_COLUMNS = {+ "account": "The evaluated cloud account or project (id and alias).",+ "evalType": "The evaluation type, such as LW_SA (Lacework security assessment).",+ "id": "The identifier of the evaluated recommendation, such as LW_AWS_IAM_7.",+ "reason": "Why the resource is non-compliant with the recommendation.",+ "recommendation": "The recommendation the resource was evaluated against.",+ "region": "The cloud region of the evaluated resource.",+ "reportTime": "When the compliance evaluation ran.",+ "resource": "The identifier (e.g. ARN) of the evaluated resource.",+ "section": "The compliance report section the recommendation belongs to.",+ "severity": "The severity of the recommendation.",+ "status": "The evaluation result, such as Compliant or NonCompliant.",+}+++def _compliance_entry(provider: str) -> CanonicalEndpoint:+ return {+ "description": f"{provider} compliance evaluations: one row per resource per recommendation per report, with the compliance status, reason, and severity.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Configs",+ "columns": _COMPLIANCE_COLUMNS,+ }+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "alerts": {+ "description": "Alerts raised by Lacework FortiCNAPP for potential threats, anomalies, and policy violations across your cloud environments.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Alerts",+ "columns": {+ "alertId": "Unique identifier for the alert.",+ "alertType": "The alert type, such as MaliciousFile.",+ "alertName": "The alert name, such as 'Service called GCP API'.",+ "alertInfo": "Details of the alert (subject and description).",+ "severity": "The alert's severity level, such as Critical, High, Medium, Low, or Info.",+ "internetExposure": "Whether any entity involved in the alert is exposed to the internet.",+ "reachability": "Whether any entity in the alert is reachable.",+ "derivedFields": "The alert category, subcategory, and source.",+ "startTime": "When the potential threat started.",+ "endTime": "When the potential threat ended.",+ "lastUserUpdatedTime": "When a user last updated the alert.",+ "status": "The current status of the alert, such as Open or Closed.",+ },+ },+ "audit_logs": {+ "description": "Lacework console audit log: one row per action a user performed in the Lacework FortiCNAPP account.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/AuditLogs",+ "columns": {+ "createdTime": "When the logged action happened.",+ "accountName": "The account name associated with the logged action.",+ "userName": "The username of the user associated with the logged action.",+ "eventName": "The name of the logged event, such as User Login.",+ "userAction": "Summary of the action, such as 'Login with OAuth Succeeded' or 'Alert Channel Created'.",+ "eventDescription": "Human-readable summary of the event.",+ },+ },+ "agent_info": {+ "description": "Inventory of Lacework agents: one row per agent with its version, host, status, and tags.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/AgentInfo",+ "columns": {+ "agentVersion": "The version of the installed Lacework agent.",+ "createdTime": "When the agent was first seen.",+ "hostname": "The hostname of the machine the agent runs on.",+ "ipAddr": "The IP address of the machine the agent runs on.",+ "lastUpdate": "When the agent last reported in.",+ "mid": "The machine identifier the agent is installed on.",+ "mode": "The agent mode, such as normal.",+ "os": "The operating system of the machine the agent runs on.",+ "status": "The agent status, such as ACTIVE.",+ "tags": "Cloud provider and custom tags of the machine the agent runs on.",+ },+ },+ "vulnerabilities_hosts": {+ "description": "Host vulnerability assessment results: one row per CVE per machine per assessment, with severity, fix, and risk information.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Vulnerabilities",+ "columns": {+ "startTime": "When the assessment window started.",+ "endTime": "When the assessment window ended.",+ "vulnId": "The vulnerability identifier, such as a CVE id.",+ "mid": "The machine identifier the vulnerability was found on.",+ "machineTags": "Cloud provider and custom tags of the machine.",+ "evalCtx": "Evaluation context for the assessment, such as hostname and scan batch.",+ "evalGuid": "Unique identifier of the assessment run.",+ "featureKey": "The affected package (name, namespace, installed version).",+ "packageStatus": "The package status, such as ACTIVE.",+ "severity": "The severity of the vulnerability.",+ "fixInfo": "Fix availability and the fixed version.",+ "status": "The vulnerability status, such as New, Active, or Fixed.",+ "cveProps": "CVE metadata, including description, link, and CVSS scores.",+ "riskScore": "Lacework's risk score for this vulnerability on this machine.",+ "riskInfo": "Factors contributing to the risk score.",+ "cveRiskScore": "Risk score of the CVE itself.",+ "hostRiskScore": "Risk score of the affected host.",+ },+ },+ "vulnerabilities_containers": {+ "description": "Container image vulnerability assessment results: one row per CVE per image per assessment, with severity, fix, and risk information.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Vulnerabilities",+ "columns": {+ "startTime": "When the assessment ran.",+ "vulnId": "The vulnerability identifier, such as a CVE id.",+ "imageId": "The identifier of the affected container image.",+ "evalCtx": "Evaluation context for the assessment, such as the image registry, repo, and tags.",+ "evalGuid": "Unique identifier of the assessment run.",+ "featureKey": "The affected package (name, namespace, version).",+ "featureProps": "Additional properties of the affected package, such as the introducing layer.",+ "packageStatus": "The package status, such as ACTIVE.",+ "fixInfo": "Fix availability and the fixed version.",+ "severity": "The severity of the vulnerability.",+ "status": "The vulnerability status, such as New, Active, or Fixed.",+ "riskScore": "Lacework's risk score for this vulnerability in this image.",+ "riskInfo": "Factors contributing to the risk score.",+ "cveRiskScore": "Risk score of the CVE itself.",+ "imageRiskScore": "Risk score of the affected image.",+ },+ },+ "compliance_evaluations_aws": _compliance_entry("AWS"),+ "compliance_evaluations_azure": _compliance_entry("Azure"),+ "compliance_evaluations_gcp": _compliance_entry("GCP"),+ "compliance_evaluations_k8s": _compliance_entry("Kubernetes"),+ "entities_machines": {+ "description": "Machines observed online in your environment: one row per machine per activity segment.",+ "docs_url": "https://api.lacework.net/api/v2/docs#tag/Entities",+ "columns": {+ "startTime": "When the machine's activity segment started.",+ "endTime": "When the machine's activity segment ended.",+ "mid": "The machine identifier.",+ "hostname": "The hostname of the machine.",+ "machineTags": "Cloud provider and custom tags of the machine.",+ "primaryIpAddr": "The primary IP address of the machine.",+ "entityType": "The entity type (Machine).",+ },+ },+}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.pynew file mode 100644index 000000000000..be3fa9afb471--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.py@@ -0,0 +1,416 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.settings import (+ LACEWORK_ENDPOINTS,+ LaceworkEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# The rate limit is 480 requests per rolling hour; a 429's Retry-After can be long, so cap the+# in-process wait and let the (resumable) Temporal activity retry handle anything longer.+MAX_RETRY_AFTER_SECONDS = 60+TOKEN_EXPIRY_SECONDS = 3600+TOKEN_REFRESH_LEEWAY_SECONDS = 300+# Lacework caps one request's result set (across all its pages) at 500k rows.+RESULT_SET_ROW_CAP = 500_000++INVALID_ACCOUNT_ERROR = "Invalid Lacework account name"++_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.\-]*$")+++class LaceworkRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class LaceworkResumeConfig:+ # ISO start of the time window currently being paged. Windows are re-derived from this on+ # resume, so boundaries stay consistent across attempts.+ window_start: str+ # ISO end of that window (pinned so a saved nextPage URL is always paired with the exact+ # window it belongs to).+ window_end: str+ # Next page URL within the window. None means "start the window at its first page".+ next_page_url: str | None = None+++def normalize_account(account_name: str) -> str:+ """Turn whatever the user typed into a bare account name.++ Accepts values like ``mycompany``, ``mycompany.lacework.net``, or+ ``https://mycompany.lacework.net/`` and returns ``mycompany``.+ """+ account = account_name.strip()+ account = re.sub(r"^https?://", "", account, flags=re.IGNORECASE)+ account = account.split("/")[0].strip()+ account = re.sub(r"\.lacework\.net$", "", account, flags=re.IGNORECASE)+ return account+++def base_url(account_name: str) -> str:+ """Account-specific API base. The validation pins every request to ``*.lacework.net``."""+ account = normalize_account(account_name)+ if not account or not _ACCOUNT_RE.match(account):+ raise ValueError(INVALID_ACCOUNT_ERROR)+ return f"https://{account}.lacework.net/api/v2"+++def _is_same_host(url: str, account_name: str) -> bool:+ """Whether a (server-controlled) nextPage URL points back at the configured account host.++ Parse the URL the way requests/urllib3 will before comparing hosts: a backslash (literal or+ percent-encoded) in the authority is a path separator to them, so ``https://evil.example\\@host``+ connects to ``evil.example`` even though ``urlparse`` reports ``host``. Normalize backslashes to+ forward slashes first, then require an ``https`` URL on the default port whose hostname matches+ exactly — otherwise a crafted resume/nextPage URL could exfiltrate the bearer token.+ """+ try:+ normalized = url.replace("\\", "/").replace("%5c", "/").replace("%5C", "/")+ parsed = urlparse(normalized)+ if parsed.scheme.lower() != "https":+ return False+ if parsed.port not in (None, 443):+ return False+ expected = urlparse(base_url(account_name)).hostname or ""+ return (parsed.hostname or "").lower() == expected.lower()+ except Exception:+ return False+++def _format_datetime(dt: datetime) -> str:+ """Lacework accepts ``yyyy-MM-ddTHH:mm:ss.SSSZ``; millisecond precision keeps window+ boundaries exact so watermark-derived starts don't truncate backwards."""+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _parse_datetime(value: Any) -> datetime:+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+ raise ValueError(f"Cannot parse datetime from {value!r}")+++def _parse_retry_after(response: requests.Response) -> float | None:+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, LaceworkRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++class LaceworkClient:+ """Thin client handling the two-step auth (API key -> short-lived bearer token) and requests.++ The bearer token is cached and refreshed with a leeway before its expiry, so long syncs never+ send an expired token.+ """++ def __init__(+ self,+ session: requests.Session,+ account_name: str,+ key_id: str,+ secret_key: str,+ logger: FilteringBoundLogger,+ ) -> None:+ self._session = session+ self._account_name = account_name+ self._base_url = base_url(account_name)+ self._key_id = key_id+ self._secret_key = secret_key+ self._logger = logger+ self._token: str | None = None+ self._token_expires_at: datetime | None = None+ # Token exchanges carry the secret key in the X-LW-UAKS header and return the minted+ # bearer token in a generic `token` field — neither is recognised by the name-based+ # sample scrubbers, so keep auth calls out of HTTP sample capture entirely.+ self._auth_session = make_tracked_session(redact_values=(secret_key,), capture=False)++ @retry(+ retry=retry_if_exception_type((LaceworkRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def _request(+ self,+ session: requests.Session,+ method: str,+ url: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None = None,+ ) -> requests.Response:+ response = session.request(+ method,+ url,+ headers=headers,+ json=json_body,+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise LaceworkRetryableError(+ f"Lacework API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ if not response.ok:+ self._logger.error(f"Lacework API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response++ def _get_token(self) -> str:+ now = datetime.now(UTC)+ if (+ self._token is not None+ and self._token_expires_at is not None+ and now < self._token_expires_at - timedelta(seconds=TOKEN_REFRESH_LEEWAY_SECONDS)+ ):+ return self._token++ response = self._request(+ self._auth_session,+ "POST",+ f"{self._base_url}/access/tokens",+ headers={"X-LW-UAKS": self._secret_key, "Content-Type": "application/json"},+ json_body={"keyId": self._key_id, "expiryTime": TOKEN_EXPIRY_SECONDS},+ )+ data = response.json()+ self._token = str(data["token"])+ try:+ self._token_expires_at = _parse_datetime(data["expiresAt"])+ except Exception:+ self._token_expires_at = now + timedelta(seconds=TOKEN_EXPIRY_SECONDS)+ return self._token++ def _auth_headers(self) -> dict[str, str]:+ return {"Authorization": f"Bearer {self._get_token()}", "Content-Type": "application/json"}++ def fetch(self, method: str, url: str, json_body: dict[str, Any] | None = None) -> dict[str, Any]:+ """Fetch one page. A 204 (no data) comes back as an empty payload."""+ response = self._request(self._session, method, url, headers=self._auth_headers(), json_body=json_body)+ if response.status_code == 204 or not response.content:+ return {}+ parsed = response.json()+ return parsed if isinstance(parsed, dict) else {"data": parsed}+++def validate_credentials(account_name: str, key_id: str, secret_key: str) -> tuple[bool, str | None]:+ """One cheap probe: the token exchange itself confirms the account, key id, and secret."""+ try:+ url = f"{base_url(account_name)}/access/tokens"+ except ValueError:+ return False, INVALID_ACCOUNT_ERROR++ try:+ # capture=False + redact_values: the request's X-LW-UAKS header and the response's+ # generic `token` field would otherwise slip past the name-based sample scrubbers.+ response = make_tracked_session(redact_values=(secret_key,), capture=False).post(+ url,+ headers={"X-LW-UAKS": secret_key, "Content-Type": "application/json"},+ json={"keyId": key_id, "expiryTime": TOKEN_EXPIRY_SECONDS},+ timeout=10,+ allow_redirects=False,+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 201:+ return True, None++ if response.status_code in (401, 403):+ return False, "Invalid Lacework API key ID or secret key"++ try:+ body = response.json()+ return False, str(body.get("message", response.text))+ except Exception:+ return False, response.text or f"Lacework API returned status {response.status_code}"+++def _first_page_request(+ config: LaceworkEndpointConfig, api_base_url: str, window_start: datetime, window_end: datetime+) -> tuple[str, str, dict[str, Any] | None]:+ """Build (method, url, body) for the first page of a time window."""+ start = _format_datetime(window_start)+ end = _format_datetime(window_end)+ if config.method == "GET":+ query = urlencode({"startTime": start, "endTime": end})+ return "GET", f"{api_base_url}{config.path}?{query}", None++ body: dict[str, Any] = {"timeFilter": {"startTime": start, "endTime": end}}+ if config.dataset:+ body["dataset"] = config.dataset+ return "POST", f"{api_base_url}{config.path}", body+++def get_rows(+ account_name: str,+ key_id: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LaceworkResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> 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()+ client = LaceworkClient(session, account_name, key_id, secret_key, logger)+ api_base_url = base_url(account_name)++ now = datetime.now(UTC)++ start: datetime | None = None+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ try:+ start = _parse_datetime(db_incremental_field_last_value)+ except ValueError:+ logger.warning(+ f"Lacework: could not parse incremental value {db_incremental_field_last_value!r}, "+ f"falling back to the default lookback"+ )+ if start is None:+ start = now - timedelta(days=config.default_lookback_days)+ # A future-dated watermark (bad source data) would build an inverted window; clamp to now.+ start = min(start, now)++ window_start = start+ window_end: datetime | None = None+ next_page_url: str | None = None++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ window_start = _parse_datetime(resume.window_start)+ window_end = _parse_datetime(resume.window_end)+ if resume.next_page_url and not _is_same_host(resume.next_page_url, account_name):+ logger.warning("Lacework: ignoring resume URL whose host does not match the configured account")+ else:+ next_page_url = resume.next_page_url+ logger.debug(f"Lacework: resuming from window_start={resume.window_start}, url={next_page_url}")++ while window_start < now:+ if window_end is None:+ window_end = min(window_start + timedelta(days=config.window_days), now)++ if next_page_url is not None:+ method, url, body = "GET", next_page_url, None+ else:+ method, url, body = _first_page_request(config, api_base_url, window_start, window_end)++ while True:+ data = client.fetch(method, url, body)+ rows = data.get("data") or []+ paging = data.get("paging") or {}+ total_rows = paging.get("totalRows")+ if isinstance(total_rows, int | float) and total_rows >= RESULT_SET_ROW_CAP:+ logger.warning(+ f"Lacework: result set for {endpoint} window "+ f"{_format_datetime(window_start)}..{_format_datetime(window_end)} hit the API's "+ f"{RESULT_SET_ROW_CAP}-row cap; rows beyond the cap are not returned"+ )++ next_page_url = (paging.get("urls") or {}).get("nextPage")+ if next_page_url is not None and not _is_same_host(next_page_url, account_name):+ logger.warning("Lacework: stopping pagination, next URL host does not match the configured account")+ next_page_url = None++ if rows:+ yield rows++ # Save AFTER yielding so a crash re-yields the current page rather than skipping it.+ # When the window is done, checkpoint the NEXT window instead so a resume doesn't+ # re-walk this one.+ if next_page_url is not None:+ resumable_source_manager.save_state(+ LaceworkResumeConfig(+ window_start=_format_datetime(window_start),+ window_end=_format_datetime(window_end),+ next_page_url=next_page_url,+ )+ )+ method, url, body = "GET", next_page_url, None+ else:+ break++ window_start = window_end+ window_end = None+ if window_start < now:+ next_window_end = min(window_start + timedelta(days=config.window_days), now)+ resumable_source_manager.save_state(+ LaceworkResumeConfig(+ window_start=_format_datetime(window_start),+ window_end=_format_datetime(next_window_end),+ next_page_url=None,+ )+ )+++def lacework_source(+ account_name: str,+ key_id: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LaceworkResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = LACEWORK_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ account_name=account_name,+ key_id=key_id,+ secret_key=secret_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Rows within a time window arrive in no documented order, so the incremental watermark+ # must only persist at successful job end ("desc" mode) — a per-batch checkpoint could+ # advance it past unfetched rows of the same window. Mid-job crashes resume via the+ # ResumableSourceManager state instead.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.pynew file mode 100644index 000000000000..497b0470402f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.py@@ -0,0 +1,153 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class LaceworkEndpointConfig:+ name: str+ # Path relative to https://{account}.lacework.net/api/v2, e.g. "/Alerts" or+ # "/Vulnerabilities/Hosts/search". GET endpoints take startTime/endTime query params;+ # POST search endpoints take a `timeFilter` object in the request body.+ path: str+ method: Literal["GET", "POST"] = "POST"+ # Row field the server-side time window filters on. Every Lacework list/search endpoint is+ # windowed (max 7 days per request), so this doubles as the incremental cursor field.+ time_filter_field: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Merge sync (dedupe on primary_keys) is only offered where the API exposes a unique row id.+ supports_incremental: bool = False+ supports_append: bool = False+ primary_keys: Optional[list[str]] = None+ # Stable field to partition by (a created/started timestamp, never a mutating one).+ partition_key: Optional[str] = None+ # Days per request window. The API hard-caps a request's time range at 7 days; high-volume+ # datasets use smaller windows so one result set stays under the 500,000-row cap Lacework+ # applies across all pages of a single request.+ window_days: int = 7+ # First sync / full refresh reaches back this many days instead of full history.+ default_lookback_days: int = 90+ # Required `dataset` body param for /Configs/ComplianceEvaluations/search.+ dataset: Optional[str] = None+ description: Optional[str] = None+++def _compliance_endpoint(name: str, dataset: str, provider: str) -> LaceworkEndpointConfig:+ # Compliance evaluation rows have no unique id (one row per resource/recommendation per+ # report), so they sync append-only on reportTime. The API only serves the last 90 days.+ return LaceworkEndpointConfig(+ name=name,+ path="/Configs/ComplianceEvaluations/search",+ dataset=dataset,+ time_filter_field="reportTime",+ incremental_fields=[_datetime_incremental_field("reportTime")],+ supports_append=True,+ partition_key="reportTime",+ default_lookback_days=90,+ description=f"{provider} compliance evaluations. Syncs the last 90 days on first sync or full refresh",+ )+++LACEWORK_ENDPOINTS: dict[str, LaceworkEndpointConfig] = {+ "alerts": LaceworkEndpointConfig(+ name="alerts",+ path="/Alerts",+ method="GET",+ time_filter_field="startTime",+ incremental_fields=[_datetime_incremental_field("startTime")],+ supports_incremental=True,+ supports_append=True,+ primary_keys=["alertId"],+ partition_key="startTime",+ default_lookback_days=90,+ description=(+ "Alerts raised by Lacework, filtered by the time the potential threat started. "+ "Status changes on alerts older than the last synced window are only picked up on a full refresh"+ ),+ ),+ "audit_logs": LaceworkEndpointConfig(+ name="audit_logs",+ path="/AuditLogs",+ method="GET",+ time_filter_field="createdTime",+ incremental_fields=[_datetime_incremental_field("createdTime")],+ supports_append=True,+ partition_key="createdTime",+ default_lookback_days=90,+ description="Lacework console audit log entries. Syncs the last 90 days on first sync or full refresh",+ ),+ "agent_info": LaceworkEndpointConfig(+ name="agent_info",+ path="/AgentInfo/search",+ # Agent rows mutate in place (status, lastUpdate) and the search window filters on+ # recent activity, so this is a full-refresh inventory of agents seen in the last 7 days.+ default_lookback_days=7,+ description="Inventory of Lacework agents active in the last 7 days. Full refresh only",+ ),+ "vulnerabilities_hosts": LaceworkEndpointConfig(+ name="vulnerabilities_hosts",+ path="/Vulnerabilities/Hosts/search",+ time_filter_field="startTime",+ incremental_fields=[_datetime_incremental_field("startTime")],+ supports_append=True,+ partition_key="startTime",+ # Host vulnerability assessments are the highest-volume dataset: 1-day windows keep each+ # request's result set under the API's 500k-row cap on large environments.+ window_days=1,+ default_lookback_days=30,+ description=(+ "Host vulnerability assessment results (one row per CVE per machine per assessment). "+ "Syncs the last 30 days on first sync or full refresh"+ ),+ ),+ "vulnerabilities_containers": LaceworkEndpointConfig(+ name="vulnerabilities_containers",+ path="/Vulnerabilities/Containers/search",+ time_filter_field="startTime",+ incremental_fields=[_datetime_incremental_field("startTime")],+ supports_append=True,+ partition_key="startTime",+ window_days=1,+ default_lookback_days=30,+ description=(+ "Container image vulnerability assessment results (one row per CVE per image per assessment). "+ "Syncs the last 30 days on first sync or full refresh"+ ),+ ),+ "compliance_evaluations_aws": _compliance_endpoint("compliance_evaluations_aws", "AwsCompliance", "AWS"),+ "compliance_evaluations_azure": _compliance_endpoint("compliance_evaluations_azure", "AzureCompliance", "Azure"),+ "compliance_evaluations_gcp": _compliance_endpoint("compliance_evaluations_gcp", "GcpCompliance", "GCP"),+ "compliance_evaluations_k8s": _compliance_endpoint("compliance_evaluations_k8s", "K8sCompliance", "Kubernetes"),+ "entities_machines": LaceworkEndpointConfig(+ name="entities_machines",+ path="/Entities/Machines/search",+ time_filter_field="startTime",+ incremental_fields=[_datetime_incremental_field("startTime")],+ supports_append=True,+ partition_key="startTime",+ # One row per machine per activity segment — 1-day windows keep large fleets under the+ # 500k-row-per-request cap.+ window_days=1,+ default_lookback_days=30,+ description=(+ "Machines observed online, one row per machine per activity segment. "+ "Syncs the last 30 days on first sync or full refresh"+ ),+ ),+}++ENDPOINTS = tuple(LACEWORK_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LACEWORK_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/source.pyindex b7684cb96dc0..84095fff7646 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/source.py@@ -1,30 +1,162 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LaceworkSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.lacework import (+ INVALID_ACCOUNT_ERROR,+ LaceworkResumeConfig,+ lacework_source,+ validate_credentials as validate_lacework_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LACEWORK_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LaceworkSource(SimpleSource[LaceworkSourceConfig]):+class LaceworkSource(ResumableSource[LaceworkSourceConfig, LaceworkResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LACEWORK+ @property+ def connection_host_fields(self) -> list[str]:+ # `account_name` decides which host the stored secret key is sent to; retargeting it must+ # re-require the credentials.+ return ["account_name"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.LACEWORK,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Lacework FortiCNAPP (Fortinet)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["forticnapp", "fortinet", "cnapp", "cloud security"],+ caption="""Link your Lacework FortiCNAPP account to pull alerts, vulnerabilities, and compliance data into the PostHog Data warehouse.++Create an API key in the FortiCNAPP Console under **Settings > Configuration > API keys** (requires admin permission), then download it to get the key ID and secret key.++Your account name is the first part of your FortiCNAPP URL: `https://<account name>.lacework.net`.""",iconPath="/static/services/lacework.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/lacework",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="account_name",+ label="Account name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="mycompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="key_id",+ label="API key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="ACCOUNT_ABCDEF0123456789...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="_abcdef0123456789",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The API host is account-specific, so match on the stable status text rather than a full+ # URL. These errors only surface from this source's own requests.+ return {+ "401 Client Error": "Your Lacework API key is invalid or has been revoked. Create a new API key in the FortiCNAPP Console and reconnect.",+ "403 Client Error": "Your Lacework API key does not have the required permissions. Check the key's permissions in the FortiCNAPP Console and reconnect.",+ INVALID_ACCOUNT_ERROR: "The Lacework account name is invalid. Enter the first part of your FortiCNAPP URL: https://<account name>.lacework.net.",+ }++ def get_schemas(+ self,+ config: LaceworkSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=LACEWORK_ENDPOINTS[endpoint].supports_incremental,+ supports_append=LACEWORK_ENDPOINTS[endpoint].supports_append,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=LACEWORK_ENDPOINTS[endpoint].description,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: LaceworkSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_lacework_credentials(config.account_name, config.key_id, config.secret_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LaceworkResumeConfig]:+ return ResumableSourceManager[LaceworkResumeConfig](inputs, LaceworkResumeConfig)++ def source_for_pipeline(+ self,+ config: LaceworkSourceConfig,+ resumable_source_manager: ResumableSourceManager[LaceworkResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return lacework_source(+ account_name=config.account_name,+ key_id=config.key_id,+ secret_key=config.secret_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)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.pynew file mode 100644index 000000000000..4aa4e7252693--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py@@ -0,0 +1,529 @@+from datetime import UTC, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.lacework import (+ INVALID_ACCOUNT_ERROR,+ LaceworkResumeConfig,+ _is_same_host,+ base_url,+ get_rows,+ lacework_source,+ normalize_account,+ validate_credentials,+)++_LACEWORK_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.lacework.lacework"+++class _FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, headers: dict[str, str] | None = None) -> None:+ self.status_code = status_code+ self._json_data = json_data+ self.headers = headers or {}+ self.content = b"" if json_data is None else b"{}"+ self.text = "" if json_data is None else str(json_data)++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._json_data++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ raise requests.HTTPError(+ f"{self.status_code} Client Error: error for url: fake", response=requests.Response()+ )+++class _FakeSession:+ def __init__(self, data_responses: list[_FakeResponse]) -> None:+ self.data_calls: list[tuple[str, str, dict[str, Any] | None, dict[str, str]]] = []+ self.token_calls = 0+ self._data_responses = list(data_responses)++ def request(self, method: str, url: str, **kwargs: Any) -> _FakeResponse:+ if url.endswith("/access/tokens"):+ self.token_calls += 1+ return _FakeResponse(201, {"token": "tok-123", "expiresAt": "2100-01-01T00:00:00.000Z"})+ self.data_calls.append((method, url, kwargs.get("json"), kwargs.get("headers") or {}))+ return self._data_responses.pop(0)+++class _FakeResumableManager:+ def __init__(self, state: LaceworkResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[LaceworkResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> LaceworkResumeConfig | None:+ return self._state++ def save_state(self, data: LaceworkResumeConfig) -> None:+ self.saved.append(data)+++def _collect_rows(+ session: _FakeSession,+ endpoint: str,+ manager: _FakeResumableManager | None = None,+ **incremental: Any,+) -> list[dict]:+ rows: list[dict] = []+ with patch(f"{_LACEWORK_MODULE}.make_tracked_session", return_value=session):+ for batch in get_rows(+ account_name="mycompany",+ key_id="KEY_ID",+ secret_key="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager or _FakeResumableManager(), # type: ignore[arg-type]+ **incremental,+ ):+ rows.extend(batch)+ return rows+++class TestAccountNormalization:+ @parameterized.expand(+ [+ ("bare_account", "mycompany"),+ ("full_domain", "mycompany.lacework.net"),+ ("full_url", "https://mycompany.lacework.net/"),+ ("url_with_path", "https://mycompany.lacework.net/api/v2"),+ ("whitespace", " mycompany "),+ ]+ )+ def test_normalize_account_variants(self, _name: str, value: str) -> None:+ assert normalize_account(value) == "mycompany"+ assert base_url(value) == "https://mycompany.lacework.net/api/v2"++ def test_account_with_path_stays_pinned_under_lacework_net(self) -> None:+ # Anything after a slash is dropped, so a crafted value can't escape *.lacework.net.+ assert base_url("evil.com/pwn?x=") == "https://evil.com.lacework.net/api/v2"++ @parameterized.expand(+ [+ ("empty", ""),+ ("leading_dash", "-mycompany"),+ ("query_injection", "mycompany?x=1"),+ ("space_inside", "my company"),+ ("at_sign", "[email protected]"),+ ]+ )+ def test_base_url_rejects_invalid_accounts(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError, match=INVALID_ACCOUNT_ERROR):+ base_url(value)+++class TestIsSameHost:+ @parameterized.expand(+ [+ ("plain", "https://mycompany.lacework.net/api/v2/Alerts/next"),+ ("uppercase_host", "https://MyCompany.Lacework.NET/api/v2/next"),+ ("default_port", "https://mycompany.lacework.net:443/api/v2/next"),+ ]+ )+ def test_accepts_matching_host(self, _name: str, url: str) -> None:+ assert _is_same_host(url, "mycompany") is True++ @parameterized.expand(+ [+ ("foreign_host", "https://evil.com/api/v2/steal"),+ # requests/urllib3 treat a backslash in the authority as a path separator, so these+ # connect to evil.example while urlparse would otherwise report the trusted host.+ ("literal_backslash", "https://evil.example\\@mycompany.lacework.net/api/v2/next"),+ ("encoded_backslash_lower", "https://evil.example%[email protected]/api/v2/next"),+ ("encoded_backslash_upper", "https://evil.example%[email protected]/api/v2/next"),+ ("http_scheme", "http://mycompany.lacework.net/api/v2/next"),+ ("non_default_port", "https://mycompany.lacework.net:8443/api/v2/next"),+ ]+ )+ def test_rejects_bad_host(self, _name: str, url: str) -> None:+ assert _is_same_host(url, "mycompany") is False+++class TestValidateCredentials:+ def _validate(self, response: _FakeResponse) -> tuple[bool, str | None]:+ session = MagicMock()+ session.post.return_value = response+ with patch(f"{_LACEWORK_MODULE}.make_tracked_session", return_value=session):+ return validate_credentials("mycompany", "KEY_ID", "secret")++ def test_valid_credentials(self) -> None:+ assert self._validate(_FakeResponse(201, {"token": "tok", "expiresAt": "2100-01-01T00:00:00.000Z"})) == (+ True,+ None,+ )++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])+ def test_bad_credentials(self, _name: str, status_code: int) -> None:+ ok, message = self._validate(_FakeResponse(status_code, {"message": "unauthorized"}))+ assert ok is False+ assert message == "Invalid Lacework API key ID or secret key"++ def test_other_error_surfaces_api_message(self) -> None:+ ok, message = self._validate(_FakeResponse(400, {"message": "expiryTime out of range"}))+ assert ok is False+ assert message == "expiryTime out of range"++ def test_invalid_account_fails_without_network(self) -> None:+ with patch(f"{_LACEWORK_MODULE}.make_tracked_session") as mock_session:+ ok, message = validate_credentials("my company", "KEY_ID", "secret")+ assert ok is False+ assert message == INVALID_ACCOUNT_ERROR+ mock_session.assert_not_called()+++class TestGetRowsWindowing:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_post_search_slices_watermark_to_now_into_windows(self) -> None:+ # vulnerabilities_hosts uses 1-day windows; a watermark 2.5 days back must produce three+ # consecutive windows ending exactly at now — a slicing bug would skip or overlap data.+ session = _FakeSession(+ [+ _FakeResponse(200, {"data": [{"vulnId": "CVE-1"}], "paging": {}}),+ _FakeResponse(200, {"data": [{"vulnId": "CVE-2"}], "paging": {}}),+ _FakeResponse(200, {"data": [{"vulnId": "CVE-3"}], "paging": {}}),+ ]+ )+ rows = _collect_rows(+ session,+ "vulnerabilities_hosts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 13, 0, 0, tzinfo=UTC),+ )++ assert [r["vulnId"] for r in rows] == ["CVE-1", "CVE-2", "CVE-3"]+ assert [+ (method, body["timeFilter"]) for method, _url, body, _headers in session.data_calls if body is not None+ ] == [+ ("POST", {"startTime": "2026-06-13T00:00:00.000Z", "endTime": "2026-06-14T00:00:00.000Z"}),+ ("POST", {"startTime": "2026-06-14T00:00:00.000Z", "endTime": "2026-06-15T00:00:00.000Z"}),+ ("POST", {"startTime": "2026-06-15T00:00:00.000Z", "endTime": "2026-06-15T12:00:00.000Z"}),+ ]+ assert all(url.endswith("/api/v2/Vulnerabilities/Hosts/search") for _m, url, _b, _h in session.data_calls)++ @freeze_time("2026-06-15T12:00:00Z")+ def test_get_endpoint_sends_time_window_as_query_params(self) -> None:+ session = _FakeSession([_FakeResponse(200, {"data": [{"alertId": 1}], "paging": {}})])+ rows = _collect_rows(+ session,+ "alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )++ assert rows == [{"alertId": 1}]+ method, url, body, _headers = session.data_calls[0]+ assert method == "GET"+ assert body is None+ parsed = urlparse(url)+ assert parsed.path == "/api/v2/Alerts"+ assert parse_qs(parsed.query) == {+ "startTime": ["2026-06-15T06:00:00.000Z"],+ "endTime": ["2026-06-15T12:00:00.000Z"],+ }++ @freeze_time("2026-06-15T12:00:00Z")+ def test_compliance_search_includes_dataset(self) -> None:+ session = _FakeSession([_FakeResponse(200, {"data": [], "paging": {}})])+ _collect_rows(+ session,+ "compliance_evaluations_aws",+ 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"++ @freeze_time("2026-06-15T12:00:00Z")+ def test_full_refresh_uses_default_lookback(self) -> None:+ # agent_info: 7-day lookback with 7-day windows -> exactly one request window.+ session = _FakeSession([_FakeResponse(200, {"data": [{"mid": 1}], "paging": {}})])+ rows = _collect_rows(session, "agent_info", should_use_incremental_field=False)++ assert rows == [{"mid": 1}]+ assert len(session.data_calls) == 1+ _method, _url, body, _headers = session.data_calls[0]+ assert body is not None and body["timeFilter"] == {+ "startTime": "2026-06-08T12:00:00.000Z",+ "endTime": "2026-06-15T12:00:00.000Z",+ }++ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_watermark_yields_nothing(self) -> None:+ session = _FakeSession([])+ rows = _collect_rows(+ session,+ "alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2027, 1, 1, tzinfo=UTC),+ )++ assert rows == []+ assert session.data_calls == []+++class TestGetRowsPagination:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_follows_next_page_and_checkpoints_after_yield(self) -> None:+ next_url = "https://mycompany.lacework.net/api/v2/Alerts/AbCdEf123"+ session = _FakeSession(+ [+ _FakeResponse(200, {"data": [{"alertId": 1}], "paging": {"urls": {"nextPage": next_url}}}),+ _FakeResponse(200, {"data": [{"alertId": 2}], "paging": {}}),+ ]+ )+ manager = _FakeResumableManager()+ rows = _collect_rows(+ session,+ "alerts",+ manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )++ assert [r["alertId"] for r in rows] == [1, 2]+ method, url, body, _headers = session.data_calls[1]+ assert (method, url, body) == ("GET", next_url, None)+ assert manager.saved == [+ LaceworkResumeConfig(+ window_start="2026-06-15T06:00:00.000Z",+ window_end="2026-06-15T12:00:00.000Z",+ next_page_url=next_url,+ )+ ]++ @freeze_time("2026-06-15T12:00:00Z")+ def test_next_page_on_foreign_host_is_not_followed(self) -> None:+ session = _FakeSession(+ [+ _FakeResponse(+ 200,+ {"data": [{"alertId": 1}], "paging": {"urls": {"nextPage": "https://evil.com/api/v2/steal"}}},+ )+ ]+ )+ rows = _collect_rows(+ session,+ "alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )++ assert [r["alertId"] for r in rows] == [1]+ assert len(session.data_calls) == 1++ @freeze_time("2026-06-15T12:00:00Z")+ def test_resume_continues_from_saved_window_and_page(self) -> None:+ resume_url = "https://mycompany.lacework.net/api/v2/Alerts/ResumeToken"+ manager = _FakeResumableManager(+ LaceworkResumeConfig(+ window_start="2026-06-15T00:00:00.000Z",+ window_end="2026-06-15T06:00:00.000Z",+ next_page_url=resume_url,+ )+ )+ session = _FakeSession(+ [+ _FakeResponse(200, {"data": [{"alertId": 1}], "paging": {}}),+ _FakeResponse(200, {"data": [{"alertId": 2}], "paging": {}}),+ ]+ )+ rows = _collect_rows(+ session,+ "alerts",+ manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 10, tzinfo=UTC),+ )++ assert [r["alertId"] for r in rows] == [1, 2]+ # First request resumes the in-flight page, then pagination continues into the next+ # window (06:00 -> now) instead of restarting from the stale watermark.+ assert session.data_calls[0][:2] == ("GET", resume_url)+ parsed = urlparse(session.data_calls[1][1])+ assert parse_qs(parsed.query) == {+ "startTime": ["2026-06-15T06:00:00.000Z"],+ "endTime": ["2026-06-15T12:00:00.000Z"],+ }+ # The next window was checkpointed once the resumed window finished paging.+ assert manager.saved == [+ LaceworkResumeConfig(+ window_start="2026-06-15T06:00:00.000Z",+ window_end="2026-06-15T12:00:00.000Z",+ next_page_url=None,+ )+ ]++ @freeze_time("2026-06-15T12:00:00Z")+ def test_resume_url_on_foreign_host_is_ignored(self) -> None:+ manager = _FakeResumableManager(+ LaceworkResumeConfig(+ window_start="2026-06-15T06:00:00.000Z",+ window_end="2026-06-15T12:00:00.000Z",+ next_page_url="https://evil.com/api/v2/steal",+ )+ )+ session = _FakeSession([_FakeResponse(200, {"data": [{"alertId": 1}], "paging": {}})])+ rows = _collect_rows(+ session,+ "alerts",+ manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 10, tzinfo=UTC),+ )++ assert [r["alertId"] for r in rows] == [1]+ method, url, _body, _headers = session.data_calls[0]+ assert method == "GET"+ assert urlparse(url).hostname == "mycompany.lacework.net"++ @freeze_time("2026-06-15T12:00:00Z")+ def test_204_no_data_yields_nothing(self) -> None:+ session = _FakeSession([_FakeResponse(204, None)])+ rows = _collect_rows(+ session,+ "alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )++ assert rows == []+++class TestAuth:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_token_exchanged_once_and_sent_as_bearer(self) -> None:+ next_url = "https://mycompany.lacework.net/api/v2/Alerts/AbCdEf123"+ session = _FakeSession(+ [+ _FakeResponse(200, {"data": [{"alertId": 1}], "paging": {"urls": {"nextPage": next_url}}}),+ _FakeResponse(200, {"data": [{"alertId": 2}], "paging": {}}),+ ]+ )+ _collect_rows(+ session,+ "alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )++ assert session.token_calls == 1+ for _method, _url, _body, headers in session.data_calls:+ assert headers["Authorization"] == "Bearer tok-123"++ @freeze_time("2026-06-15T12:00:00Z")+ def test_token_exchange_is_excluded_from_sample_capture(self) -> None:+ # The X-LW-UAKS request header and the response's generic `token` field are not caught by+ # the name-based sample scrubbers, so the auth session must opt out of capture and redact+ # the secret; without this an operator-enabled capture rule would persist credentials.+ session = _FakeSession([_FakeResponse(200, {"data": [], "paging": {}})])+ 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="alerts",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )+ )++ uncaptured = [c for c in mock_make.call_args_list if c.kwargs.get("capture") is False]+ assert len(uncaptured) == 1+ assert uncaptured[0].kwargs.get("redact_values") == ("secret",)++ mock_validate_session = MagicMock()+ mock_validate_session.post.return_value = _FakeResponse(201, {"token": "tok"})+ with patch(f"{_LACEWORK_MODULE}.make_tracked_session", return_value=mock_validate_session) as mock_make:+ validate_credentials("mycompany", "KEY_ID", "secret")+ assert mock_make.call_args.kwargs.get("capture") is False+ assert mock_make.call_args.kwargs.get("redact_values") == ("secret",)++ @freeze_time("2026-06-15T12:00:00Z")+ def test_retries_on_429_using_retry_after(self) -> None:+ session = _FakeSession(+ [+ _FakeResponse(429, {"message": "rate limited"}, headers={"Retry-After": "0"}),+ _FakeResponse(200, {"data": [{"alertId": 1}], "paging": {}}),+ ]+ )+ rows = _collect_rows(+ session,+ "alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )++ assert [r["alertId"] for r in rows] == [1]+ assert len(session.data_calls) == 2++ @freeze_time("2026-06-15T12:00:00Z")+ def test_result_set_row_cap_is_logged(self) -> None:+ session = _FakeSession(+ [_FakeResponse(200, {"data": [{"alertId": 1}], "paging": {"rows": 5000, "totalRows": 500_000}})]+ )+ logger = MagicMock()+ with patch(f"{_LACEWORK_MODULE}.make_tracked_session", return_value=session):+ list(+ get_rows(+ account_name="mycompany",+ key_id="KEY_ID",+ secret_key="secret",+ endpoint="alerts",+ logger=logger,+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 15, 6, 0, tzinfo=UTC),+ )+ )++ assert any("row cap" in str(call) for call in logger.warning.call_args_list)+++class TestLaceworkSourceResponse:+ @parameterized.expand(+ [+ ("alerts", ["alertId"], ["startTime"]),+ ("vulnerabilities_hosts", None, ["startTime"]),+ ("compliance_evaluations_gcp", None, ["reportTime"]),+ ("audit_logs", None, ["createdTime"]),+ ("agent_info", None, None),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, expected_primary_keys: list[str] | None, expected_partition_keys: list[str] | None+ ) -> None:+ response = lacework_source(+ account_name="mycompany",+ key_id="KEY_ID",+ secret_key="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.partition_keys == expected_partition_keys+ # Windowed results arrive in no documented order, so the watermark must only persist at+ # successful job end.+ assert response.sort_mode == "desc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework_source.pynew file mode 100644index 000000000000..a13229d3dcfa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework_source.py@@ -0,0 +1,118 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LaceworkSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.lacework import LaceworkResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.settings import (+ ENDPOINTS,+ LACEWORK_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lacework.source import LaceworkSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.lacework.source"+++class TestLaceworkSource:+ def setup_method(self) -> None:+ self.source = LaceworkSource()+ self.config = LaceworkSourceConfig(account_name="mycompany", key_id="KEY_ID", secret_key="secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.LACEWORK++ def test_source_is_released_as_alpha(self) -> None:+ config = self.source.get_source_config+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_source_config_fields(self) -> None:+ fields = {f.name: f for f in self.source.get_source_config.fields}+ assert list(fields.keys()) == ["account_name", "key_id", "secret_key"]+ assert all(isinstance(f, SourceFieldInputConfig) and f.required for f in fields.values())+ secret_key_field = fields["secret_key"]+ account_name_field = fields["account_name"]+ assert isinstance(secret_key_field, SourceFieldInputConfig)+ assert isinstance(account_name_field, SourceFieldInputConfig)+ assert secret_key_field.secret is True+ assert account_name_field.secret is False++ def test_account_name_is_a_connection_host_field(self) -> None:+ # Retargeting the account (and therefore the host the secret is sent to) must force the+ # editor to re-enter credentials.+ assert self.source.connection_host_fields == ["account_name"]++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert [s.name for s in schemas] == list(ENDPOINTS)++ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_get_schemas_flags_match_endpoint_settings(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)+ endpoint_config = LACEWORK_ENDPOINTS[endpoint]+ assert schema.supports_incremental == endpoint_config.supports_incremental+ assert schema.supports_append == endpoint_config.supports_append+ assert [f["field"] for f in schema.incremental_fields] == [+ f["field"] for f in endpoint_config.incremental_fields+ ]++ def test_only_alerts_supports_merge_sync(self) -> None:+ # Only alerts has a unique row id (alertId); merge sync on any other endpoint would+ # multi-match rows and corrupt the table.+ incremental = [s.name for s in self.source.get_schemas(self.config, team_id=1) if s.supports_incremental]+ assert incremental == ["alerts"]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["alerts", "audit_logs"])+ assert {s.name for s in schemas} == {"alerts", "audit_logs"}++ @parameterized.expand([(True, None), (False, "Invalid Lacework API key ID or secret key")])+ def test_validate_credentials_delegates_to_transport(self, ok: bool, message: str | None) -> None:+ with patch(f"{_SOURCE_MODULE}.validate_lacework_credentials", return_value=(ok, message)) as mock_validate:+ assert self.source.validate_credentials(self.config, team_id=1) == (ok, message)+ mock_validate.assert_called_once_with("mycompany", "KEY_ID", "secret")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LaceworkResumeConfig++ @parameterized.expand([(True,), (False,)])+ def test_source_for_pipeline_plumbs_inputs(self, should_use_incremental_field: bool) -> None:+ inputs = MagicMock()+ inputs.schema_name = "alerts"+ inputs.should_use_incremental_field = should_use_incremental_field+ inputs.db_incremental_field_last_value = "2026-06-15T06:00:00Z"+ manager = MagicMock()++ with patch(f"{_SOURCE_MODULE}.lacework_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["account_name"] == "mycompany"+ assert kwargs["key_id"] == "KEY_ID"+ assert kwargs["secret_key"] == "secret"+ assert kwargs["endpoint"] == "alerts"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field+ expected_value = "2026-06-15T06:00:00Z" if should_use_incremental_field else None+ assert kwargs["db_incremental_field_last_value"] == expected_value++ @parameterized.expand(+ [+ ("401 Client Error",),+ ("403 Client Error",),+ ("Invalid Lacework account name",),+ ]+ )+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)