:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement orca_security import source (#71176)
Tom Owers00892d11be4e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7779f8648c4a..2457f0c87858 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -326,6 +326,7 @@ the row lists both.| openai | HTTP | requests | ✅ || opinion_stage | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ |+| orca_security | HTTP (POST query DSL) | requests | ✅ || openaq | HTTP | requests | ✅ || openfda | HTTP | requests | ✅ || openrouter | HTTP | requests | ✅ |@@ -793,7 +794,6 @@ doesn't conflict with concurrent PRs.- oracle_ebs- oracle_fusion- orbit-- orca_security- outlook- outreach- oveitdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex f82a802dedec..72d883df0a4e 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@@ -2985,7 +2985,8 @@ class OrbitSourceConfig(config.Config):@config.configclass OrcaSecuritySourceConfig(config.Config):- pass+ api_token: str+ region: Literal["global", "us", "eu"] = config.value(default="global")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/canonical_descriptions.pynew file mode 100644index 000000000000..b54cc7c4ff4c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/canonical_descriptions.py@@ -0,0 +1,54 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Column names match the Serving Layer field names lifted to the row root by `_normalize_item`.+# Coverage is intentionally partial — fields not listed fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "alerts": {+ "description": "Security alerts Orca raised for detected risks (misconfigurations, malicious activity, neglected assets, and more).",+ "docs_url": "https://docs.orcasecurity.io/docs/alerts",+ "columns": {+ "id": "Globally unique identifier for the alert record.",+ "AlertId": "Orca's identifier for the alert.",+ "AlertType": "Human-readable name of the rule that produced the alert.",+ "Category": "Risk category the alert belongs to (e.g. IAM misconfigurations, Data at risk).",+ "RiskLevel": "Severity of the alert (e.g. informational, low, medium, high, critical).",+ "OrcaScore": "Orca's contextual risk score for the alert.",+ "Status": "Current alert status (e.g. open, in progress, dismissed).",+ "Source": "System or scan that surfaced the alert.",+ "RuleSource": "Origin of the rule (e.g. Orca, Vendor).",+ "Labels": "Tags associated with the alert.",+ "CreatedAt": "Timestamp when the alert was first created.",+ "LastSeen": "Timestamp when the alert was most recently observed.",+ },+ },+ "assets": {+ "description": "Cloud asset inventory discovered by Orca (compute instances, storage, functions, databases, and more).",+ "docs_url": "https://docs.orcasecurity.io/docs/asset-inventory",+ "columns": {+ "id": "Globally unique identifier for the asset record.",+ "Name": "Display name of the asset.",+ "Type": "Asset type (e.g. AwsEc2Instance, AwsS3Bucket).",+ "CloudProvider": "Cloud provider hosting the asset (e.g. aws, azure, gcp).",+ },+ },+ "cloud_accounts": {+ "description": "Cloud accounts, subscriptions, or projects connected to Orca for scanning.",+ "docs_url": "https://docs.orcasecurity.io/docs/cloud-accounts",+ "columns": {+ "id": "Globally unique identifier for the cloud account record.",+ "Name": "Display name of the cloud account.",+ "CloudProvider": "Cloud provider of the account (e.g. aws, azure, gcp).",+ },+ },+ "vulnerabilities": {+ "description": "CVEs and vulnerabilities Orca detected across scanned assets.",+ "docs_url": "https://docs.orcasecurity.io/docs/vulnerabilities",+ "columns": {+ "id": "Globally unique identifier for the vulnerability record.",+ "CVEID": "CVE identifier for the vulnerability.",+ "Severity": "Severity classification of the vulnerability.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/orca_security.py b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/orca_security.pynew file mode 100644index 000000000000..c62bab4ff034--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/orca_security.py@@ -0,0 +1,246 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++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.orca_security.settings import (+ DEFAULT_REGION,+ ORCA_ENDPOINTS,+ ORCA_REGION_HOSTS,+ PAGE_SIZE,+ QUERY_PATH,+ OrcaEndpointConfig,+)++REQUEST_TIMEOUT = 120+++class OrcaRetryableError(Exception):+ pass+++class OrcaResumeConfig:+ # Serving Layer offset (`start_at_index`) of the next page to fetch. Offset pagination has no+ # opaque cursor, so the offset alone is enough to pick back up after a heartbeat timeout.+ start_at_index: int = 0+++def _host(region: str) -> str:+ return ORCA_REGION_HOSTS.get(region or DEFAULT_REGION, ORCA_REGION_HOSTS[DEFAULT_REGION])+++def _headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Token {api_token}",+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++def _format_datetime(value: Any) -> str:+ """Format a datetime/date as an ISO 8601 string. Orca's Serving Layer is strict about the format."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _build_payload(+ config: OrcaEndpointConfig,+ start_at_index: int,+ incremental_field: str | None,+ formatted_last_value: str | None,+) -> dict[str, Any]:+ """Build the Serving Layer object_set query body for one page of a stream."""+ query: dict[str, Any] = {"models": [config.model], "type": "object_set"}++ # Server-side incremental filter, only for streams with a verified `date_gte`-able field.+ if config.incremental_key and formatted_last_value:+ filter_field = incremental_field or config.incremental_key+ query["with"] = {+ "type": "operation",+ "operator": "and",+ "values": [+ {+ "key": filter_field,+ "values": [formatted_last_value],+ "type": "datetime",+ "operator": "date_gte",+ "value_type": "days",+ }+ ],+ }++ payload: dict[str, Any] = {+ "query": query,+ "limit": PAGE_SIZE,+ "start_at_index": start_at_index,+ }+ # Ascending order on the incremental field keeps the pipeline's watermark advancing correctly+ # (matches SourceResponse.sort_mode="asc") and gives offset pagination a stable order.+ if config.incremental_key:+ payload["order_by[]"] = [config.incremental_key]++ return payload+++def _normalize_item(item: dict[str, Any]) -> dict[str, Any]:+ """Flatten a Serving Layer object into a flat row.++ Objects arrive as ``{"id", "type", "data": {"Field": {"value": ...}}}``. We lift the stable+ top-level ``id``/``type`` and unwrap each ``{"value": ...}`` field to the row root so the+ warehouse table has queryable columns instead of a single nested blob.+ """+ row: dict[str, Any] = {}+ if "id" in item:+ row["id"] = item["id"]+ if "type" in item:+ row["type"] = item["type"]++ data = item.get("data")+ if isinstance(data, dict):+ for key, wrapped in data.items():+ if isinstance(wrapped, dict) and "value" in wrapped:+ row[key] = wrapped["value"]+ else:+ row[key] = wrapped+ return row+++@retry(+ retry=retry_if_exception_type(+ (+ OrcaRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], payload: dict[str, Any], logger: FilteringBoundLogger+) -> dict:+ response = session.post(url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT)++ if response.status_code == 429 or response.status_code >= 500:+ raise OrcaRetryableError(f"Orca API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Orca API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str, region: str) -> tuple[bool, Optional[str]]:+ """Probe the token against a cheap single-row Serving Layer query."""+ url = f"{_host(region)}{QUERY_PATH}"+ payload = {"query": {"models": ["CloudAccount"], "type": "object_set"}, "limit": 1, "start_at_index": 0}+ try:+ response = make_tracked_session().post(url, headers=_headers(api_token), json=payload, timeout=30)+ except Exception as e:+ return False, f"Could not reach Orca Security ({e}). Check your network and the selected region, then retry."++ if response.status_code in (401, 403):+ return (+ False,+ "Orca rejected the API token. Generate a new token in Settings → Users & Permissions → API and reconnect.",+ )+ if not response.ok:+ return False, f"Orca API returned an unexpected status ({response.status_code}). Please retry."+ return True, None+++def get_rows(+ api_token: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OrcaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = ORCA_ENDPOINTS[endpoint]+ url = f"{_host(region)}{QUERY_PATH}"+ headers = _headers(api_token)+ session = make_tracked_session()++ formatted_last_value = (+ _format_datetime(db_incremental_field_last_value)+ if should_use_incremental_field and config.incremental_key and db_incremental_field_last_value+ else None+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_at_index = resume.start_at_index if resume else 0+ if resume:+ logger.debug(f"Orca: resuming {endpoint} from start_at_index={start_at_index}")++ while True:+ payload = _build_payload(config, start_at_index, incremental_field, formatted_last_value)+ data = _fetch_page(session, url, headers, payload, logger)++ items = data.get("data", [])+ if not items:+ break++ yield [_normalize_item(item) for item in items]++ # `next_page_token` is the next offset; fall back to advancing by page size. A short page+ # (fewer than PAGE_SIZE rows) means we've reached the end.+ next_token = data.get("next_page_token")+ if not next_token and len(items) < PAGE_SIZE:+ break+ start_at_index = int(next_token) if next_token else start_at_index + len(items)++ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary key)+ # rather than skipping it.+ resumable_source_manager.save_state(OrcaResumeConfig(start_at_index=start_at_index))+++def orca_source(+ api_token: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OrcaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = ORCA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/settings.pynew file mode 100644index 000000000000..c620bf4b2fcf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/settings.py@@ -0,0 +1,79 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Region -> Serving Layer API base URL. Orca hosts a US and an EU cloud plus a generic+# default; the token is only valid for the region it was generated in, so the user picks one.+ORCA_REGION_HOSTS: dict[str, str] = {+ "global": "https://api.orcasecurity.io/api",+ "us": "https://app.us.orcasecurity.io/api",+ "eu": "https://app.eu.orcasecurity.io/api",+}+DEFAULT_REGION = "global"++# Everything funnels through the single Serving Layer query endpoint; each stream just+# swaps the Orca model it asks for in the POST body.+QUERY_PATH = "/serving-layer/query"++PAGE_SIZE = 1000+++@dataclass+class OrcaEndpointConfig:+ name: str+ # Orca Serving Layer model queried in the object_set body (e.g. "Alert", "Inventory").+ model: str+ incremental_fields: list[IncrementalField]+ # Serving Layer field the server-side `date_gte` filter is applied to, e.g. "CreatedAt".+ # None => no verified server-side timestamp filter, so this stream is full-refresh only.+ incremental_key: Optional[str] = None+ # Stable field to partition by. Must never change after creation (created-style, not last-seen).+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++ORCA_ENDPOINTS: dict[str, OrcaEndpointConfig] = {+ # Security alerts (misconfigurations, malicious activity, etc). CreatedAt is stable and the+ # Serving Layer honors a `date_gte` filter on it, so this is the one incremental stream.+ "alerts": OrcaEndpointConfig(+ name="alerts",+ model="Alert",+ incremental_key="CreatedAt",+ partition_key="CreatedAt",+ incremental_fields=[+ {+ "label": "CreatedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "CreatedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Cloud asset inventory (EC2 instances, buckets, functions, ...). The Serving Layer exposes+ # this as the `Inventory` model. No verified server-side timestamp filter, so full refresh.+ "assets": OrcaEndpointConfig(+ name="assets",+ model="Inventory",+ incremental_fields=[],+ ),+ # Connected cloud accounts/subscriptions/projects.+ "cloud_accounts": OrcaEndpointConfig(+ name="cloud_accounts",+ model="CloudAccount",+ incremental_fields=[],+ ),+ # Detected CVEs / vulnerabilities across scanned assets.+ "vulnerabilities": OrcaEndpointConfig(+ name="vulnerabilities",+ model="CVE",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(ORCA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ORCA_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/source.pyindex 2c16621c40ca..431b9f38fa5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/source.py@@ -1,30 +1,163 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OrcaSecuritySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.orca_security import (+ OrcaResumeConfig,+ orca_source,+ validate_credentials as validate_orca_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ ORCA_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OrcaSecuritySource(SimpleSource[OrcaSecuritySourceConfig]):+class OrcaSecuritySource(ResumableSource[OrcaSecuritySourceConfig, OrcaResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ORCASECURITY+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` selects the origin the stored API token is sent to; changing it must+ # re-require the token (Orca tokens are region-scoped anyway).+ return ["region"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ message = (+ "Orca rejected the API token. Generate a new token in Orca under "+ "Settings → Users & Permissions → API (Viewer role is enough) and reconnect."+ )+ return {+ "401 Client Error: Unauthorized": message,+ "403 Client Error: Forbidden": message,+ }++ def get_schemas(+ self,+ config: OrcaSecuritySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None+ and len(INCREMENTAL_FIELDS[endpoint]) > 0,+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None+ and len(INCREMENTAL_FIELDS[endpoint]) > 0,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=ORCA_ENDPOINTS[endpoint].should_sync_default,+ )+ 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: OrcaSecuritySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_orca_credentials(config.api_token, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OrcaResumeConfig]:+ return ResumableSourceManager[OrcaResumeConfig](inputs, OrcaResumeConfig)++ def source_for_pipeline(+ self,+ config: OrcaSecuritySourceConfig,+ resumable_source_manager: ResumableSourceManager[OrcaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return orca_source(+ api_token=config.api_token,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ORCA_SECURITY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Orca Security",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Enter your Orca Security API token to pull your cloud security posture data into the "+ "PostHog Data warehouse.\n\n"+ "Create an API token in Orca under **Settings → Users & Permissions → API**. A user with the "+ "**Viewer** role is enough to read alerts, assets, cloud accounts, and vulnerabilities.\n\n"+ "Pick the **region** that matches the URL you sign in to — the token is only valid for the "+ "region it was created in."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/orca-security",iconPath="/static/services/orca_security.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="global",+ options=[+ SourceFieldSelectConfigOption(label="Global (api.orcasecurity.io)", value="global"),+ SourceFieldSelectConfigOption(label="US (app.us.orcasecurity.io)", value="us"),+ SourceFieldSelectConfigOption(label="EU (app.eu.orcasecurity.io)", value="eu"),+ ],+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/tests/test_orca_security.py b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/tests/test_orca_security.pynew file mode 100644index 000000000000..dffe84dd7554--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/tests/test_orca_security.py@@ -0,0 +1,268 @@+from datetime import UTC, date, datetime+from typing import Any++from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security import orca_security+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.orca_security import (+ OrcaResumeConfig,+ _build_payload,+ _format_datetime,+ _headers,+ _host,+ _normalize_item,+ get_rows,+ orca_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.settings import (+ ORCA_ENDPOINTS,+ PAGE_SIZE,+)+++class FakeManager:+ """Stand-in for ResumableSourceManager that records saved state in memory."""++ def __init__(self, initial: OrcaResumeConfig | None = None):+ self._state = initial+ self.saved: list[OrcaResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> OrcaResumeConfig | None:+ return self._state++ def save_state(self, data: OrcaResumeConfig) -> None:+ self.saved.append(data)+++class TestHost:+ @parameterized.expand(+ [+ ("global", "https://api.orcasecurity.io/api"),+ ("us", "https://app.us.orcasecurity.io/api"),+ ("eu", "https://app.eu.orcasecurity.io/api"),+ ("", "https://api.orcasecurity.io/api"),+ ("unknown", "https://api.orcasecurity.io/api"),+ ]+ )+ def test_host_mapping(self, region: str, expected: str) -> None:+ assert _host(region) == expected+++class TestHeaders:+ def test_token_header(self) -> None:+ headers = _headers("abc123")+ assert headers["Authorization"] == "Token abc123"+ assert headers["Content-Type"] == "application/json"+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("aware", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ ("naive", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ ("date", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("string_passthrough", "cursor", "cursor"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected+++class TestBuildPayload:+ def test_full_refresh_has_no_filter_or_order(self) -> None:+ payload = _build_payload(+ ORCA_ENDPOINTS["assets"], start_at_index=0, incremental_field=None, formatted_last_value=None+ )+ assert payload["query"] == {"models": ["Inventory"], "type": "object_set"}+ assert payload["limit"] == PAGE_SIZE+ assert payload["start_at_index"] == 0+ assert "with" not in payload["query"]+ assert "order_by[]" not in payload++ def test_incremental_stream_always_sorts(self) -> None:+ payload = _build_payload(+ ORCA_ENDPOINTS["alerts"], start_at_index=0, incremental_field=None, formatted_last_value=None+ )+ # Even on first sync (no watermark), the incremental stream requests ascending order so the+ # pipeline watermark advances correctly.+ assert payload["order_by[]"] == ["CreatedAt"]+ assert "with" not in payload["query"]++ def test_incremental_filter_applied(self) -> None:+ payload = _build_payload(+ ORCA_ENDPOINTS["alerts"],+ start_at_index=100,+ incremental_field="CreatedAt",+ formatted_last_value="2026-01-01T00:00:00+00:00",+ )+ assert payload["start_at_index"] == 100+ with_clause = payload["query"]["with"]+ assert with_clause["operator"] == "and"+ value = with_clause["values"][0]+ assert value["key"] == "CreatedAt"+ assert value["operator"] == "date_gte"+ assert value["values"] == ["2026-01-01T00:00:00+00:00"]++ def test_incremental_field_override(self) -> None:+ payload = _build_payload(+ ORCA_ENDPOINTS["alerts"],+ start_at_index=0,+ incremental_field="LastSeen",+ formatted_last_value="2026-01-01T00:00:00+00:00",+ )+ assert payload["query"]["with"]["values"][0]["key"] == "LastSeen"+++class TestNormalizeItem:+ def test_unwraps_value_fields(self) -> None:+ item = {+ "id": "acc_1_alert_1",+ "type": "Alert",+ "data": {+ "AlertId": {"value": "alert_1"},+ "Category": {"value": "IAM misconfigurations"},+ "Labels": {"value": ["a", "b"]},+ },+ }+ row = _normalize_item(item)+ assert row == {+ "id": "acc_1_alert_1",+ "type": "Alert",+ "AlertId": "alert_1",+ "Category": "IAM misconfigurations",+ "Labels": ["a", "b"],+ }++ def test_keeps_unwrapped_field(self) -> None:+ row = _normalize_item({"id": "x", "data": {"Raw": {"nested": 1}}})+ assert row["Raw"] == {"nested": 1}++ def test_missing_data(self) -> None:+ assert _normalize_item({"id": "x", "type": "Alert"}) == {"id": "x", "type": "Alert"}+++class TestGetRows:+ def _page(self, ids: list[str], next_token: int | None) -> dict:+ return {+ "data": [{"id": i, "type": "Alert", "data": {"AlertId": {"value": i}}} for i in ids],+ "next_page_token": next_token,+ }++ def test_paginates_until_short_page(self) -> None:+ manager = FakeManager()+ pages = [+ self._page([str(n) for n in range(PAGE_SIZE)], PAGE_SIZE),+ self._page(["last"], None),+ ]+ with (+ mock.patch.object(orca_security, "make_tracked_session"),+ mock.patch.object(orca_security, "_fetch_page", side_effect=pages),+ ):+ batches = list(+ get_rows("tok", "us", "alerts", mock.MagicMock(), manager) # type: ignore[arg-type]+ )+ # Two pages yielded, each normalized.+ assert len(batches) == 2+ assert batches[1][0]["id"] == "last"+ # State saved once (after first full page) with the advanced offset.+ assert manager.saved == [OrcaResumeConfig(start_at_index=PAGE_SIZE)]++ def test_stops_on_empty_page(self) -> None:+ manager = FakeManager()+ with (+ mock.patch.object(orca_security, "make_tracked_session"),+ mock.patch.object(orca_security, "_fetch_page", return_value={"data": [], "next_page_token": None}),+ ):+ batches = list(get_rows("tok", "us", "alerts", mock.MagicMock(), manager)) # type: ignore[arg-type]+ assert batches == []+ assert manager.saved == []++ def test_resumes_from_saved_offset(self) -> None:+ manager = FakeManager(initial=OrcaResumeConfig(start_at_index=PAGE_SIZE))+ captured: list[int] = []++ def fake_fetch(session, url, headers, payload, logger):+ captured.append(payload["start_at_index"])+ return {"data": [{"id": "r", "type": "Alert", "data": {}}], "next_page_token": None}++ with (+ mock.patch.object(orca_security, "make_tracked_session"),+ mock.patch.object(orca_security, "_fetch_page", side_effect=fake_fetch),+ ):+ list(get_rows("tok", "us", "alerts", mock.MagicMock(), manager)) # type: ignore[arg-type]++ # First fetch continues from the saved offset rather than 0.+ assert captured[0] == PAGE_SIZE++ def test_incremental_value_only_formatted_when_used(self) -> None:+ manager = FakeManager()+ captured: list[dict] = []++ def fake_fetch(session, url, headers, payload, logger):+ captured.append(payload)+ return {"data": [], "next_page_token": None}++ with (+ mock.patch.object(orca_security, "make_tracked_session"),+ mock.patch.object(orca_security, "_fetch_page", side_effect=fake_fetch),+ ):+ list(+ get_rows(+ "tok",+ "us",+ "alerts",+ mock.MagicMock(),+ manager, # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )+ assert captured[0]["query"]["with"]["values"][0]["values"] == ["2026-01-01T00:00:00+00:00"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ (200, True),+ (401, False),+ (403, False),+ ]+ )+ def test_status_mapping(self, status: int, expected: bool) -> None:+ response = mock.MagicMock()+ response.status_code = status+ response.ok = status == 200+ session = mock.MagicMock()+ session.post.return_value = response+ with mock.patch.object(orca_security, "make_tracked_session", return_value=session):+ ok, _err = validate_credentials("tok", "us")+ assert ok is expected++ def test_network_error_is_failure(self) -> None:+ session = mock.MagicMock()+ session.post.side_effect = Exception("boom")+ with mock.patch.object(orca_security, "make_tracked_session", return_value=session):+ ok, err = validate_credentials("tok", "us")+ assert ok is False+ assert err is not None+++class TestOrcaSource:+ def test_alerts_is_partitioned_and_ascending(self) -> None:+ response = orca_source("tok", "us", "alerts", mock.MagicMock(), FakeManager()) # type: ignore[arg-type]+ assert response.name == "alerts"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["CreatedAt"]++ def test_full_refresh_stream_has_no_partition(self) -> None:+ response = orca_source("tok", "us", "assets", mock.MagicMock(), FakeManager()) # type: ignore[arg-type]+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/tests/test_orca_security_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/tests/test_orca_security_source.pynew file mode 100644index 000000000000..2d854ce6c541--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/orca_security/tests/test_orca_security_source.py@@ -0,0 +1,145 @@+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ 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 OrcaSecuritySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.orca_security import (+ OrcaResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.source import OrcaSecuritySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestOrcaSecuritySource:+ def setup_method(self):+ self.source = OrcaSecuritySource()+ self.team_id = 42++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.ORCASECURITY++ def test_source_is_released(self):+ # A finished source must be visible: no unreleasedSource flag, soft ALPHA label.+ config = self.source.get_source_config+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_source_config_basics(self):+ config = self.source.get_source_config+ assert config.label == "Orca Security"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/orca-security"++ def test_source_config_fields(self):+ fields = {f.name: f for f in self.source.get_source_config.fields}+ assert set(fields) == {"api_token", "region"}++ token = fields["api_token"]+ assert isinstance(token, SourceFieldInputConfig)+ assert token.type == SourceFieldInputConfigType.PASSWORD+ assert token.required is True+ assert token.secret is True++ region = fields["region"]+ assert isinstance(region, SourceFieldSelectConfig)+ assert region.defaultValue == "global"+ assert {o.value for o in region.options} == {"global", "us", "eu"}++ def test_region_change_requires_credential_reentry(self):+ # `region` retargets where the stored token is sent, so editing it must force re-entering+ # the token — dropping this would let an editor redirect the preserved credential.+ assert self.source.connection_host_fields == ["region"]++ def test_lists_tables_without_credentials(self):+ # get_schemas is a static catalog with no I/O, so public docs may render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(mock.MagicMock(), self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_alerts_is_incremental(self):+ schemas = {s.name: s for s in self.source.get_schemas(mock.MagicMock(), self.team_id)}+ assert schemas["alerts"].supports_incremental is True+ assert [f["field"] for f in schemas["alerts"].incremental_fields] == ["CreatedAt"]+ for name in ("assets", "cloud_accounts", "vulnerabilities"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filters_by_name(self):+ schemas = self.source.get_schemas(mock.MagicMock(), self.team_id, names=["alerts"])+ assert [s.name for s in schemas] == ["alerts"]++ def test_validate_credentials_delegates(self):+ config = OrcaSecuritySourceConfig(api_token="tok", region="us")+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.source.validate_orca_credentials",+ return_value=(True, None),+ ) as mock_validate:+ assert self.source.validate_credentials(config, self.team_id) == (True, None)+ mock_validate.assert_called_once_with("tok", "us")++ def test_non_retryable_errors_cover_auth(self):+ errors = self.source.get_non_retryable_errors()+ assert "401 Client Error: Unauthorized" in errors+ assert "403 Client Error: Forbidden" in errors++ def test_canonical_descriptions_present(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(ENDPOINTS).issubset(set(canonical))+ assert "id" in canonical["alerts"]["columns"]++ def test_resumable_manager_bound_to_data_class(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OrcaResumeConfig++ def test_source_for_pipeline_plumbs_config(self):+ config = OrcaSecuritySourceConfig(api_token="tok", region="eu")+ inputs = mock.MagicMock()+ inputs.schema_name = "alerts"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "CreatedAt"+ manager = mock.MagicMock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.source.orca_source"+ ) as mock_orca_source:+ self.source.source_for_pipeline(config, manager, inputs)++ mock_orca_source.assert_called_once_with(+ api_token="tok",+ region="eu",+ endpoint="alerts",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="CreatedAt",+ )++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):+ config = OrcaSecuritySourceConfig(api_token="tok", region="global")+ inputs = mock.MagicMock()+ inputs.schema_name = "assets"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "should-be-ignored"+ inputs.incremental_field = None+ manager = mock.MagicMock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.orca_security.source.orca_source"+ ) as mock_orca_source:+ self.source.source_for_pipeline(config, manager, inputs)++ assert mock_orca_source.call_args.kwargs["db_incremental_field_last_value"] is None