: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 drata import source (#71213)
Tom Owers2267bf712aa1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d57bbfc88179..d673fa9a42f7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -164,6 +164,7 @@ the row lists both.| dockerhub | HTTP | requests | ✅ || docuseal | HTTP | requests | ✅ || doit | HTTP | requests | ✅ |+| drata | HTTP | requests | ✅ || dropbox_sign | HTTP | requests | ✅ || drip | HTTP | requests | ✅ || e2b | HTTP | requests | ✅ |@@ -633,7 +634,6 @@ doesn't conflict with concurrent PRs.- dodopayments- dolibarr- doppler-- drata- dremio- dropbox- dubdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/canonical_descriptions.pynew file mode 100644index 000000000000..701718680901--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/canonical_descriptions.py@@ -0,0 +1,209 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "workspaces": {+ "description": "Workspaces (products) in your Drata account. Controls, monitoring tests, evidence, and frameworks are scoped to a workspace.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Workspaces/",+ "columns": {+ "id": "Unique identifier for the workspace.",+ "primary": "Whether this is the account's primary workspace.",+ "name": "Name of the workspace.",+ "description": "Description of the workspace.",+ "url": "URL of the product the workspace represents.",+ "createdAt": "When the workspace was created.",+ "updatedAt": "When the workspace was last updated.",+ },+ },+ "users": {+ "description": "User accounts in your Drata organization.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Users-and-Roles/",+ "columns": {+ "id": "Unique identifier for the user.",+ "email": "Email address of the user.",+ "firstName": "First name of the user.",+ "lastName": "Last name of the user.",+ "jobTitle": "Job title of the user.",+ "createdAt": "When the user was created.",+ "updatedAt": "When the user was last updated.",+ },+ },+ "personnel": {+ "description": "Personnel records tracked for compliance, including employment status and per-person compliance checks (security training, background checks, MDM).",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Personnel/",+ "columns": {+ "id": "Unique identifier for the personnel record.",+ "userId": "Identifier of the user this personnel record belongs to.",+ "employmentStatus": "Employment status, e.g. CURRENT_EMPLOYEE, FORMER_EMPLOYEE, CURRENT_CONTRACTOR.",+ "startedAt": "When this person started employment.",+ "separatedAt": "When this person separated, if applicable.",+ "createdAt": "When the personnel record was created.",+ "updatedAt": "When the personnel record was last updated.",+ },+ },+ "devices": {+ "description": "Devices monitored for compliance (encryption, firewall, antivirus, screen lock) across MDM and agent sources.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Devices/",+ "columns": {+ "id": "Unique identifier for the device.",+ "personnelId": "Identifier of the personnel record the device belongs to.",+ "serialNumber": "Serial number of the device.",+ "macAddress": "MAC address of the device.",+ "model": "Hardware model of the device.",+ "osVersion": "Operating system version of the device.",+ "sourceType": "Where the device record came from, e.g. AGENT, JAMF, INTUNE, KANDJI.",+ "createdAt": "When the device record was created.",+ "updatedAt": "When the device record was last updated.",+ },+ },+ "assets": {+ "description": "Assets in your Drata asset inventory — physical and virtual assets discovered from connections or added manually.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Assets/",+ "columns": {+ "id": "Unique identifier for the asset.",+ "name": "Name of the asset.",+ "description": "Description of the asset.",+ "assetType": "Whether the asset is PHYSICAL or VIRTUAL.",+ "assetProvider": "Provider the asset was discovered from, e.g. AWS, AZURE, GCP, AGENT.",+ "externalId": "Identifier of the asset in the provider's system.",+ "removedAt": "When the asset was removed, if applicable.",+ "createdAt": "When the asset record was created.",+ "updatedAt": "When the asset record was last updated.",+ },+ },+ "vendors": {+ "description": "Vendors tracked in Drata's vendor risk management, with risk, impact, and review status.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Vendors/",+ "columns": {+ "id": "Unique identifier for the vendor.",+ "name": "Name of the vendor.",+ "category": "Business category of the vendor, e.g. ENGINEERING, FINANCE, SECURITY.",+ "status": "Lifecycle status of the vendor, e.g. ACTIVE, ARCHIVED, UNDER_REVIEW.",+ "type": "Relationship type, e.g. VENDOR, SUPPLIER, CONTRACTOR, PARTNER.",+ "risk": "Assessed risk level of the vendor: NONE, LOW, MODERATE, or HIGH.",+ "impactLevel": "Assessed business impact of the vendor, e.g. MINOR, MODERATE, CRITICAL.",+ "hasPii": "Whether the vendor accesses or processes personally identifiable information.",+ "renewalDate": "When the vendor contract renews.",+ "createdAt": "When the vendor record was created.",+ "updatedAt": "When the vendor record was last updated.",+ },+ },+ "policies": {+ "description": "Policies in your Drata account, including version, approval, and renewal state.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Policies/",+ "columns": {+ "id": "Unique identifier for the policy.",+ "name": "Name of the policy.",+ "description": "Description of the policy.",+ "status": "Status of the policy, e.g. ACTIVE, ARCHIVED, OUTDATED.",+ "version": "Current major version of the policy.",+ "currentVersionId": "Identifier of the currently published policy version.",+ "renewalDate": "When the policy is next due for review.",+ "publishedAt": "When the current version was published.",+ "approvedAt": "When the current version was approved.",+ "createdAt": "When the policy was created.",+ },+ },+ "events": {+ "description": "Audit-trail events recording activity across your Drata account (policy changes, vendor updates, connection activity, and more).",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Events/",+ "columns": {+ "id": "Unique identifier (UUID) for the event.",+ "type": "Specific event type, e.g. COMPANY_DATA_UPDATED.",+ "category": "Area of the product the event belongs to, e.g. POLICY, VENDOR, RISK.",+ "source": "What produced the event, e.g. APP, AUTOPILOT, PUBLIC_API, SCHEDULED.",+ "description": "Human-readable description of the event.",+ "userId": "Identifier of the user associated with the event, if any.",+ "connectionId": "Identifier of the connection associated with the event, if any.",+ "createdAt": "When the event occurred.",+ },+ },+ "controls": {+ "description": "Controls in each workspace, with readiness, monitoring, and framework mappings.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Controls/",+ "columns": {+ "workspaceId": "Identifier of the workspace the control belongs to (added by PostHog).",+ "id": "Unique identifier for the control.",+ "name": "Name of the control.",+ "code": "Short code of the control, e.g. DCF-1001.",+ "description": "Description of what the control requires.",+ "archivedAt": "When the control was archived, if applicable.",+ "createdAt": "When the control was created.",+ "updatedAt": "When the control was last updated.",+ },+ },+ "monitoring_tests": {+ "description": "Automated monitoring tests in each workspace, with pass/fail status and check state.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Monitoring-Tests/",+ "columns": {+ "workspaceId": "Identifier of the workspace the test belongs to (added by PostHog).",+ "id": "Account-wide unique identifier for the monitoring test instance.",+ "testId": "Workspace-scoped identifier of the test, used in Drata API paths.",+ "name": "Name of the monitoring test.",+ "checkResultStatus": "Latest result of the test, e.g. PASSED, FAILED, ERROR.",+ "checkStatus": "Whether the test is ENABLED, DISABLED, NEW, or UNUSED.",+ "testSource": "Origin of the test, e.g. DRATA, CUSTOM, EXTERNAL.",+ "lastPassedAt": "When the test last passed.",+ "failedSince": "When the test started failing, if it is failing.",+ "createdAt": "When the test was created.",+ "updatedAt": "When the test was last updated.",+ },+ },+ "evidence_library": {+ "description": "Evidence library items in each workspace, tracking artifacts collected for audits and their renewal status.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Evidence-Library/",+ "columns": {+ "workspaceId": "Identifier of the workspace the evidence belongs to (added by PostHog).",+ "id": "Unique identifier for the evidence library item.",+ "name": "Name of the evidence item.",+ "description": "Description of the evidence item.",+ "createdAt": "When the evidence item was created.",+ "updatedAt": "When the evidence item was last updated.",+ },+ },+ "frameworks": {+ "description": "Compliance frameworks enabled in each workspace (SOC 2, ISO 27001, HIPAA, ...), with readiness counts.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Frameworks/",+ "columns": {+ "workspaceId": "Identifier of the workspace the framework belongs to (added by PostHog).",+ "id": "Unique identifier for the framework.",+ "name": "Name of the framework.",+ "tag": "Framework tag, e.g. SOC_2, ISO27001.",+ "isEnabled": "Whether the framework is enabled in the workspace.",+ "isReady": "Whether the framework is audit-ready.",+ "numInScopeControls": "Number of in-scope controls for the framework.",+ "numInScopeRequirements": "Number of in-scope requirements for the framework.",+ "createdAt": "When the framework was created.",+ "updatedAt": "When the framework was last updated.",+ },+ },+ "risk_registers": {+ "description": "Risk registers grouping the risks you track. Requires Drata's Risk Management Pro feature.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Risk-Registers/",+ "columns": {+ "id": "Unique identifier for the risk register.",+ "name": "Name of the risk register.",+ "description": "Description of the risk register.",+ "createdAt": "When the risk register was created.",+ "updatedAt": "When the risk register was last updated.",+ },+ },+ "risks": {+ "description": "Risks in each risk register, with scoring and treatment plans. Requires Drata's Risk Management Pro feature.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Risks/",+ "columns": {+ "riskRegisterId": "Identifier of the risk register the risk belongs to (added by PostHog).",+ "id": "Unique identifier for the risk within its register.",+ "riskId": "Human-readable risk code, e.g. RISK-001.",+ "title": "Title of the risk.",+ "status": "Status of the risk: ACTIVE, ARCHIVED, or CLOSED.",+ "treatmentPlan": "Treatment plan, e.g. UNTREATED, ACCEPT, MITIGATE.",+ "impact": "Assessed impact score of the risk.",+ "likelihood": "Assessed likelihood score of the risk.",+ "score": "Calculated risk score (impact × likelihood).",+ "createdAt": "When the risk was created.",+ "updatedAt": "When the risk was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/drata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/drata.pynew file mode 100644index 000000000000..7780d78496a2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/drata.py@@ -0,0 +1,369 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlsplit, urlunsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import 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.drata.settings import (+ DRATA_ENDPOINTS,+ DrataEndpointConfig,+)++# Drata hosts its public API per data-residency region; the user picks their region at connect time.+REGION_BASE_URLS: dict[str, str] = {+ "US": "https://public-api.drata.com/public/v2",+ "EU": "https://public-api.eu.drata.com/public/v2",+ "APAC": "https://public-api.apac.drata.com/public/v2",+}+DEFAULT_REGION = "US"+REQUEST_TIMEOUT_SECONDS = 60+# Cheap list probe used to confirm an API key is genuine. Any authenticated endpoint works; the+# workspaces list is small on every account.+PROBE_PATH = "/workspaces"+++class DrataRetryableError(Exception):+ pass+++class DrataResumeConfig:+ # Opaque `pagination.cursor` pointing at the page after the last one yielded. A crashed sync+ # resumes from there; merge dedupes the re-pulled page on the primary key.+ cursor: str | None = None+ # For fan-out endpoints: a stable id bookmark of the parent currently being processed (not a+ # positional index, so parents added/removed between a crash and the retry can't resume us into+ # the wrong parent). None for top-level endpoints.+ parent_id: int | None = None+++def base_url_for_region(region: str | None) -> str:+ return REGION_BASE_URLS.get((region or DEFAULT_REGION).upper(), REGION_BASE_URLS[DEFAULT_REGION])+++def _scrub_url(url: str | None) -> str:+ # Drop the query string before a URL reaches any error message or log line. The API key rides in+ # the Authorization header, but keeping cursors and filters out of persisted job errors is+ # cheap. The scheme/host/path stays intact so `get_non_retryable_errors()` can still match.+ if not url:+ return REGION_BASE_URLS[DEFAULT_REGION]+ parts = urlsplit(url)+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))+++def _format_incremental_value(value: Any) -> str:+ # Drata's date-time params take ISO 8601; normalize to UTC with a Z suffix to avoid ambiguity.+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return _format_incremental_value(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _build_incremental_params(+ config: DrataEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, str]:+ if not should_use_incremental_field or db_incremental_field_last_value is None:+ return {}++ field = incremental_field or config.default_incremental_field+ if field is None:+ return {}++ param = config.incremental_param_by_field.get(field)+ if param is None:+ raise ValueError(f"Drata endpoint '{config.name}' has no server-side filter for field '{field}'")++ return {param: _format_incremental_value(db_incremental_field_last_value)}+++@retry(+ retry=retry_if_exception_type((DrataRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(url, params=params or None, timeout=REQUEST_TIMEOUT_SECONDS)++ # Drata rate limits at 500 requests/minute per source IP; 429s and transient 5xx are retried+ # with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise DrataRetryableError(+ f"Drata API error (retryable): status={response.status_code}, url={_scrub_url(response.url)}"+ )++ if not response.ok:+ logger.error(+ f"Drata API error: status={response.status_code}, body={response.text}, url={_scrub_url(response.url)}"+ )+ # Raise with the query scrubbed from the URL rather than calling raise_for_status(), whose+ # message embeds the full request URL. The base host stays intact so+ # `get_non_retryable_errors()` can still match on it.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {_scrub_url(response.url)}",+ response=response,+ )++ data = response.json()+ # Every v2 list endpoint wraps its payload as {"data": [...], "pagination": {"cursor": ...}}.+ if not isinstance(data, dict) or "data" not in data:+ raise DrataRetryableError(f"Drata returned an unexpected payload for {_scrub_url(url)}: {type(data).__name__}")++ return data+++def _rows_from_body(body: dict[str, Any], url: str) -> list[dict[str, Any]]:+ data = body["data"]+ if not isinstance(data, list):+ raise DrataRetryableError(f"Drata returned a non-list payload for {_scrub_url(url)}: {type(data).__name__}")+ return data+++def _iter_pages(+ session: requests.Session,+ url: str,+ base_params: dict[str, Any],+ page_size: int,+ logger: FilteringBoundLogger,+ start_cursor: str | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Walk a cursor-paginated v2 list endpoint, yielding (rows, next_cursor) per page.++ The API returns `pagination.cursor` only while more pages exist; a missing/empty cursor (or a+ cursor that stops advancing) terminates the walk.+ """+ cursor = start_cursor++ while True:+ params = {**base_params, "size": page_size}+ if cursor:+ params["cursor"] = cursor++ body = _fetch_page(session, url, params, logger)+ items = _rows_from_body(body, url)++ pagination = body.get("pagination") or {}+ next_cursor = pagination.get("cursor")+ if not items or not next_cursor or next_cursor == cursor:+ yield items, None+ return++ yield items, next_cursor+ cursor = next_cursor+++def _list_parent_ids(+ session: requests.Session,+ base_url: str,+ parent_config: DrataEndpointConfig,+ logger: FilteringBoundLogger,+) -> list[int]:+ """Page through a fan-out parent endpoint and return every parent id, in creation order."""+ url = f"{base_url}{parent_config.path}"+ params = {"sort": parent_config.sort, "sortDir": "ASC"}+ ids: list[int] = []+ for items, _next_cursor in _iter_pages(session, url, params, parent_config.page_size, logger):+ ids.extend(item["id"] for item in items)+ return ids+++def _get_fan_out_rows(+ session: requests.Session,+ base_url: str,+ config: DrataEndpointConfig,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DrataResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ assert config.fan_out_parent is not None and config.fan_out_parent_id_column is not None+ parent_config = DRATA_ENDPOINTS[config.fan_out_parent]+ parent_ids = _list_parent_ids(session, base_url, parent_config, logger)++ # Resolve the saved parent-id bookmark to the slice of parents still to process. If the+ # bookmarked parent no longer exists (deleted between runs), start over from the first parent —+ # merge dedupes the re-pulled rows on the primary key. `resume_cursor` seeds the first parent+ # only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = parent_ids+ resume_cursor: str | None = None+ if resume is not None and resume.parent_id is not None and resume.parent_id in parent_ids:+ remaining = parent_ids[parent_ids.index(resume.parent_id) :]+ resume_cursor = resume.cursor+ logger.debug(f"Drata: resuming {config.name} from parent_id={resume.parent_id}, cursor={resume_cursor}")++ for index, parent_id in enumerate(remaining):+ url = f"{base_url}{config.path.format(parent_id=parent_id)}"+ start_cursor = resume_cursor+ resume_cursor = None++ try:+ for items, next_cursor in _iter_pages(session, url, base_params, config.page_size, logger, start_cursor):+ if items:+ yield [{**item, config.fan_out_parent_id_column: parent_id} for item in items]+ # Save AFTER yielding so a crash re-fetches the last page rather than skipping it;+ # merge dedupes the re-pulled rows on the primary key.+ if next_cursor:+ resumable_source_manager.save_state(DrataResumeConfig(cursor=next_cursor, parent_id=parent_id))+ except requests.HTTPError as exc:+ # A parent deleted between enumeration and this fetch 404s. Skip it rather than failing+ # the whole sync — its children are genuinely gone. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Drata: {config.fan_out_parent} {parent_id} not found while fetching {config.name}")+ else:+ raise++ # Advance the bookmark to the next parent so a crash between parents resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(DrataResumeConfig(cursor=None, parent_id=remaining[index + 1]))+++def _get_top_level_rows(+ session: requests.Session,+ url: str,+ config: DrataEndpointConfig,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DrataResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_cursor = resume.cursor if resume else None+ if start_cursor is not None:+ logger.debug(f"Drata: resuming {config.name} from cursor {start_cursor}")++ for items, next_cursor in _iter_pages(session, url, base_params, config.page_size, logger, start_cursor):+ if items:+ yield items+ # Save AFTER yielding so a crash re-fetches the last page rather than skipping it; merge+ # dedupes the re-pulled rows on the primary key.+ if next_cursor:+ resumable_source_manager.save_state(DrataResumeConfig(cursor=next_cursor))+++def get_rows(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DrataResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = DRATA_ENDPOINTS[endpoint]+ session = make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ )+ base_url = base_url_for_region(region)+ # An explicit stable creation-order sort keeps cursor pages consistent while rows are inserted+ # mid-sync.+ base_params: dict[str, Any] = {"sort": config.sort, "sortDir": "ASC"}+ base_params.update(+ _build_incremental_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ )++ if config.fan_out_parent:+ yield from _get_fan_out_rows(session, base_url, config, base_params, logger, resumable_source_manager)+ return++ url = f"{base_url}{config.path}"+ yield from _get_top_level_rows(session, url, config, base_params, logger, resumable_source_manager)+++def drata_source(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DrataResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = DRATA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Every request passes sort=createdAt&sortDir=ASC, but the ordering couldn't be verified+ # against a live account, so the incremental endpoint declares "desc": the pipeline then+ # commits the watermark only after a complete sync, which stays correct regardless of the+ # actual arrival order.+ sort_mode="desc" if config.incremental_fields else "asc",+ )+++def check_access(api_key: str, region: str, path: str = PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403``/``412`` auth-shaped statuses,+ ``0`` for a connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ )+ try:+ response = session.get(+ f"{base_url_for_region(region)}{path}", params={"size": 1}, timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception as e:+ return 0, f"Could not connect to Drata: {e}"++ if response.status_code in (401, 403, 412):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Drata returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, region: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key, region)+ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Drata API key"+ if status == 403:+ # The key is genuine but lacks the workspaces read scope. Custom-scoped keys may+ # legitimately only grant the endpoints the user wants to sync, so don't block+ # source-create on it; sync-time 403s are surfaced per table.+ return True, None+ if status == 412:+ return False, "You must accept the Drata API terms and conditions in your Drata account before connecting"+ return False, message or "Could not validate Drata API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/settings.pynew file mode 100644index 000000000000..3edb2a0a9560--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/settings.py@@ -0,0 +1,130 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++_CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class DrataEndpointConfig:+ name: str+ # Path template; fan-out endpoints carry a `{parent_id}` placeholder.+ path: str+ # Parent endpoint to walk for fan-out children (e.g. controls fan out over workspaces).+ fan_out_parent: Optional[str] = None+ # Column the parent's id is injected under on each child row (camelCase, matching the API).+ # Child rows don't carry their parent id natively, and child ids aren't documented as unique+ # beyond their parent, so fan-out primary keys must include this column.+ fan_out_parent_id_column: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp used for datetime partitioning (never an updated-at style field).+ partition_key: Optional[str] = "createdAt"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Maps an incremental field name to the server-side query param that filters on it.+ incremental_param_by_field: dict[str, str] = field(default_factory=dict)+ default_incremental_field: Optional[str] = None+ # `sort` value passed on every request. Every v2 list endpoint accepts `createdAt` (most also+ # accept `updatedAt`); a stable creation-order sort keeps cursor pages consistent mid-sync.+ sort: str = "createdAt"+ # Results per page; the v2 API allows 1-500 (default 50).+ page_size: int = 250+ # False leaves the table deselected by default in the schema picker. Used for the risk tables,+ # which are gated on Drata's Risk Management Pro feature and 403 on accounts without it.+ should_sync_default: bool = True+++# Drata public API v2 list endpoints (https://developers.drata.com/openapi/reference/v2/overview/).+# Only `events` exposes a server-side timestamp filter (`createdAtStartDate`), so it is the only+# incremental-capable endpoint; the rest are compliance inventories synced via full refresh.+DRATA_ENDPOINTS: dict[str, DrataEndpointConfig] = {+ "workspaces": DrataEndpointConfig(+ name="workspaces",+ path="/workspaces",+ ),+ "users": DrataEndpointConfig(+ name="users",+ path="/users",+ ),+ "personnel": DrataEndpointConfig(+ name="personnel",+ path="/personnel",+ ),+ "devices": DrataEndpointConfig(+ name="devices",+ path="/devices",+ ),+ "assets": DrataEndpointConfig(+ name="assets",+ path="/assets",+ ),+ "vendors": DrataEndpointConfig(+ name="vendors",+ path="/vendors",+ ),+ "policies": DrataEndpointConfig(+ name="policies",+ path="/policies",+ ),+ "events": DrataEndpointConfig(+ name="events",+ path="/events",+ incremental_fields=_CREATED_AT_INCREMENTAL_FIELDS,+ incremental_param_by_field={"createdAt": "createdAtStartDate"},+ default_incremental_field="createdAt",+ ),+ "controls": DrataEndpointConfig(+ name="controls",+ path="/workspaces/{parent_id}/controls",+ fan_out_parent="workspaces",+ fan_out_parent_id_column="workspaceId",+ primary_keys=["workspaceId", "id"],+ ),+ "monitoring_tests": DrataEndpointConfig(+ name="monitoring_tests",+ path="/workspaces/{parent_id}/monitoring-tests",+ fan_out_parent="workspaces",+ fan_out_parent_id_column="workspaceId",+ primary_keys=["workspaceId", "id"],+ ),+ "evidence_library": DrataEndpointConfig(+ name="evidence_library",+ path="/workspaces/{parent_id}/evidence-library",+ fan_out_parent="workspaces",+ fan_out_parent_id_column="workspaceId",+ primary_keys=["workspaceId", "id"],+ ),+ "frameworks": DrataEndpointConfig(+ name="frameworks",+ path="/workspaces/{parent_id}/frameworks",+ fan_out_parent="workspaces",+ fan_out_parent_id_column="workspaceId",+ primary_keys=["workspaceId", "id"],+ ),+ "risk_registers": DrataEndpointConfig(+ name="risk_registers",+ path="/risk-registers",+ should_sync_default=False,+ ),+ "risks": DrataEndpointConfig(+ name="risks",+ path="/risk-registers/{parent_id}/risks",+ fan_out_parent="risk_registers",+ fan_out_parent_id_column="riskRegisterId",+ primary_keys=["riskRegisterId", "id"],+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(DRATA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DRATA_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/source.pyindex 79fb6fe21ad8..d9d118f3d61d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/source.py@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.drata import (+ DrataResumeConfig,+ drata_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.settings import (+ DRATA_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DrataSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DrataSource(SimpleSource[DrataSourceConfig]):+class DrataSource(ResumableSource[DrataSourceConfig, DrataResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DRATA@@ -24,7 +50,110 @@ class DrataSource(SimpleSource[DrataSourceConfig]):name=SchemaExternalDataSourceType.DRATA,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Drata",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Drata API key to pull your compliance data into the PostHog Data warehouse.++You can create an API key under **Settings → API keys** in [Drata](https://app.drata.com/). A key with **read** scopes is sufficient; pick the region that matches your Drata account.+""",iconPath="/static/services/drata.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/drata",+ keywords=["compliance", "grc", "soc2", "audit"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Drata region",+ required=True,+ defaultValue="US",+ options=[+ SourceFieldSelectConfigOption(label="North America", value="US"),+ SourceFieldSelectConfigOption(label="Europe", value="EU"),+ SourceFieldSelectConfigOption(label="Asia-Pacific", value="APAC"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.drata.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The host varies by region (public-api.drata.com / public-api.eu.drata.com /+ # public-api.apac.drata.com), so match on the shared prefix.+ return {+ "401 Client Error: Unauthorized for url: https://public-api": "Your Drata API key is invalid or has expired. Create a new API key under Settings → API keys in Drata, then reconnect.",+ "403 Client Error: Forbidden for url: https://public-api": "Your Drata API key does not have permission to read this data. Grant the key the matching read scope in Drata, then reconnect.",+ "412 Client Error: Precondition Failed for url: https://public-api": "You must accept the Drata API terms and conditions in your Drata account before syncing.",+ }++ def get_schemas(+ self,+ config: DrataSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only events exposes a server-side timestamp filter (createdAtStartDate), so it is the+ # only endpoint that supports incremental sync.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=DRATA_ENDPOINTS[endpoint].should_sync_default,+ detected_primary_keys=DRATA_ENDPOINTS[endpoint].primary_keys,+ )+ 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: DrataSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide; one probe validates the token itself. Per-endpoint scopes+ # are surfaced at sync time via get_non_retryable_errors.+ return validate_credentials(config.api_key, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DrataResumeConfig]:+ return ResumableSourceManager[DrataResumeConfig](inputs, DrataResumeConfig)++ def source_for_pipeline(+ self,+ config: DrataSourceConfig,+ resumable_source_manager: ResumableSourceManager[DrataResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in DRATA_ENDPOINTS:+ raise ValueError(f"Unknown Drata schema '{inputs.schema_name}'")++ return drata_source(+ api_key=config.api_key,+ region=config.region,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/tests/test_drata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/tests/test_drata.pynew file mode 100644index 000000000000..b3385cfd6f29--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/tests/test_drata.py@@ -0,0 +1,408 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.drata import drata+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.drata import (+ REGION_BASE_URLS,+ DrataResumeConfig,+ DrataRetryableError,+ base_url_for_region,+ check_access,+ drata_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.settings import DRATA_ENDPOINTS, ENDPOINTS++US_BASE_URL = REGION_BASE_URLS["US"]++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = drata._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: DrataResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[DrataResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> DrataResumeConfig | None:+ return self._state++ def save_state(self, data: DrataResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager,+ fake_fetch: Any,+ endpoint: str,+ region: str = "US",+ **kwargs: Any,+) -> tuple[list[dict], list[dict[str, Any]]]:+ calls: list[dict[str, Any]] = []++ def _fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:+ calls.append({"url": url, "params": params})+ return fake_fetch(url, params)++ with (+ patch.object(drata, "_fetch_page", _fetch),+ patch.object(drata, "make_tracked_session", return_value=MagicMock()),+ ):+ rows: list[dict] = []+ for batch in get_rows(+ api_key="drata_key",+ region=region,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows, calls+++class TestTopLevelCursorPagination:+ def _pages(self, url: str, params: dict[str, Any]) -> dict[str, Any]:+ cursor = params.get("cursor")+ if cursor is None:+ return {"data": [{"id": 1}], "pagination": {"cursor": "c2", "totalCount": 2}}+ if cursor == "c2":+ return {"data": [{"id": 2}], "pagination": {"cursor": None, "totalCount": 2}}+ raise AssertionError(f"unexpected cursor {cursor}")++ def test_follows_cursor_until_absent(self) -> None:+ manager = _FakeResumableManager()+ rows, calls = _collect(manager, self._pages, "users")+ assert rows == [{"id": 1}, {"id": 2}]+ assert calls[0]["params"] == {"sort": "createdAt", "sortDir": "ASC", "size": 250}+ assert calls[1]["params"]["cursor"] == "c2"+ # State is saved once — after the first page, pointing at the next cursor — then we stop.+ assert [s.cursor for s in manager.saved] == ["c2"]++ def test_stops_when_cursor_does_not_advance(self) -> None:+ # An API that echoes the same cursor back must terminate, not loop forever.+ manager = _FakeResumableManager()++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ return {"data": [{"id": 1}], "pagination": {"cursor": params.get("cursor") or "c1"}}++ rows, calls = _collect(manager, pages, "users")+ assert [c["params"].get("cursor") for c in calls] == [None, "c1"]+ assert len(rows) == 2++ def test_resumes_from_saved_cursor(self) -> None:+ manager = _FakeResumableManager(DrataResumeConfig(cursor="c2"))+ rows, calls = _collect(manager, self._pages, "users")+ # The first page must never be re-fetched on resume.+ assert rows == [{"id": 2}]+ assert calls[0]["params"]["cursor"] == "c2"++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = _FakeResumableManager()++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ return {"data": [], "pagination": {"cursor": None}}++ rows, _ = _collect(manager, pages, "users")+ assert rows == []+ assert manager.saved == []++ @parameterized.expand([("US",), ("EU",), ("APAC",)])+ def test_requests_hit_the_selected_region_host(self, region: str) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(manager, lambda url, params: {"data": []}, "users", region=region)+ assert calls[0]["url"] == f"{REGION_BASE_URLS[region]}/users"+++class TestEventsIncremental:+ def _pages(self, url: str, params: dict[str, Any]) -> dict[str, Any]:+ cursor = params.get("cursor")+ if cursor is None:+ return {"data": [{"id": "e1"}], "pagination": {"cursor": "c2"}}+ return {"data": [{"id": "e2"}], "pagination": {"cursor": None}}++ def test_server_side_filter_sent_on_every_page(self) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(+ manager,+ self._pages,+ "events",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ incremental_field="createdAt",+ )+ for call in calls:+ assert call["params"]["createdAtStartDate"] == "2026-01-02T03:04:05.000Z"++ def test_date_watermark_formatted_as_utc_datetime(self) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(+ manager,+ self._pages,+ "events",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 2),+ incremental_field="createdAt",+ )+ assert calls[0]["params"]["createdAtStartDate"] == "2026-01-02T00:00:00.000Z"++ def test_unknown_incremental_field_raises(self) -> None:+ manager = _FakeResumableManager()+ with pytest.raises(ValueError, match="no server-side filter"):+ _collect(+ manager,+ self._pages,+ "events",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ incremental_field="updatedAt",+ )++ @parameterized.expand(+ [+ ("incremental_disabled", False, "2026-01-01"),+ ("no_last_value", True, None),+ ]+ )+ def test_no_filter_param_without_watermark(self, _name: str, should_use: bool, last_value: Any) -> None:+ manager = _FakeResumableManager()+ _, calls = _collect(+ manager,+ self._pages,+ "events",+ should_use_incremental_field=should_use,+ db_incremental_field_last_value=last_value,+ incremental_field="createdAt",+ )+ assert "createdAtStartDate" not in calls[0]["params"]+++class TestWorkspaceFanOut:+ def _pages(self, url: str, params: dict[str, Any]) -> dict[str, Any]:+ if url.endswith("/workspaces"):+ return {"data": [{"id": 10}, {"id": 20}], "pagination": {"cursor": None}}+ if url.endswith("/workspaces/10/controls"):+ if params.get("cursor") is None:+ return {"data": [{"id": 1}], "pagination": {"cursor": "w10c2"}}+ return {"data": [{"id": 2}], "pagination": {"cursor": None}}+ if url.endswith("/workspaces/20/controls"):+ return {"data": [{"id": 1}], "pagination": {"cursor": None}}+ raise AssertionError(f"unexpected url {url}")++ def test_walks_every_workspace_and_injects_workspace_id(self) -> None:+ manager = _FakeResumableManager()+ rows, _ = _collect(manager, self._pages, "controls")+ # Control id 1 appears in both workspaces; the injected workspaceId keeps the+ # ["workspaceId", "id"] primary key unique table-wide.+ assert rows == [+ {"id": 1, "workspaceId": 10},+ {"id": 2, "workspaceId": 10},+ {"id": 1, "workspaceId": 20},+ ]++ def test_saves_cursor_within_parent_and_bookmark_between_parents(self) -> None:+ manager = _FakeResumableManager()+ _collect(manager, self._pages, "controls")+ assert [(s.parent_id, s.cursor) for s in manager.saved] == [(10, "w10c2"), (20, None)]++ def test_resumes_from_parent_bookmark_without_refetching_earlier_parents(self) -> None:+ manager = _FakeResumableManager(DrataResumeConfig(cursor=None, parent_id=20))+ rows, calls = _collect(manager, self._pages, "controls")+ assert rows == [{"id": 1, "workspaceId": 20}]+ child_urls = [c["url"] for c in calls if "/controls" in c["url"]]+ assert child_urls == [f"{US_BASE_URL}/workspaces/20/controls"]++ def test_resume_cursor_applies_to_bookmarked_parent_only(self) -> None:+ manager = _FakeResumableManager(DrataResumeConfig(cursor="w10c2", parent_id=10))+ rows, calls = _collect(manager, self._pages, "controls")+ # Workspace 10 resumes mid-pagination; workspace 20 starts from its first page.+ assert rows == [{"id": 2, "workspaceId": 10}, {"id": 1, "workspaceId": 20}]+ first_child_call = next(c for c in calls if c["url"].endswith("/workspaces/10/controls"))+ assert first_child_call["params"]["cursor"] == "w10c2"++ def test_deleted_bookmark_parent_starts_over(self) -> None:+ manager = _FakeResumableManager(DrataResumeConfig(cursor="stale", parent_id=999))+ rows, _ = _collect(manager, self._pages, "controls")+ assert len(rows) == 3++ def test_parent_404_is_skipped_and_sync_continues(self) -> None:+ manager = _FakeResumableManager()+ response = MagicMock()+ response.status_code = 404++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ if url.endswith("/workspaces"):+ return {"data": [{"id": 10}, {"id": 20}], "pagination": {"cursor": None}}+ if url.endswith("/workspaces/10/controls"):+ raise requests.HTTPError("404 Client Error", response=response)+ return {"data": [{"id": 1}], "pagination": {"cursor": None}}++ rows, _ = _collect(manager, pages, "controls")+ assert rows == [{"id": 1, "workspaceId": 20}]++ def test_parent_403_fails_the_sync(self) -> None:+ manager = _FakeResumableManager()+ response = MagicMock()+ response.status_code = 403++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ if url.endswith("/workspaces"):+ return {"data": [{"id": 10}], "pagination": {"cursor": None}}+ raise requests.HTTPError("403 Client Error", response=response)++ with pytest.raises(requests.HTTPError):+ _collect(manager, pages, "controls")++ def test_risks_fan_out_over_risk_registers(self) -> None:+ manager = _FakeResumableManager()++ def pages(url: str, params: dict[str, Any]) -> dict[str, Any]:+ if url.endswith("/risk-registers"):+ return {"data": [{"id": 5}], "pagination": {"cursor": None}}+ if url.endswith("/risk-registers/5/risks"):+ return {"data": [{"id": 1, "riskId": "RISK-001"}], "pagination": {"cursor": None}}+ raise AssertionError(f"unexpected url {url}")++ rows, _ = _collect(manager, pages, "risks")+ assert rows == [{"id": 1, "riskId": "RISK-001", "riskRegisterId": 5}]+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.reason = "Unauthorized"+ # The error path must strip the query string before the URL reaches the exception message.+ response.url = f"{US_BASE_URL}/users?cursor=abc&size=250"+ response.json.return_value = body if body is not None else {"data": [], "pagination": {}}+ response.text = ""+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(DrataRetryableError):+ _fetch_page_unwrapped(session, f"{US_BASE_URL}/users", {}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("terms_not_accepted", 412)])+ def test_client_errors_raise_http_error_with_scrubbed_url(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError) as exc_info:+ _fetch_page_unwrapped(session, f"{US_BASE_URL}/users", {}, MagicMock())+ # The base URL stays so `get_non_retryable_errors()` can match; the query string must not+ # reach the persisted error message.+ message = str(exc_info.value)+ assert f"for url: {US_BASE_URL}/users" in message+ assert "?" not in message++ @parameterized.expand([("bare_list", [{"id": 1}]), ("missing_data", {"pagination": {}})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(DrataRetryableError):+ _fetch_page_unwrapped(session, f"{US_BASE_URL}/users", {}, MagicMock())+++class TestCredentialValidation:+ def _session(self, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ def _response(self, status: int) -> MagicMock:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ return response++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Drata API key"),+ # A genuine token without the workspaces read scope must not block source creation —+ # custom-scoped keys may only grant the endpoints the user wants to sync.+ ("forbidden_scope", 403, True, None),+ (+ "terms_not_accepted",+ 412,+ False,+ "You must accept the Drata API terms and conditions in your Drata account before connecting",+ ),+ ("server_error", 500, False, "Drata returned HTTP 500"),+ ]+ )+ def test_validate_credentials_status_mapping(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ with patch.object(drata, "make_tracked_session", return_value=self._session(self._response(status))):+ assert validate_credentials("drata_key", "US") == (expected_valid, expected_message)++ def test_connection_error_reports_message(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(drata, "make_tracked_session", return_value=session):+ valid, message = validate_credentials("drata_key", "US")+ assert valid is False+ assert message is not None and "boom" in message++ def test_check_access_probes_the_selected_region(self) -> None:+ session = self._session(self._response(200))+ with patch.object(drata, "make_tracked_session", return_value=session):+ check_access("drata_key", "EU")+ url = session.get.call_args.args[0]+ assert url == f"{REGION_BASE_URLS['EU']}/workspaces"++ @parameterized.expand(+ [("lowercase", "eu", "EU"), ("unknown_falls_back_to_us", "atlantis", "US"), ("none", None, "US")]+ )+ def test_base_url_for_region_normalizes(self, _name: str, region: str | None, expected: str) -> None:+ assert base_url_for_region(region) == REGION_BASE_URLS[expected]+++class TestDrataSourceResponse:+ def _response(self, endpoint: str):+ return drata_source(+ api_key="drata_key",+ region="US",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )++ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_primary_keys_match_endpoint_config(self, endpoint: str) -> None:+ response = self._response(endpoint)+ assert response.name == endpoint+ assert response.primary_keys == DRATA_ENDPOINTS[endpoint].primary_keys++ @parameterized.expand([("controls",), ("monitoring_tests",), ("evidence_library",), ("frameworks",)])+ def test_workspace_children_use_composite_primary_key(self, endpoint: str) -> None:+ # Child ids aren't documented as unique beyond their workspace; a bare ["id"] key would+ # multi-match on merge and duplicate rows across workspaces.+ assert self._response(endpoint).primary_keys == ["workspaceId", "id"]++ def test_events_partitions_on_stable_created_at_and_defers_watermark(self) -> None:+ response = self._response("events")+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]+ # The requested ASC ordering couldn't be verified against a live account, so the watermark+ # must only commit after a complete sync.+ assert response.sort_mode == "desc"++ @parameterized.expand([(e,) for e in ENDPOINTS if e != "events"])+ def test_full_refresh_endpoints_declare_asc(self, endpoint: str) -> None:+ assert self._response(endpoint).sort_mode == "asc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/tests/test_drata_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/tests/test_drata_source.pynew file mode 100644index 000000000000..6f86642cbe1c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/tests/test_drata_source.py@@ -0,0 +1,145 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.drata import DrataResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.drata.source import DrataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DrataSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestDrataSource:+ def setup_method(self) -> None:+ self.source = DrataSource()+ self.team_id = 123+ self.config = DrataSourceConfig(api_key="drata_key", region="EU")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DRATA++ def test_source_is_visible_with_alpha_release_status(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Drata"+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/drata"++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_region_field_offers_every_drata_region(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")+ assert field.defaultValue == "US"+ assert [o.value for o in field.options] == ["US", "EU", "APAC"]++ def test_get_schemas_covers_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_events_supports_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["events"].supports_incremental is True+ assert [f["field"] for f in schemas["events"].incremental_fields] == ["createdAt"]+ for name, schema in schemas.items():+ if name == "events":+ continue+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_feature_gated_risk_tables_are_deselected_by_default(self) -> None:+ # Risk endpoints 403 on accounts without Drata's Risk Management Pro feature; enabling them+ # by default would fail the first sync for most accounts.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["risk_registers"].should_sync_default is False+ assert schemas["risks"].should_sync_default is False+ assert schemas["controls"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["events", "nope"])+ assert [s.name for s in schemas] == ["events"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ # Exercises the placeholder-config path the public docs endpoint uses (no credentials).+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert tables["controls"]["primary_keys"] == ["workspaceId", "id"]++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://public-api.drata.com/public/v2/users",),+ ("403 Client Error: Forbidden for url: https://public-api.eu.drata.com/public/v2/risk-registers",),+ ("412 Client Error: Precondition Failed for url: https://public-api.apac.drata.com/public/v2/events",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures_in_every_region(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://public-api.drata.com/public/v2/users",),+ ("429 Client Error: Too Many Requests for url: https://public-api.drata.com/public/v2/events",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.drata.source.validate_credentials")+ def test_validate_credentials_passes_key_and_region(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Drata API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid Drata API key")+ mock_validate.assert_called_once_with("drata_key", "EU")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DrataResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.drata.source.drata_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "createdAt"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "drata_key"+ assert kwargs["region"] == "EU"+ assert kwargs["endpoint"] == "events"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "createdAt"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.drata.source.drata_source")+ def test_source_for_pipeline_drops_incremental_value_when_disabled(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Drata schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --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 72030e529c44..0a179d2635f0 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@@ -1260,7 +1260,8 @@ class DopplerSourceConfig(config.Config):@config.configclass DrataSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["US", "EU", "APAC"] = config.value(default="US")@config.config