Skip to content

: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.

feat(data-warehouse): implement secureframe import source (#71194)

Tom Owers7293511da16a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 09930ce27abd..1df503dca6fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -427,6 +427,7 @@ the row lists both.
| scale_ai | HTTP | requests | ✅ |
| scaleway | HTTP | requests | ✅ |
| secoda | HTTP | requests | ✅ |
+| secureframe | HTTP | requests | ✅ |
| segment | HTTP | requests | ✅ |
| semgrep | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
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.py
index 1c28c1da6901..2d5688e98430 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
@@ -3755,7 +3755,9 @@ class SecodaSourceConfig(config.Config):
@config.config
class SecureframeSourceConfig(config.Config):
- pass
+ api_key: str
+ api_secret: str
+ region: Literal["us", "uk"] = config.value(default="us")
@config.config
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.py
new file mode 100644
index 000000000000..dd6ac78d978a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/canonical_descriptions.py
@@ -0,0 +1,318 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Table and column descriptions sourced from the official Secureframe API reference
+# (https://developer.secureframe.com/).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "controls": {
+ "description": "A security control the company maintains to satisfy framework requirements, with aggregated test-health counts.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this control.",
+ "at_risk_test_count": "The number of associated tests currently at risk of failing.",
+ "author_name": "The name of the author if custom, Secureframe otherwise.",
+ "created_at": "The date the control was created.",
+ "custom": "True if the control is custom, false if it's Secureframe-authored.",
+ "description": "The control description.",
+ "disabled_justification": "The reason the control was disabled if applicable.",
+ "disabled_test_count": "The number of associated tests that are disabled.",
+ "enabled": "True if the control is currently enabled.",
+ "failing_test_count": "The number of associated tests currently failing.",
+ "first_failed_at": "The date the control first failed.",
+ "framework_ids": "The IDs of the frameworks that the control is associated with.",
+ "framework_keys": "The keys of the frameworks that the control is associated with.",
+ "framework_requirement_keys": "The keys of the framework requirements that the control is associated with.",
+ "health_status": "The overall health of the control.",
+ "implementation_date": "The date when the control is/was to be implemented.",
+ "implementation_status": "The current implementation status of the control.",
+ "key": "The user-friendly identifier used to reference this control.",
+ "name": "The control name.",
+ "owner_assigned_at": "The date the control was assigned to its current owner.",
+ "owner_name": "The control owner's name.",
+ "passing_test_count": "The number of associated tests currently passing.",
+ "updated_at": "The date when the control was last updated.",
+ },
+ },
+ "tests": {
+ "description": "A compliance test that continuously evaluates a control, with pass/fail health status and evidence timing.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this test.",
+ "control_ids": "The IDs of the controls that the test is associated with.",
+ "control_keys": "The keys of the controls that the test is associated with.",
+ "created_at": "The date when this test was created.",
+ "custom": "True if the test is custom (user generated), false if it's Secureframe-authored.",
+ "description": "The description for the test.",
+ "detailed_remediation_steps": "Guidance for remediating this test in the event it fails.",
+ "disabled_justification": "Reason for disabling the test.",
+ "enabled": "True if the test is currently enabled.",
+ "enabled_field_updated_by_user_name": "The name of the user who enabled the test, null if wasn't enabled by a user.",
+ "failure_message": "The message to be displayed if the test fails.",
+ "first_failed_at": "The date the test first failed.",
+ "framework_ids": "The IDs of the frameworks that the test is associated with.",
+ "framework_keys": "The keys of the frameworks that the test is associated with.",
+ "health_status": "The overall health of the test.",
+ "key": "The user-friendly identifier used to reference this test.",
+ "last_evaluated": "The date the test was last evaluated at.",
+ "last_passed_at": "The date the test last had a passing evaluation.",
+ "next_due_date": "The date new test evidence is needed by if applicable.",
+ "owner_assigned_at": "The date the test owner was assigned.",
+ "owner_name": "The test owner's name.",
+ "pass": "True if the test is passing, false otherwise.",
+ "passed_with_upload": "True if the test passed from the existance of an upload, false otherwise.",
+ "passed_with_upload_justification": "The justification used on evidence upload to pass the test if applicable.",
+ "promote_at": "The current date set for implementation of the test.",
+ "promoted_by_name": "The name of the user who set the implementation date.",
+ "recommended_action": "Actions for completing the test.",
+ "required_implementation_date": "The pre-configured date the test must be implemented by.",
+ "resource_category": "The category the test resource belongs to.",
+ "test_domain": "The domain the test belongs to.",
+ "test_function": "The purpose of the test.",
+ "test_interval_seconds": "The interval in which test evidence should be collected if applicable.",
+ "test_type": "The type of test.",
+ "title": "The test title.",
+ "tolerance_window_seconds": "The time between the test interval elapsing and evidence becoming stale and test failing if applicable.",
+ "updated_at": "The date the test was last updated.",
+ "vendor_name": "The vendor name associated with the test if applicable.",
+ },
+ },
+ "users": {
+ "description": "A person (employee, contractor, or other personnel) tracked for compliance, onboarding, and audit scope.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this user.",
+ "access_role": "The user's access role in the system.",
+ "active": "True if the user's account is active, false if it has been deactivated.",
+ "active_source": "The integration the active status was sourced from.",
+ "created_at": "The date when this user account was created.",
+ "department_id": "The identifier of the department the user belongs to.",
+ "email": "The user's email.",
+ "employee_type": "The type of employee (contractor, employee, non-employee etc).",
+ "end_date": "The date of the user's termination if applicable.",
+ "first_name": "The user's first name.",
+ "image_url": "The user's icon image URL.",
+ "in_audit_scope": "True if this user is in scope for being audited, false if they are exempt.",
+ "invited": "True if an invitation to Secureframe has been sent to the user's email, false otherwise.",
+ "invited_at": "The date the user was invited.",
+ "last_name": "The user's last name.",
+ "manager_name": "The name of the user's manager if applicable, null otherwise.",
+ "middle_name": "The user's middle name.",
+ "name": "The first and last name of the user separated by a space.",
+ "onboarding_status": "The current onboarding status of the user.",
+ "personnel_status": "The current personnel status of the user.",
+ "preferred_first_name": "The user's preferred first name if applicable, null otherwise.",
+ "role": "The user's role at the company.",
+ "secureframe_agent_acknowledged_at": "The date the user completed installation of the Secureframe device agent.",
+ "start_date": "The date the user started employment at the company.",
+ "title": "The user's job title.",
+ "updated_at": "The date this user account was last updated.",
+ },
+ },
+ "user_accounts": {
+ "description": "An account discovered on a connected vendor (e.g. a SaaS login), optionally linked to a Secureframe user.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this UserAccount.",
+ "active": "Flag to indicate if this is an active user account on the vendor side. Defaults to true if the vendor does not support or provide this value.",
+ "created_at": "The date this UserAccount was created.",
+ "email": "The email received from the connection.",
+ "first_name": "The first name of the user received from the connection.",
+ "has_user": "Flag to indicate if this UserAccount has a User. False indicates that it's an unlinked account.",
+ "last_name": "The last name of the user received from the connection.",
+ "third_party_id": "The identifier for this UserAccount on the vendor side.",
+ "username": "The user name of the UserAccount on the vendor side.",
+ "vendor_name": "The name of the vendor that this UserAccount is from.",
+ "updated_at": "The date this UserAccount was last updated.",
+ },
+ },
+ "devices": {
+ "description": "A managed device reporting security posture such as disk encryption, firewall, and antivirus status.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this Device.",
+ "created_at": "The date this Device object was created.",
+ "cpu": "The cpu info available for this Device.",
+ "device_name": "The name of the Device.",
+ "hard_drive_encrypted": "Flag to indicate if the hard drive is encrypted.",
+ "in_audit_scope": "Flag to indicate if this Device is in scope.",
+ "last_checkin_at": "The date this Device last checked in.",
+ "local_firewall_enabled": "Flag to indicate if the local firewall is enabled.",
+ "mac_address": "The MAC address of the Device.",
+ "make": "The make of the Device.",
+ "memory": "The memory of the Device.",
+ "model": "The model of the Device.",
+ "native_anti_virus_enabled": "Flag to indicate if the native antivirus is enabled.",
+ "os": "The operating system of the Device.",
+ "out_of_audit_scope_reason": "Out of scope reason if the Device is not in scope.",
+ "password_enforcement_enabled": "Flag to indicate if password enforcement is enabled.",
+ "remote_ip": "The remote IP of the Device.",
+ "serial_number": "The serial number of the Device.",
+ "session_timeout_enabled": "Flag to indicate if session timeout is enabled.",
+ "updated_at": "The date this Device was last updated.",
+ },
+ },
+ "vendors": {
+ "description": "A third-party vendor tracked in the legacy vendor register, with risk and review metadata.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this Vendor.",
+ "archived": "Flag to indicate if this Vendor is archived.",
+ "archived_at": "The date this Vendor was archived (if it is archived).",
+ "archived_by": "The identifier of the User that archived this Vendor (if it is archived).",
+ "audit_scopes": "The audit scopes for this Vendor.",
+ "authentication_type": "The authentication type for this Vendor.",
+ "data_collected": "The data collected for this Vendor.",
+ "date_of_engagement": "The date of engagement for this Vendor.",
+ "domain": "The domain of the Vendor.",
+ "environment_types": "The environment types for this Vendor.",
+ "last_reviewed_at": "The date this Vendor was last reviewed.",
+ "name": "The name of the Vendor.",
+ "operational_reliance": "The operational reliance for this Vendor.",
+ "other_information": "Other information for this Vendor.",
+ "owner_id": "The identifier of the User that is the owner for this Vendor.",
+ "risk_level": "The risk level for this Vendor.",
+ "security_url": "The security URL for this Vendor.",
+ "services": "The services provided by this Vendor.",
+ "terminated_at": "The date this Vendor was terminated (if it is archived).",
+ "third_party_audit_report_concerns": "The third party audit report concerns for this Vendor.",
+ "two_factor_enabled": "Flag to indicate if two factor is enabled for this Vendor.",
+ "updated_at": "The date this Vendor was last updated.",
+ },
+ },
+ "tprm_vendors": {
+ "description": "A vendor tracked in Third Party Risk Management, with risk level, status, and subassessment responses.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this Vendor.",
+ "archived": "Flag to indicate if this Vendor is archived.",
+ "archived_at": "The date this Vendor was archived.",
+ "authentication_type": "The authentication type for this Vendor.",
+ "created_at": "The date this Vendor was created.",
+ "data_collected": "The data collected for this Vendor.",
+ "environment_types": "The environments for this Vendor.",
+ "last_reviewed_at": "The date this Vendor was last reviewed.",
+ "name": "The name of the Vendor.",
+ "other_information": "Other information for this Vendor.",
+ "owner_id": "The identifier of the User that is the owner for this Vendor.",
+ "risk_level": "The risk level for this Vendor.",
+ "security_url": "The security URL for this Vendor.",
+ "services_provided": "The services provided by this Vendor.",
+ "third_party_audit_report_concerns": "The third party audit report concerns for this Vendor.",
+ "two_factor_enabled": "Flag to indicate if two factor is enabled for this Vendor.",
+ "updated_at": "The date this Vendor was last updated.",
+ "vendor_status": "The status of the Vendor.",
+ "vendor_risk_subassessment_responses": "The assesments for each risk subcategory.",
+ "website": "The website of the Vendor.",
+ },
+ },
+ "frameworks": {
+ "description": "A compliance framework (e.g. SOC 2, ISO 27001) with aggregate control and test counts.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this Framework.",
+ "applicable_controls_count": "The number of applicable controls for this Framework.",
+ "applicable_framework_requirements_count": "The number of applicable framework requirements for this Framework.",
+ "at_risk_test_count": "The number of at risk tests for this Framework.",
+ "created_at": "The date this Framework was created.",
+ "description": "The description of the Framework.",
+ "discarded_at": "The date this Framework was discarded.",
+ "disabled_test_count": "The number of non-applicable tests for this Framework.",
+ "failing_test_count": "The number of failing tests for this Framework.",
+ "key": "The key of the Framework.",
+ "title": "The title of the Framework.",
+ "passing_test_count": "The number of passing tests for this Framework.",
+ "updated_at": "The date this CompanyVendorConnection was updated.",
+ },
+ },
+ "framework_requirements": {
+ "description": "A single requirement within a compliance framework and its overall health.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this Framework Requirement.",
+ "company_id": "The identifier for the Company.",
+ "created_at": "The date this Framework Requirement was created.",
+ "description": "The description of the Framework Requirement.",
+ "enabled": "Whether this Framework Requirement is enabled.",
+ "health_status": "The overall health of the Framework Requirement.",
+ "key": "The key of the Framework Requirement.",
+ "name": "The name of the Framework Requirement.",
+ "updated_at": "The date this Framework Requirement was updated.",
+ },
+ },
+ "risks": {
+ "description": "A risk register entry with impact, likelihood, treatment, and ownership details.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this CompanyRisk.",
+ "annualized_rate_of_occurrence": "The annualized rate of occurrence for this CompanyRisk.",
+ "asset_value": "The asset value for this CompanyRisk.",
+ "categories": "The categories for this CompanyRisk.",
+ "cia": "The CIA for this CompanyRisk.",
+ "departments": "The departments for this CompanyRisk.",
+ "description": "The description for this CompanyRisk.",
+ "exposure_factor": "The exposure factor for this CompanyRisk.",
+ "impact_justification": "The impact justification for this CompanyRisk.",
+ "likelihood_justification": "The likelihood justification for this CompanyRisk.",
+ "notes": "The notes for this CompanyRisk.",
+ "reference_url": "The reference URL for this CompanyRisk.",
+ "related_tickets": "The related tickets for this CompanyRisk.",
+ "reported_by": "The reported by for this CompanyRisk.",
+ "residual_impact_justification": "The residual impact justification for this CompanyRisk.",
+ "residual_likelihood_justification": "The residual likelihood justification for this CompanyRisk.",
+ "responsible_team": "The responsible team for this CompanyRisk.",
+ "source": "The source for this CompanyRisk.",
+ "status": "The status for this CompanyRisk.",
+ "treatment": "The treatment for this CompanyRisk.",
+ "treatment_decision_notes": "The treatment decision notes for this CompanyRisk.",
+ "uncertainty": "The uncertainty for this CompanyRisk.",
+ "created_at": "The date this CompanyRisk was created.",
+ "updated_at": "The date this CompanyRisk was updated.",
+ "company_id": "The identifier for the company for this CompanyRisk.",
+ "owner_id": "The identifier for the owner for this CompanyRisk.",
+ "custom_risk_id": "The custom risk ID for this CompanyRisk.",
+ },
+ },
+ "repositories": {
+ "description": "A source-code repository discovered from a connected vendor, with audit-scope status.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this Repository.",
+ "created_at": "The date this Repository object was created.",
+ "name": "The name of the Repository.",
+ "in_audit_scope": "Flag to indicate if this Repository is in scope.",
+ "out_of_audit_scope_reason": "Out of scope reason if the repository is not in scope.",
+ "private": "Flag to indicate if this Repository is private.",
+ "third_party_id": "The identifier for this Repository on the vendor side.",
+ "vendor_name": "The name of the vendor that this Repository is from.",
+ "updated_at": "The date this Repository was last updated.",
+ },
+ },
+ "integration_connections": {
+ "description": "A connection to an integrated vendor and its current sync status.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this IntegrationConnection.",
+ "name": "The name of the IntegrationConnection if applicable.",
+ "status": "The status of the IntegrationConnection.",
+ "vendor_name": "The name of the vendor for this IntegrationConnection.",
+ "updated_at": "The date this IntegrationConnection was last updated.",
+ },
+ },
+ "cloud_resources": {
+ "description": "A cloud infrastructure resource discovered from a connected vendor, with audit-scope status.",
+ "docs_url": "https://developer.secureframe.com/",
+ "columns": {
+ "id": "The identifier for this CloudResource.",
+ "cloud_resource_type": "The type of this CloudResource.",
+ "created_at": "The date this CloudResource was created.",
+ "in_audit_scope": "Flag to indicate if this CloudResource is in scope.",
+ "out_of_audit_scope_reason": "Out of scope reason if the repository is not in scope.",
+ "region": "The region this CloudResource belongs to.",
+ "tags": "The tags for this CloudResource.",
+ "third_party_id": "The identifier for this CloudResource on the vendor side.",
+ "vendor_name": "The name of the vendor that this CloudResource is from.",
+ "updated_at": "The date this CloudResource 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.py
new file mode 100644
index 000000000000..623211bcad2e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/secureframe.py
@@ -0,0 +1,236 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+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.secureframe.settings import SECUREFRAME_ENDPOINTS
+
+BASE_URLS = {
+ "us": "https://api.secureframe.com",
+ "uk": "https://api-uk.secureframe.com",
+}
+DEFAULT_REGION = "us"
+# Secureframe caps list pages at 100 items (also the documented default).
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class SecureframeRetryableError(Exception):
+ pass
+
+
+class SecureframeResumeConfig:
+ page: int
+
+
+def _base_url(region: str) -> str:
+ return BASE_URLS.get(region, BASE_URLS[DEFAULT_REGION])
+
+
+def _get_headers(api_key: str, api_secret: str) -> dict[str, str]:
+ # Secureframe authenticates with the API key and secret joined by a space (no scheme prefix).
+ return {
+ "Authorization": f"{api_key} {api_secret}",
+ "Accept": "application/json",
+ }
+
+
+def _make_session(api_key: str, api_secret: str) -> requests.Session:
+ # capture=False keeps Secureframe's credentialed responses out of the shared HTTP sample
+ # bucket: they carry personnel, device (serial/MAC/IP), and compliance-evidence fields the
+ # generic scrubber can't reliably redact. Requests stay metered and logged; redact_values
+ # masks the key/secret from logged URLs.
+ return make_tracked_session(
+ headers=_get_headers(api_key, api_secret),
+ redact_values=(api_key, api_secret),
+ capture=False,
+ )
+
+
+def _build_url(region: str, path: str, page: int) -> str:
+ params = {"page": page, "per_page": PAGE_SIZE}
+ return f"{_base_url(region)}{path}?{urlencode(params)}"
+
+
+def _flatten_resource(obj: Any) -> Optional[dict[str, Any]]:
+ """Flatten a JSON:API-style resource envelope into a plain row dict.
+
+ Secureframe wraps each resource as ``{"data": {"id", "type", "attributes": {...}}}``;
+ the attributes already carry ``id`` per the API spec, but we backfill it from the
+ envelope defensively. Plain dicts pass through untouched.
+ """
+ if not isinstance(obj, dict):
+ return None
+
+ node = obj.get("data", obj)
+ if not isinstance(node, dict):
+ return None
+
+ attributes = node.get("attributes")
+ if isinstance(attributes, dict):
+ row = dict(attributes)
+ if "id" not in row and node.get("id") is not None:
+ row["id"] = node["id"]
+ return row
+
+ return node
+
+
+def _extract_rows(payload: Any) -> list[dict[str, Any]]:
+ if isinstance(payload, list):
+ items = payload
+ elif isinstance(payload, dict) and isinstance(payload.get("data"), list):
+ items = payload["data"]
+ else:
+ items = []
+
+ return [row for row in (_flatten_resource(item) for item in items) if row is not None]
+
+
+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}
+ response = session.get(
+ f"{_base_url(region)}{path}?{urlencode(params)}",
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ return response.status_code
+
+
+def validate_credentials(api_key: str, api_secret: str, region: str, endpoint: str | None = None) -> tuple[bool, bool]:
+ """Probe the API and return ``(authenticated, authorized)``.
+
+ Secureframe returns 401 for a bad key/secret pair and 403 when the pair is valid but
+ the key's RBAC role can't read the probed resource. At source-create a 403 is
+ acceptable (users may only grant the scopes they intend to sync), so callers get both
+ signals. Any other failure counts as unauthenticated.
+ """
+ path = SECUREFRAME_ENDPOINTS[endpoint].path if endpoint else "/users"
+ try:
+ status = _probe_endpoint(_make_session(api_key, api_secret), region, path)
+ except Exception:
+ return False, False
+
+ if status == 200:
+ return True, True
+ if status == 403:
+ return True, False
+ return False, False
+
+
+def get_endpoint_permissions(api_key: str, api_secret: str, region: str, endpoints: list[str]) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = {}
+ session = _make_session(api_key, api_secret)
+ for endpoint in endpoints:
+ config = SECUREFRAME_ENDPOINTS.get(endpoint)
+ if config is None:
+ permissions[endpoint] = None
+ continue
+ 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
+ return permissions
+
+
+def get_rows(
+ api_key: str,
+ api_secret: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SecureframeResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SECUREFRAME_ENDPOINTS[endpoint]
+ session = _make_session(api_key, api_secret)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ page = max(resume_config.page, 1)
+ logger.debug(f"Secureframe: resuming {endpoint} from page {page}")
+ else:
+ page = 1
+
+ @retry(
+ retry=retry_if_exception_type((SecureframeRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> Any:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Secureframe doesn't publish rate limits; back off on 429 and transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SecureframeRetryableError(
+ f"Secureframe API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Secureframe API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ url = _build_url(region, config.path, page)
+ payload = fetch_page(url)
+ rows = _extract_rows(payload)
+
+ # The API exposes no page-count metadata, so pagination terminates on the first
+ # empty page. A short page could just mean the server capped per_page below what
+ # we asked for, so it does not end the scan.
+ if not rows:
+ break
+
+ yield rows
+
+ page += 1
+ resumable_source_manager.save_state(SecureframeResumeConfig(page=page))
+
+
+def secureframe_source(
+ api_key: str,
+ api_secret: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SecureframeResumeConfig],
+) -> SourceResponse:
+ config = SECUREFRAME_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ api_secret=api_secret,
+ region=region,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ 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,
+ )
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.py
new file mode 100644
index 000000000000..c76795b81eee
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/settings.py
@@ -0,0 +1,91 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class SecureframeEndpointConfig:
+ name: str
+ path: str
+ primary_key: str = "id"
+ # 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
+
+
+# Every list endpoint in the Secureframe public API paginates with `page`/`per_page`
+# (per_page max 100) and wraps rows in JSON:API-style envelopes. The API exposes no
+# server-side timestamp filter (only a Lucene `q` search whose date-range semantics are
+# undocumented), so every endpoint is full refresh only.
+SECUREFRAME_ENDPOINTS: dict[str, SecureframeEndpointConfig] = {
+ "controls": SecureframeEndpointConfig(
+ name="controls",
+ path="/controls",
+ partition_key="created_at",
+ ),
+ "tests": SecureframeEndpointConfig(
+ name="tests",
+ path="/tests",
+ partition_key="created_at",
+ ),
+ "users": SecureframeEndpointConfig(
+ name="users",
+ path="/users",
+ partition_key="created_at",
+ ),
+ "user_accounts": SecureframeEndpointConfig(
+ name="user_accounts",
+ path="/user_accounts",
+ partition_key="created_at",
+ ),
+ "devices": SecureframeEndpointConfig(
+ name="devices",
+ path="/devices",
+ partition_key="created_at",
+ ),
+ # The legacy vendor list. Its schema has no created_at, so no partitioning.
+ "vendors": SecureframeEndpointConfig(
+ name="vendors",
+ path="/vendors",
+ ),
+ "tprm_vendors": SecureframeEndpointConfig(
+ name="tprm_vendors",
+ path="/tprm/vendors",
+ partition_key="created_at",
+ ),
+ "frameworks": SecureframeEndpointConfig(
+ name="frameworks",
+ path="/frameworks",
+ partition_key="created_at",
+ ),
+ "framework_requirements": SecureframeEndpointConfig(
+ name="framework_requirements",
+ path="/framework_requirements",
+ partition_key="created_at",
+ ),
+ "risks": SecureframeEndpointConfig(
+ name="risks",
+ path="/risks",
+ partition_key="created_at",
+ ),
+ "repositories": SecureframeEndpointConfig(
+ name="repositories",
+ path="/repositories",
+ partition_key="created_at",
+ ),
+ # Integration connection schema exposes only id/name/status/vendor_name/updated_at.
+ "integration_connections": SecureframeEndpointConfig(
+ name="integration_connections",
+ path="/integration_connections",
+ ),
+ "cloud_resources": SecureframeEndpointConfig(
+ name="cloud_resources",
+ path="/cloud_resources",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(SECUREFRAME_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/source.py
index 90b09cd2bcb3..4922e72aa868 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/source.py
@@ -1,30 +1,178 @@
-from typing import cast
+from typing import Optional, cast
from 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.generated_configs import SecureframeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.secureframe import (
+ DEFAULT_REGION,
+ SecureframeResumeConfig,
+ get_endpoint_permissions as get_secureframe_endpoint_permissions,
+ secureframe_source,
+ validate_credentials as validate_secureframe_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SecureframeSource(SimpleSource[SecureframeSourceConfig]):
+class SecureframeSource(ResumableSource[SecureframeSourceConfig, SecureframeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SECUREFRAME
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Secureframe authentication failed. Please check your API key and secret, and that you selected the right region.",
+ "403 Client Error: Forbidden for url": "Your Secureframe API key's role does not have permission to read this data. Update the role's permissions in Secureframe and try again.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SECUREFRAME,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Secureframe",
+ caption="""Enter your Secureframe API credentials to pull your compliance data (controls, tests, personnel, devices, vendors, and more) into the PostHog Data warehouse.
+
+You can create an API key and secret in the Secureframe Console under **Your Profile → Company settings → API keys**. The key's role-based permissions govern which tables you can sync.""",
iconPath="/static/services/secureframe.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/secureframe",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["compliance", "grc", "soc2", "audit"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue=DEFAULT_REGION,
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.secureframe.com)", value="us"),
+ SourceFieldSelectConfigOption(label="UK (api-uk.secureframe.com)", value="uk"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="api_secret",
+ label="API secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SecureframeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The Secureframe API exposes no server-side timestamp filter, so every endpoint is
+ # full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ 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: SecureframeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ authenticated, authorized = validate_secureframe_credentials(
+ config.api_key, config.api_secret, config.region, endpoint=schema_name
+ )
+
+ if schema_name is not None:
+ if authenticated and authorized:
+ return True, None
+ if authenticated:
+ return (
+ False,
+ f"Your Secureframe API key's role does not have permission to read {schema_name}. Update the role's permissions in Secureframe.",
+ )
+ return False, "Invalid Secureframe API key or secret, or wrong region selected"
+
+ # At source-create only the key needs to be genuine — a 403 means a valid key whose
+ # role lacks a scope, which the user can sort out per table.
+ if authenticated:
+ return True, None
+
+ return False, "Invalid Secureframe API key or secret, or wrong region selected"
+
+ def get_endpoint_permissions(
+ self, config: SecureframeSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ return get_secureframe_endpoint_permissions(config.api_key, config.api_secret, config.region, endpoints)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SecureframeResumeConfig]:
+ return ResumableSourceManager[SecureframeResumeConfig](inputs, SecureframeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SecureframeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SecureframeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return secureframe_source(
+ api_key=config.api_key,
+ api_secret=config.api_secret,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
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.py
new file mode 100644
index 000000000000..83079b079955
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe.py
@@ -0,0 +1,241 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.secureframe import (
+ SecureframeResumeConfig,
+ _build_url,
+ _extract_rows,
+ get_endpoint_permissions,
+ get_rows,
+ secureframe_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.settings import (
+ ENDPOINTS,
+ SECUREFRAME_ENDPOINTS,
+)
+
+MOCK_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.secureframe"
+
+
+def _make_manager(resume_state: SecureframeResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: Any, status_code: int = 200) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.json.return_value = payload
+ response.status_code = status_code
+ response.ok = status_code < 400
+ if status_code >= 400:
+ response.raise_for_status.side_effect = HTTPError(f"{status_code} Client Error", response=response)
+ return response
+
+
+class TestExtractRows:
+ @pytest.mark.parametrize(
+ "payload, expected",
+ [
+ # Array of per-item JSON:API envelopes (the shape the OpenAPI spec declares).
+ (
+ [{"data": {"id": "a", "type": "control", "attributes": {"name": "x"}}}],
+ [{"id": "a", "name": "x"}],
+ ),
+ # Standard JSON:API document with a top-level data array.
+ (
+ {"data": [{"id": "b", "type": "control", "attributes": {"id": "b", "name": "y"}}]},
+ [{"id": "b", "name": "y"}],
+ ),
+ # Plain row dicts, with and without a wrapping data key.
+ ([{"id": "c", "name": "z"}], [{"id": "c", "name": "z"}]),
+ ({"data": [{"id": "d", "name": "w"}]}, [{"id": "d", "name": "w"}]),
+ # Attributes win, but a missing id is backfilled from the envelope.
+ (
+ [{"data": {"id": "e", "attributes": {"name": "v", "id": "other"}}}],
+ [{"id": "other", "name": "v"}],
+ ),
+ # Unexpected payloads yield nothing instead of raising.
+ ({"message": "Authorization failed"}, []),
+ ([], []),
+ (None, []),
+ ("not json we expect", []),
+ ([None, "junk", 42], []),
+ ],
+ )
+ def test_extract_rows_shapes(self, payload, expected):
+ assert _extract_rows(payload) == expected
+
+
+class TestBuildUrl:
+ @pytest.mark.parametrize(
+ "region, expected_host",
+ [
+ ("us", "https://api.secureframe.com"),
+ ("uk", "https://api-uk.secureframe.com"),
+ ("unknown", "https://api.secureframe.com"),
+ ],
+ )
+ def test_region_maps_to_host(self, region, expected_host):
+ assert _build_url(region, "/controls", 2) == f"{expected_host}/controls?page=2&per_page=100"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, (True, True)),
+ # A valid key whose role lacks the probed scope is authenticated but not authorized.
+ (403, (True, False)),
+ (401, (False, False)),
+ (500, (False, False)),
+ ],
+ )
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("key", "secret", "us") == expected
+
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key", "secret", "us") == (False, False)
+
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_probes_requested_endpoint(self, mock_session):
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("key", "secret", "us", endpoint="devices")
+
+ assert "/devices?" in mock_session.return_value.get.call_args.args[0]
+
+
+class TestGetEndpointPermissions:
+ @pytest.mark.parametrize("denied_status", [401, 403])
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_denied_endpoints_carry_a_reason(self, mock_session, denied_status):
+ ok = mock.MagicMock(status_code=200)
+ denied = mock.MagicMock(status_code=denied_status)
+ mock_session.return_value.get.side_effect = [ok, denied]
+
+ permissions = get_endpoint_permissions("key", "secret", "us", ["controls", "tests"])
+
+ assert permissions["controls"] is None
+ assert permissions["tests"] is not None
+ assert "tests" in permissions["tests"]
+
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_transient_failures_are_not_denials(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("connection reset")
+
+ assert get_endpoint_permissions("key", "secret", "us", ["controls"]) == {"controls": None}
+
+
+class TestGetRows:
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_paginates_until_empty_page(self, mock_session):
+ pages = [
+ _response({"data": [{"id": "1", "attributes": {"id": "1"}}, {"id": "2", "attributes": {"id": "2"}}]}),
+ _response({"data": [{"id": "3", "attributes": {"id": "3"}}]}),
+ _response({"data": []}),
+ ]
+ mock_session.return_value.get.side_effect = pages
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "secret", "us", "controls", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert [f"page={n}" in url for n, url in enumerate(urls, start=1)] == [True, True, True]
+
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_state_saved_after_each_yielded_batch(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"id": "1", "attributes": {"id": "1"}}]}),
+ _response({"data": []}),
+ ]
+
+ manager = _make_manager()
+ rows_iterator = get_rows("key", "secret", "us", "controls", mock.MagicMock(), manager)
+
+ next(rows_iterator)
+ # Generator paused at the yield: page 1 is in flight downstream, so no checkpoint yet —
+ # a crash here must re-fetch page 1, not skip it.
+ manager.save_state.assert_not_called()
+
+ assert list(rows_iterator) == []
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].page == 2
+
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_page(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"data": []})
+
+ manager = _make_manager(SecureframeResumeConfig(page=5))
+ list(get_rows("key", "secret", "us", "controls", mock.MagicMock(), manager))
+
+ assert "page=5" in mock_session.return_value.get.call_args.args[0]
+
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_auth_failure_raises_instead_of_ending_sync(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"message": "Authorization failed"}, status_code=401)
+
+ manager = _make_manager()
+ with pytest.raises(HTTPError):
+ list(get_rows("key", "secret", "us", "controls", mock.MagicMock(), manager))
+
+ manager.save_state.assert_not_called()
+
+
+class TestSessionHardening:
+ @pytest.mark.parametrize(
+ "call",
+ [
+ lambda: validate_credentials("key", "secret", "us"),
+ lambda: get_endpoint_permissions("key", "secret", "us", ["controls"]),
+ lambda: list(get_rows("key", "secret", "us", "controls", mock.MagicMock(), _make_manager())),
+ ],
+ )
+ @mock.patch(f"{MOCK_MODULE}.make_tracked_session")
+ def test_session_excludes_responses_from_sample_capture_and_redacts_credentials(self, mock_session, call):
+ mock_session.return_value.get.return_value = _response({"data": []})
+
+ call()
+
+ # Secureframe responses carry customer PII the generic scrubber can't remove, so the
+ # session must opt out of HTTP sample capture and mask both credential halves.
+ _, kwargs = mock_session.call_args
+ assert kwargs["capture"] is False
+ assert set(kwargs["redact_values"]) == {"key", "secret"}
+
+
+class TestSecureframeSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = SECUREFRAME_ENDPOINTS[endpoint]
+ response = secureframe_source("key", "secret", "us", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(SECUREFRAME_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "created_at"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe_source.py
new file mode 100644
index 000000000000..092d17da3239
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secureframe/tests/test_secureframe_source.py
@@ -0,0 +1,128 @@
+import pytest
+from unittest import mock
+
+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.generated_configs import SecureframeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.secureframe import (
+ SecureframeResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.source import SecureframeSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MOCK_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.secureframe.source"
+
+
+class TestSecureframeSource:
+ def setup_method(self):
+ self.source = SecureframeSource()
+ self.team_id = 123
+ self.config = SecureframeSourceConfig(api_key="key", api_secret="secret", region="us")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.SECUREFRAME
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Secureframe"
+ assert config.label == "Secureframe"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/secureframe.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/secureframe"
+
+ assert [f.name for f in config.fields] == ["region", "api_key", "api_secret"]
+
+ @pytest.mark.parametrize("field_name", ["api_key", "api_secret"])
+ def test_credential_fields_are_secret_passwords(self, field_name):
+ # Both halves of the credential must be secret so the source serializer never echoes
+ # them back in job_inputs to anyone who can read the source.
+ config = self.source.get_source_config
+ secret_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ def test_region_field_defaults_to_us(self):
+ config = self.source.get_source_config
+ region_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))
+ assert region_field.defaultValue == "us"
+ assert {option.value for option in region_field.options} == {"us", "uk"}
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.secureframe.com/controls?page=1&per_page=100",
+ "403 Client Error: Forbidden for url: https://api-uk.secureframe.com/tests?page=1&per_page=100",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ def test_non_retryable_errors_do_not_match_transient_failures(self):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(
+ key in "500 Server Error for url: https://api.secureframe.com/controls" for key in non_retryable_errors
+ )
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No verified server-side timestamp filter exists, so nothing may advertise incremental.
+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["controls"])
+ assert [schema.name for schema in schemas] == ["controls"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "probe_result, schema_name, expected_valid",
+ [
+ # At source-create a valid key with a missing scope (403) must still connect.
+ ((True, True), None, True),
+ ((True, False), None, True),
+ ((False, False), None, False),
+ # A per-schema check demands read access to that specific endpoint.
+ ((True, True), "controls", True),
+ ((True, False), "controls", False),
+ ((False, False), "controls", False),
+ ],
+ )
+ @mock.patch(f"{MOCK_MODULE}.validate_secureframe_credentials")
+ def test_validate_credentials(self, mock_validate, probe_result, schema_name, expected_valid):
+ mock_validate.return_value = probe_result
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ assert (error_message is None) is expected_valid
+ mock_validate.assert_called_once_with("key", "secret", "us", endpoint=schema_name)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SecureframeResumeConfig
+
+ @mock.patch(f"{MOCK_MODULE}.secureframe_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_secureframe_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "controls"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_secureframe_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["api_secret"] == "secret"
+ assert kwargs["region"] == "us"
+ assert kwargs["endpoint"] == "controls"
+ assert kwargs["resumable_source_manager"] is manager