: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(warehouse-sources): add drata task, failure, policy and requirement tables (#105925)
Tom Owersd18343df1ef7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 1487cdc34b28..7c4df6d83072 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2624,11 +2624,11 @@ Today (14): `assets`, `controls`, `devices`, `events`, `evidence_library`, `framDiffed against: <https://developers.drata.com/page-data/openapi/reference/v2/tag/Assets/page-data.json>-- [ ] `GET /workspaces/{workspaceId}/framework-requirements` — the requirement catalogue each synced framework is composed of — without it frameworks are opaque IDs (high)+- [x] `GET /workspaces/{workspaceId}/framework-requirements` — the requirement catalogue each synced framework is composed of — without it frameworks are opaque IDs (high)- [ ] `GET /workspaces/{workspaceId}/controls/{controlId}/requirements` — control↔requirement mapping, the junction that makes compliance coverage queryable (high)-- [ ] `GET /workspaces/{workspaceId}/monitoring-tests/{testId}/failures` — test failure history — the headline continuous-monitoring metric; monitoring_tests today gives only current state (high)-- [ ] `GET /workspaces/{workspaceId}/tasks` — remediation tasks with owners and due dates; the core operational work queue (high)-- [ ] `GET /users/{userId}/assigned-policies` — policy acceptance per user — the compliance metric auditors ask for; policies sync but attestation does not (high)+- [x] `GET /workspaces/{workspaceId}/monitoring-tests/{testId}/failures` — test failure history — the headline continuous-monitoring metric; monitoring_tests today gives only current state (high)+- [x] `GET /workspaces/{workspaceId}/tasks` — remediation tasks with owners and due dates; the core operational work queue (high)+- [x] `GET /users/{userId}/assigned-policies` — policy acceptance per user — the compliance metric auditors ask for; policies sync but attestation does not (high)- [ ] `GET /roles and GET /roles/{roleId}/users` — role lookup plus role↔user membership for the already-synced users table (medium)- [ ] `GET /workspaces/{workspaceId}/audits` — audit engagements that scope frameworks and evidence (medium)- [ ] `GET /workspaces/{workspaceId}/audits/{auditId}/requests` — auditor evidence requests and their fulfillment state (medium)diff --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.pyindex 701718680901..98cc86c37217 100644--- 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.py@@ -150,6 +150,25 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updatedAt": "When the test was last updated.",},},+ "monitoring_test_failures": {+ "description": "Findings behind each failing monitoring test: one row per cloud resource that failed a test, including findings excluded from the test result.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Monitoring-Tests/",+ "columns": {+ "workspaceId": "Identifier of the workspace the monitoring test belongs to (added by PostHog).",+ "monitoringTestId": "Identifier of the monitoring test that flagged the resource (added by PostHog).",+ "id": "Identifier of the cloud resource that failed the test, as reported by the provider.",+ "status": "Whether the finding still counts against the test (OPEN) or is excluded from it (EXCLUDED).",+ "providerName": "Cloud provider the failing resource belongs to, e.g. Amazon Web Services.",+ "resourceName": "Name of the failing resource, e.g. a security group or bucket name.",+ "accountName": "Cloud account or subscription the failing resource belongs to.",+ "clientId": "Identifier of the cloud account, subscription, or project holding the resource.",+ "resourceArn": "Full provider resource identifier, such as an AWS ARN.",+ "organizationalUnitId": "Organizational unit grouping the cloud account, where the provider has one.",+ "region": "Region or availability zone the failing resource runs in.",+ "tags": "Provider resource tags, as a key/value map.",+ "cause": "Rule evaluation entries explaining why the resource failed the test.",+ },+ },"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/",@@ -178,6 +197,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updatedAt": "When the framework was last updated.",},},+ "framework_requirements": {+ "description": "The requirement catalogue behind each framework enabled in a workspace, so framework rows resolve to the individual requirements they are made of.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Frameworks/",+ "columns": {+ "workspaceId": "Identifier of the workspace the requirement belongs to (added by PostHog).",+ "id": "Unique identifier for the requirement.",+ "name": "Name of the requirement.",+ "description": "Description of the requirement.",+ "longDescription": "Long-form description of the requirement.",+ "frameworkName": "Name of the framework the requirement belongs to.",+ "frameworkSlug": "Slug of the framework the requirement belongs to.",+ "frameworkTag": "Tag of the framework the requirement belongs to, e.g. SOC_2.",+ "frameworkPill": "Short label Drata shows for the framework.",+ "category": "Category grouping the requirement within a custom framework.",+ "externalId": "Identifier the framework itself gives this requirement.",+ "rationale": "Reason recorded for marking the requirement out of scope.",+ "additionalInfo": "Additional information about the requirement.",+ "additionalInfo2": "Second additional information field for the requirement.",+ "additionalInfo3": "Third additional information field for the requirement.",+ "archivedAt": "When the requirement was marked out of scope, if it was.",+ "createdAt": "When the requirement was created.",+ "updatedAt": "When the requirement was last updated.",+ },+ },+ "tasks": {+ "description": "Remediation tasks in each workspace, with owner, status, and due date. This is the compliance work queue.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/Tasks/",+ "columns": {+ "workspaceId": "Identifier of the workspace the task belongs to (added by PostHog).",+ "id": "Unique identifier for the task.",+ "title": "Title of the task.",+ "description": "Description of the task.",+ "status": "Task status: PAST_DUE, COMPLETED, or INCOMPLETE.",+ "taskType": "Type of the task.",+ "dueDate": "When the task is due.",+ "completedAt": "When the task was completed, if it was.",+ "assigneeId": "Identifier of the user the task is assigned to.",+ "createdById": "Identifier of the user who created the task.",+ "createdAt": "When the task was created.",+ "updatedAt": "When the task was last updated.",+ },+ },+ "user_assigned_policies": {+ "description": "Policy versions assigned to each user and whether they accepted them. This is the policy attestation record auditors ask for.",+ "docs_url": "https://developers.drata.com/openapi/reference/v2/tag/User's-Assigned-Policies/",+ "columns": {+ "userId": "Identifier of the user the policy is assigned to (added by PostHog).",+ "id": "Unique identifier for the user's assigned policy version.",+ "policyId": "Identifier of the assigned policy.",+ "policyVersionId": "Identifier of the assigned policy version.",+ "acceptedAt": "When the user accepted the policy version. Null means they have not accepted it yet.",+ "sourceType": "Where the acceptance was recorded.",+ "details": "How and where the user acknowledged the policy.",+ "createdAt": "When the policy version was assigned to the user.",+ "updatedAt": "When the assignment 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/",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.pyindex 47973690b2d6..e947505808d5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/drata.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/drata.py@@ -14,7 +14,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfind_values,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -152,7 +155,7 @@ def _client_config(api_key: str, region: str) -> ClientConfig:def _base_params(config: DrataEndpointConfig) -> dict[str, Any]:# An explicit stable creation-order sort keeps cursor pages consistent while rows are inserted# mid-sync.- return {"sort": config.sort, "sortDir": "ASC", PAGE_SIZE_PARAM: config.page_size}+ return {"sort": config.sort, "sortDir": "ASC", PAGE_SIZE_PARAM: config.page_size, **config.extra_params}def _top_level_resource(@@ -211,54 +214,77 @@ def _top_level_resource()+def _parent_chain(config: DrataEndpointConfig) -> list[DrataEndpointConfig]:+ """Ancestor-first chain, from the top-level endpoint down to ``config``."""+ chain: list[DrataEndpointConfig] = []+ node: Optional[DrataEndpointConfig] = config+ while node is not None:+ chain.append(node)+ node = DRATA_ENDPOINTS[node.fan_out_parent] if node.fan_out_parent else None+ chain.reverse()+ return chain+++def _top_level_endpoint_resource(config: DrataEndpointConfig) -> EndpointResource:+ return {+ "name": config.name,+ "endpoint": {+ "path": config.path,+ "params": _base_params(config),+ "data_selector": "data",+ },+ }+++def _fan_out_child_endpoint_resource(config: DrataEndpointConfig) -> EndpointResource:+ parent = config.fan_out_parent+ assert parent is not None and config.fan_out_parent_id_column is not None+ # Parent row field -> column it lands under on each child row. Child rows don't carry their+ # ancestor ids natively, and child ids aren't documented as unique beyond their parent, so+ # these columns are what the composite primary keys are built from.+ parent_columns = {"id": config.fan_out_parent_id_column, **config.fan_out_extra_parent_columns}++ def inject_parent_columns(row: dict[str, Any]) -> dict[str, Any]:+ for parent_field, column in parent_columns.items():+ key = f"_{parent}_{parent_field}"+ if key in row:+ row[column] = row.pop(key)+ return row++ params: dict[str, Any] = {+ placeholder: {"type": "resolve", "resource": parent, "field": parent_field}+ for placeholder, parent_field in config.fan_out_path_params.items()+ }+ params.update(_base_params(config))++ return {+ "name": config.name,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": "data",+ # A parent deleted between enumeration and this fetch 404s; skip it and continue+ # rather than failing the whole sync — its children are genuinely gone.+ "response_actions": [{"status_code": 404, "action": "ignore"}],+ },+ "include_from_parent": list(parent_columns),+ "data_map": inject_parent_columns,+ }++def _fan_out_resource(api_key: str,region: str,config: DrataEndpointConfig,resumable_source_manager: ResumableSourceManager[DrataResumeConfig],) -> 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_key = f"_{config.fan_out_parent}_id"- parent_id_column = config.fan_out_parent_id_column-- def inject_parent_id(row: dict[str, Any]) -> dict[str, Any]:- # Child rows don't carry their parent id natively; rename the framework's include_from_parent- # column to the camelCase column the composite ["<parent>Id", "id"] primary key expects.- if parent_key in row:- row[parent_id_column] = row.pop(parent_key)- return row-- child_params: dict[str, Any] = {- "parent_id": {"type": "resolve", "resource": config.fan_out_parent, "field": "id"},- **_base_params(config),- }-+ chain = _parent_chain(config)rest_config: RESTAPIConfig = {"client": _client_config(api_key, region),"resource_defaults": {},"resources": [- {- "name": config.fan_out_parent,- "endpoint": {- "path": parent_config.path,- "params": _base_params(parent_config),- "data_selector": "data",- },- },- {- "name": config.name,- "endpoint": {- "path": config.path,- "params": child_params,- "data_selector": "data",- # A parent deleted between enumeration and this fetch 404s; skip it and continue- # rather than failing the whole sync — its children are genuinely gone.- "response_actions": [{"status_code": 404, "action": "ignore"}],- },- "include_from_parent": ["id"],- "data_map": inject_parent_id,- },+ _top_level_endpoint_resource(chain[0]),+ *(_fan_out_child_endpoint_resource(node) for node in chain[1:]),],}@@ -271,6 +297,8 @@ def _fan_out_resource(def save_checkpoint(state: Optional[dict[str, Any]]) -> None:resumable_source_manager.save_state(DrataResumeConfig(fanout_state=state))+ # A chain with more than one fan-out level gets no resume: the framework refuses to feed one+ # hook to several levels, so those endpoints restart and the merge dedupes.resources = rest_api_resources(rest_config,0,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.pyindex 3edb2a0a9560..b7825a3efbf3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drata/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drata/settings.py@@ -13,7 +13,7 @@ _CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = []-@dataclass+@dataclass(frozen=True)class DrataEndpointConfig:name: str# Path template; fan-out endpoints carry a `{parent_id}` placeholder.@@ -24,6 +24,13 @@ class DrataEndpointConfig:# 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+ # Path placeholder -> parent row field that fills it. The default binds the single+ # `{parent_id}` placeholder to the parent's `id`; a child nested two levels deep binds one+ # placeholder per ancestor id carried on the parent row.+ fan_out_path_params: dict[str, str] = field(default_factory=lambda: {"parent_id": "id"})+ # Further parent row fields copied onto each child row -> the column they land under. Used by+ # deeper fan-outs whose primary key needs a grandparent id too.+ fan_out_extra_parent_columns: dict[str, str] = field(default_factory=dict)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"@@ -36,6 +43,8 @@ class DrataEndpointConfig:sort: str = "createdAt"# Results per page; the v2 API allows 1-500 (default 50).page_size: int = 250+ # Extra query params sent on every request to this endpoint.+ extra_params: dict[str, str] = field(default_factory=dict)# 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@@ -53,6 +62,13 @@ DRATA_ENDPOINTS: dict[str, DrataEndpointConfig] = {name="users",path="/users",),+ "user_assigned_policies": DrataEndpointConfig(+ name="user_assigned_policies",+ path="/users/{parent_id}/assigned-policies",+ fan_out_parent="users",+ fan_out_parent_id_column="userId",+ primary_keys=["userId", "id"],+ ),"personnel": DrataEndpointConfig(name="personnel",path="/personnel",@@ -94,6 +110,32 @@ DRATA_ENDPOINTS: dict[str, DrataEndpointConfig] = {fan_out_parent_id_column="workspaceId",primary_keys=["workspaceId", "id"],),+ "monitoring_test_failures": DrataEndpointConfig(+ name="monitoring_test_failures",+ # `{parent_id}` binds the parent's `testId`, not its `id`: Drata documents `id` as an+ # internal record identifier no public endpoint accepts.+ path="/workspaces/{workspaceId}/monitoring-tests/{parent_id}/failures",+ fan_out_parent="monitoring_tests",+ fan_out_parent_id_column="monitoringTestId",+ fan_out_path_params={"parent_id": "testId", "workspaceId": "workspaceId"},+ fan_out_extra_parent_columns={"workspaceId": "workspaceId"},+ # A failure row is one cloud resource failing one test; `id` is the provider's resource id,+ # unique only within the test that flagged it.+ primary_keys=["workspaceId", "monitoringTestId", "id"],+ # Failure rows carry no timestamp at all, so there is nothing stable to partition on.+ partition_key=None,+ # Excluded findings are omitted by default; keep them so the `status` column tells the+ # whole story instead of the row silently disappearing when someone dismisses it. Tags+ # only arrive when asked for, and they are what attributes a failing resource to a team.+ extra_params={"includeExclusions": "true", "expand[]": "tags"},+ ),+ "tasks": DrataEndpointConfig(+ name="tasks",+ path="/workspaces/{parent_id}/tasks",+ 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",@@ -108,6 +150,13 @@ DRATA_ENDPOINTS: dict[str, DrataEndpointConfig] = {fan_out_parent_id_column="workspaceId",primary_keys=["workspaceId", "id"],),+ "framework_requirements": DrataEndpointConfig(+ name="framework_requirements",+ path="/workspaces/{parent_id}/framework-requirements",+ fan_out_parent="workspaces",+ fan_out_parent_id_column="workspaceId",+ primary_keys=["workspaceId", "id"],+ ),"risk_registers": DrataEndpointConfig(name="risk_registers",path="/risk-registers",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.pyindex aae421a53729..3839f6919f0b 100644--- 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.py@@ -355,17 +355,58 @@ class TestWorkspaceFanOut:with pytest.raises(requests.HTTPError):_run(mock_session, route, "controls", _FakeManager())+ @parameterized.expand(+ [+ ("risks", "risks", "/risk-registers", "/risk-registers/5/risks", "riskRegisterId"),+ ("assigned_policies", "user_assigned_policies", "/users", "/users/5/assigned-policies", "userId"),+ ]+ )@mock.patch(CLIENT_SESSION_PATCH)- def test_risks_fan_out_over_risk_registers(self, mock_session: mock.MagicMock) -> None:+ def test_children_of_other_parents_inject_their_own_parent_column(+ self,+ _name: str,+ endpoint: str,+ parent_path: str,+ child_path: str,+ parent_column: str,+ mock_session: mock.MagicMock,+ ) -> None:def route(url: str, params: dict[str, Any]) -> Response:- if url.endswith("/risk-registers"):+ if url.endswith(parent_path):return _resp({"data": [{"id": 5}], "pagination": {"cursor": None}})- if url.endswith("/risk-registers/5/risks"):- return _resp({"data": [{"id": 1, "riskId": "RISK-001"}], "pagination": {"cursor": None}})+ if url.endswith(child_path):+ return _resp({"data": [{"id": 1}], "pagination": {"cursor": None}})raise AssertionError(f"unexpected url {url}")- rows, _ = _run(mock_session, route, "risks", _FakeManager())- assert rows == [{"id": 1, "riskId": "RISK-001", "riskRegisterId": 5}]+ rows, _ = _run(mock_session, route, endpoint, _FakeManager())+ assert rows == [{"id": 1, parent_column: 5}]+++class TestMonitoringTestFailureFanOut:+ """Failures hang two fan-out levels deep: workspaces -> monitoring tests -> failures."""++ def _route(self, url: str, params: dict[str, Any]) -> Response:+ if url.endswith("/workspaces"):+ return _resp({"data": [{"id": 10}], "pagination": {"cursor": None}})+ if url.endswith("/workspaces/10/monitoring-tests"):+ return _resp({"data": [{"id": 501, "testId": 77}], "pagination": {"cursor": None}})+ if url.endswith("/workspaces/10/monitoring-tests/77/failures"):+ return _resp({"data": [{"id": "bucket-1", "status": "OPEN"}], "pagination": {"cursor": None}})+ raise AssertionError(f"unexpected url {url}")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_request_binds_test_id_and_keeps_excluded_findings(self, mock_session: mock.MagicMock) -> None:+ rows, calls = _run(mock_session, self._route, "monitoring_test_failures", _FakeManager())+ # Drata documents the monitoring test's `id` as internal and rejects it on this path; only+ # `testId` resolves, so binding the wrong field would 404 every test.+ assert calls[-1]["url"] == f"{US_BASE_URL}/workspaces/10/monitoring-tests/77/failures"+ # Without includeExclusions a finding vanishes when someone dismisses it, instead of+ # staying put with status EXCLUDED. Tags arrive only when expanded.+ assert calls[-1]["params"]["includeExclusions"] == "true"+ assert calls[-1]["params"]["expand[]"] == "tags"+ # Both ancestor ids ride along so ["workspaceId", "monitoringTestId", "id"] stays unique:+ # `id` is only the provider's resource id, and one resource fails many tests.+ assert rows == [{"id": "bucket-1", "status": "OPEN", "monitoringTestId": 501, "workspaceId": 10}]class TestErrorHandling:@@ -493,7 +534,16 @@ class TestDrataSourceResponse:assert response.name == endpointassert response.primary_keys == DRATA_ENDPOINTS[endpoint].primary_keys- @parameterized.expand([("controls",), ("monitoring_tests",), ("evidence_library",), ("frameworks",)])+ @parameterized.expand(+ [+ ("controls",),+ ("monitoring_tests",),+ ("evidence_library",),+ ("frameworks",),+ ("framework_requirements",),+ ("tasks",),+ ]+ )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.@@ -510,3 +560,9 @@ class TestDrataSourceResponse:@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"++ def test_monitoring_test_failures_are_not_partitioned(self) -> None:+ # Failure rows carry no timestamp, so partitioning would key on a column that never lands.+ response = self._response("monitoring_test_failures")+ assert response.partition_mode is None+ assert response.partition_keys is None