:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 4 missing tables to the Secureframe source (#117458)
Tom Owers96addae03b65
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 dcefc07441eb..4355717c77ee 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@@ -10587,10 +10587,10 @@ Today (13): `cloud_resources`, `controls`, `devices`, `framework_requirements`,Diffed against: <https://developer.secureframe.com/>-- [ ] `poam_items (GET /poam_items)` — Plan of Action & Milestones — the open remediation backlog with owners and due dates (high)-- [ ] `framework_asset_scopes (GET /devices/{id}/framework_asset_scopes, /cloud_resources/{id}/…, /repositories/{id}/…)` — the join that says which framework each already-synced asset is in scope for; without it assets can't be filtered by framework (high)-- [ ] `ssp_policies (GET /ssp_policies)` — the policy inventory, a compliance object with no equivalent in the current tables (medium)-- [ ] `comments (GET /comments)` — remediation discussion attached to controls, tests and risks — the activity trail (medium)+- [x] `poam_items (GET /poam_items)` — Plan of Action & Milestones — the open remediation backlog with owners and due dates (high)+- [x] `framework_asset_scopes (GET /devices/{id}/framework_asset_scopes, /cloud_resources/{id}/…, /repositories/{id}/…)` — the join that says which framework each already-synced asset is in scope for; without it assets can't be filtered by framework (high)+- [x] `ssp_policies (GET /ssp_policies)` — the policy inventory, a compliance object with no equivalent in the current tables (medium)+- [x] `comments (GET /comments)` — remediation discussion attached to controls, tests and risks — the activity trail (medium)- [ ] `trust_center_requests (GET /trust_center_requests)` — inbound access requests to the trust center, a demand signal worth trending (medium)- [ ] `ssp_report_assessment_objectives (GET /ssp_report_assessment_objectives)` — per-objective assessment results underpinning control status (medium)- [ ] `ssp_reports (GET /ssp_reports)` — System Security Plan report headers, the parent for all ssp\_\* sections (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/canonical_descriptions.pyindex dd6ac78d978a..ddbe3c0cd1bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/canonical_descriptions.py@@ -315,4 +315,64 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "The date this CloudResource was last updated.",},},+ "poam_items": {+ "description": "A Plan of Action and Milestones (POA&M) item: an open security weakness with its remediation plan, owner, risk level and due dates.",+ "docs_url": "https://developer.secureframe.com/",+ "columns": {+ "id": "The identifier for this POA&M item.",+ "created_at": "The date when this POA&M item was created.",+ "discarded_at": "The date when this POA&M item was discarded, if any.",+ "due_date": "The due date of the POA&M item.",+ "estimated_completion_date": "The estimated completion date of the POA&M item.",+ "identifier": "The identifier of the POA&M item.",+ "issue": "The issue describing the POA&M item.",+ "owner_id": "The ID of the user who owns this POA&M item.",+ "remediation_plan": "The remediation plan for the POA&M item.",+ "risk_level": "The risk level of the POA&M item.",+ "status": "The status of the POA&M item.",+ "updated_at": "The date when this POA&M item was last updated.",+ },+ },+ "ssp_policies": {+ "description": "A policy recorded in a System Security Plan (SSP) report, linked to the control that it supports.",+ "docs_url": "https://developer.secureframe.com/",+ "columns": {+ "id": "The identifier for this SSP policy.",+ "control_id": "The identifier for the associated control.",+ "created_at": "The date when this SSP policy was created.",+ "name": "The name of the SSP policy.",+ "owner": "The owner of the SSP policy.",+ "ssp_report_id": "The identifier for the associated SSP report.",+ "summary": "The summary of the SSP policy.",+ "updated_at": "The date when this SSP policy was updated.",+ },+ },+ "comments": {+ "description": "A comment that a user left on a compliance object, such as a control, test, risk or POA&M item.",+ "docs_url": "https://developer.secureframe.com/",+ "columns": {+ "id": "The identifier for this comment.",+ "commentable_id": "The identifier for the commentable object.",+ "commentable_type": "The type of the commentable object.",+ "created_at": "The date when this comment was created.",+ "content": "The content of the comment.",+ "updated_at": "The date when this comment was updated.",+ },+ },+ "framework_asset_scopes": {+ "description": "The scope of one asset (a device, cloud resource or repository) for one compliance framework.",+ "docs_url": "https://developer.secureframe.com/",+ "columns": {+ "id": "The identifier for this framework asset scope.",+ "active": "Flag to indicate if this asset is in scope for this framework.",+ "asset_id": "The identifier of the asset.",+ "asset_type": "The type of the asset.",+ "created_at": "The date the framework asset scope was created.",+ "framework_id": "The identifier of the framework.",+ "framework_title": "The title of the framework.",+ "manually_scoped": "Flag to indicate if this asset is manually scoped.",+ "manually_scoped_reason": "Reason if this asset is manually scoped.",+ "updated_at": "The date when the framework asset scope was last updated.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/secureframe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/secureframe.pyindex cab28fd89282..9533393591ad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/secureframe.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/secureframe.py@@ -1,22 +1,31 @@-import dataclasses+from collections.abc import Callable, Iterator+from functools import partialfrom typing import Any, Optionalfrom urllib.parse import urlencodeimport requestsfrom requests import Response+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,+ rest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (PageNumberPaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom 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-from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.settings import SECUREFRAME_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.settings import (+ SECUREFRAME_ENDPOINTS,+ SecureframeEndpointConfig,+)BASE_URLS = {"us": "https://api.secureframe.com",@@ -28,9 +37,12 @@ PAGE_SIZE = 100REQUEST_TIMEOUT_SECONDS = 60+@frozenclass SecureframeResumeConfig:- page: int+ page: int = 1+ # Fan-out endpoints only: the parent kind in progress and its fan-out state.+ parent: Optional[str] = None+ fanout_state: Optional[dict[str, Any]] = Nonedef _base_url(region: str) -> str:@@ -130,6 +142,13 @@ class SecureframePaginator(PageNumberPaginator):super().update_state(response, rows)+def _probe_paths(config: SecureframeEndpointConfig) -> list[str]:+ # A fan-out child has no list of its own, so probe the parent lists that it reads.+ if config.fanout_parents:+ return [SECUREFRAME_ENDPOINTS[parent].path for parent in config.fanout_parents]+ return [config.path]++def _probe_endpoint(session: requests.Session, region: str, path: str) -> int:"""Fetch a single row from an endpoint and return the HTTP status code."""params = {"page": 1, "per_page": 1}@@ -148,7 +167,7 @@ def validate_credentials(api_key: str, api_secret: str, region: str, endpoint: sacceptable (users may only grant the scopes they intend to sync), so callers get bothsignals. Any other failure counts as unauthenticated."""- path = SECUREFRAME_ENDPOINTS[endpoint].path if endpoint else "/users"+ path = _probe_paths(SECUREFRAME_ENDPOINTS[endpoint])[0] if endpoint else "/users"url = f"{_base_url(region)}{path}?{urlencode({'page': 1, 'per_page': 1})}"_ok, status = validate_via_probe(lambda: _make_session(api_key, api_secret), url, timeout=REQUEST_TIMEOUT_SECONDS)@@ -167,22 +186,130 @@ def get_endpoint_permissions(api_key: str, api_secret: str, region: str, endpoinif config is None:permissions[endpoint] = Nonecontinue- try:- status = _probe_endpoint(session, region, config.path)- except Exception:- # A throttle, 5xx, or network blip is not a denial — report reachable.- permissions[endpoint] = None- continue- if status in (401, 403):- permissions[endpoint] = (- f"Your API key's role does not have permission to read {endpoint}. "- "Update the role's permissions in Secureframe, or deselect this table."- )- else:- permissions[endpoint] = None+ permissions[endpoint] = None+ for path in _probe_paths(config):+ try:+ status = _probe_endpoint(session, region, path)+ except Exception:+ # A throttle, 5xx, or network blip is not a denial — report reachable.+ continue+ if status in (401, 403):+ permissions[endpoint] = (+ f"Your API key's role does not have permission to read {endpoint}. "+ "Update the role's permissions in Secureframe, or deselect this table."+ )+ breakreturn permissions+def _fanout_child_resource(+ client_config: ClientConfig,+ endpoint: str,+ config: SecureframeEndpointConfig,+ parent: str,+ team_id: int,+ job_id: str,+ resume_hook: Callable[[Optional[dict[str, Any]]], None],+ initial_state: Optional[dict[str, Any]],+) -> Resource:+ parent_path = SECUREFRAME_ENDPOINTS[parent].path+ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [+ {+ "name": parent,+ "endpoint": {"path": parent_path, "params": {"per_page": PAGE_SIZE}},+ "data_map": _map_row,+ },+ {+ "name": endpoint,+ "endpoint": {+ "path": f"{parent_path}/{{parent_id}}{config.path}",+ "params": {"parent_id": {"type": "resolve", "resource": parent, "field": "id"}},+ # The per-asset list takes no page params and returns every row at once.+ "paginator": "single_page",+ # An asset deleted after the parent list was read has nothing left to sync.+ "response_actions": [{"status_code": 404, "action": "ignore"}],+ },+ "data_map": _map_row,+ },+ ],+ }+ resources = rest_api_resources(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=resume_hook,+ initial_paginator_state=initial_state,+ )+ return next(resource for resource in resources if resource.name == endpoint)+++def _iter_fanout_pages(+ children: list[tuple[str, Resource]],+ stage_parent: Callable[[str], None],+) -> Iterator[list[dict[str, Any]]]:+ for index, (parent, child) in enumerate(children):+ if index > 0:+ # Every row of the earlier parent kinds is already handed on, so a resume starts here.+ stage_parent(parent)+ yield from child+++def _fanout_source(+ client_config: ClientConfig,+ endpoint: str,+ config: SecureframeEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SecureframeResumeConfig],+) -> SourceResponse:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ parents = config.fanout_parents+ start = parents.index(resume.parent) if resume is not None and resume.parent in parents else 0++ def stage_parent(parent: str, state: Optional[dict[str, Any]] = None) -> None:+ resumable_source_manager.save_state(SecureframeResumeConfig(parent=parent, fanout_state=state))++ children = [+ (+ parent,+ _fanout_child_resource(+ client_config,+ endpoint,+ config,+ parent,+ team_id,+ job_id,+ resume_hook=partial(stage_parent, parent),+ initial_state=resume.fanout_state if resume is not None and index == start else None,+ ),+ )+ for index, parent in enumerate(parents)+ if index >= start+ ]+ # The wrapper hands each page on unchanged and holds no rows. As a `Resource` it keeps the+ # framework's checkpoints and safe points.+ resource = Resource(+ partial(_iter_fanout_pages, children, stage_parent),+ name=endpoint,+ hints=children[0][1]._hints,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=[config.primary_key],+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ 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,+ )++def secureframe_source(api_key: str,api_secret: str,@@ -193,15 +320,19 @@ def secureframe_source(resumable_source_manager: ResumableSourceManager[SecureframeResumeConfig],) -> SourceResponse:config = SECUREFRAME_ENDPOINTS[endpoint]+ client_config: ClientConfig = {+ "base_url": _base_url(region),+ # A capture=False, credential-redacting session (see _make_session); the auth header+ # rides on it rather than the framework `auth` config.+ "session": _make_session(api_key, api_secret),+ "paginator": SecureframePaginator(base_page=1),+ }++ if config.fanout_parents:+ return _fanout_source(client_config, endpoint, config, team_id, job_id, resumable_source_manager)rest_config: RESTAPIConfig = {- "client": {- "base_url": _base_url(region),- # A capture=False, credential-redacting session (see _make_session); the auth header- # rides on it rather than the framework `auth` config.- "session": _make_session(api_key, api_secret),- "paginator": SecureframePaginator(base_page=1),- },+ "client": client_config,"resource_defaults": {},"resources": [{diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/settings.pyindex c76795b81eee..0bd8fefb0704 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/settings.py@@ -1,10 +1,11 @@-from dataclasses import dataclassfrom typing import Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField-@dataclass+@frozenclass SecureframeEndpointConfig:name: strpath: str@@ -12,6 +13,9 @@ class SecureframeEndpointConfig:# Stable creation-time field used for datetime partitioning. Never an updated_at-style# field, which would rewrite partitions on every sync.partition_key: Optional[str] = None+ # Parent endpoints that each own a child list at `{parent path}/{parent id}{path}`. The rows of+ # every parent kind land in this one table.+ fanout_parents: tuple[str, ...] = ()# Every list endpoint in the Secureframe public API paginates with `page`/`per_page`@@ -84,6 +88,29 @@ SECUREFRAME_ENDPOINTS: dict[str, SecureframeEndpointConfig] = {path="/cloud_resources",partition_key="created_at",),+ "poam_items": SecureframeEndpointConfig(+ name="poam_items",+ path="/poam_items",+ partition_key="created_at",+ ),+ "ssp_policies": SecureframeEndpointConfig(+ name="ssp_policies",+ path="/ssp_policies",+ partition_key="created_at",+ ),+ "comments": SecureframeEndpointConfig(+ name="comments",+ path="/comments",+ partition_key="created_at",+ ),+ # Secureframe lists framework scopes only per asset, so this fans out over every device, cloud+ # resource and repository. Each row carries its own asset_type and asset_id.+ "framework_asset_scopes": SecureframeEndpointConfig(+ name="framework_asset_scopes",+ path="/framework_asset_scopes",+ partition_key="created_at",+ fanout_parents=("devices", "cloud_resources", "repositories"),+ ),}ENDPOINTS = tuple(SECUREFRAME_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe.pyindex d0fd41087e4a..d2c66dec8019 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe.py@@ -8,6 +8,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesScriptedResponse,SourceDriver,always,+ route,scripted_network,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.secureframe import (@@ -30,6 +31,14 @@ def _response(payload: Any, status_code: int = 200) -> ScriptedResponse:return ScriptedResponse(status=status_code, json=payload)+def _envelopes(*rows: dict[str, Any]) -> ScriptedResponse:+ return _response({"data": [{"id": row["id"], "type": "x", "attributes": row} for row in rows]})+++def _scope(scope_id: str, asset_id: str, asset_type: str) -> dict[str, Any]:+ return {"id": scope_id, "asset_id": asset_id, "asset_type": asset_type, "framework_id": "fw-1"}++class TestExtractRows:@pytest.mark.parametrize("payload, expected",@@ -91,6 +100,85 @@ class TestPagination:assert result.saved_states == []+class TestFrameworkAssetScopesFanout:+ def test_walks_every_parent_kind_and_skips_deleted_assets(self):+ result = _driver().run(+ "framework_asset_scopes",+ route(+ {+ "/devices": [_envelopes({"id": "d1"}, {"id": "d2"}), _response({"data": []})],+ "/devices/d1/framework_asset_scopes": [+ _envelopes(_scope("s1", "d1", "Device"), _scope("s2", "d1", "Device"))+ ],+ # The asset was deleted after the device list was read.+ "/devices/d2/framework_asset_scopes": [_response({"error": "not found"}, status_code=404)],+ "/cloud_resources": [_envelopes({"id": "c1"}), _response({"data": []})],+ "/cloud_resources/c1/framework_asset_scopes": [_envelopes(_scope("s3", "c1", "CloudResource"))],+ "/repositories": [_response({"data": []})],+ }+ ),+ )++ assert result.raised is None+ assert [row["id"] for row in result.rows] == ["s1", "s2", "s3"]+ assert result.rows[0] == _scope("s1", "d1", "Device")+ child_requests = [r for r in result.requests if r.path.endswith("/framework_asset_scopes")]+ assert [r.param("page") for r in child_requests] == [None, None, None]+ assert result.paths[-1] == "/repositories"++ @pytest.mark.parametrize(+ "resume_state, expected_paths",+ [+ (+ SecureframeResumeConfig(+ parent="cloud_resources",+ fanout_state={+ "completed": ["/cloud_resources/c1/framework_asset_scopes"],+ "current": None,+ "child_state": None,+ },+ ),+ ["/cloud_resources", "/cloud_resources/c2/framework_asset_scopes", "/cloud_resources", "/repositories"],+ ),+ (+ SecureframeResumeConfig(parent="repositories"),+ ["/repositories"],+ ),+ ],+ )+ def test_resumes_at_the_saved_parent_kind(self, resume_state, expected_paths):+ result = _driver().run(+ "framework_asset_scopes",+ route(+ {+ "/cloud_resources": [_envelopes({"id": "c1"}, {"id": "c2"}), _response({"data": []})],+ "/cloud_resources/c2/framework_asset_scopes": [_envelopes(_scope("s4", "c2", "CloudResource"))],+ "/repositories": [_response({"data": []})],+ }+ ),+ resume_state=resume_state,+ )++ assert result.raised is None+ assert result.paths == expected_paths++ def test_stages_the_next_parent_kind_once_the_previous_one_is_done(self):+ result = _driver().run(+ "framework_asset_scopes",+ route(+ {+ "/devices": [_envelopes({"id": "d1"}), _response({"data": []})],+ "/devices/d1/framework_asset_scopes": [_envelopes(_scope("s1", "d1", "Device"))],+ "/cloud_resources": [_response({"data": []})],+ "/repositories": [_response({"data": []})],+ }+ ),+ )++ assert SecureframeResumeConfig(parent="cloud_resources") in result.saved_states+ assert SecureframeResumeConfig(parent="repositories") in result.saved_states++class TestValidateCredentials:@pytest.mark.parametrize("status_code, expected",@@ -117,6 +205,15 @@ class TestGetEndpointPermissions:assert permissions["tests"] is not Noneassert "tests" in permissions["tests"]+ @pytest.mark.parametrize("denied_parent_index", [0, 1, 2])+ def test_fanout_table_is_denied_when_any_parent_list_is_denied(self, denied_parent_index):+ statuses = [200, 200, 200]+ statuses[denied_parent_index] = 403+ with scripted_network([ScriptedResponse(status=status, json={}) for status in statuses]):+ permissions = get_endpoint_permissions("key", "secret", "us", ["framework_asset_scopes"])++ assert permissions["framework_asset_scopes"] is not None+def test_transient_failures_are_not_denials(self):with scripted_network(always(ConnectionError("connection reset"))):assert get_endpoint_permissions("key", "secret", "us", ["controls"]) == {"controls": None}