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 the abnormal security (abnormal ai) import source (#112201)

Tom Owers4536b6d992b0
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 3d7e17be5b96..075532df1be7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -51,6 +51,7 @@ the row lists both.
| Source | Comm method | Primary library | Tracked transport |
| -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
| ably | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| abnormal_security | HTTP | requests | ✅ |
| acast | HTTP | requests | ✅ |
| acculynx | HTTP | requests + `rest_source.RESTClient` | ✅ |
| adjust | HTTP | requests | ✅ |
@@ -927,7 +928,6 @@ doesn't conflict with concurrent PRs.
- \*\*Migrate
- \*\*Switch
- ab_tasty
-- abnormal_security
- actionstep
- active_campaign
- acuity_scheduling
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/abnormal_security.py b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/abnormal_security.py
new file mode 100644
index 000000000000..75167094b275
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/abnormal_security.py
@@ -0,0 +1,173 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.settings import (
+ ENDPOINTS,
+ REGION_HOSTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import rest_api_resources
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+ RESTAPIConfig,
+)
+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 schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.abnormalsecurity import (
+ AbnormalSecuritySourceConfig,
+)
+
+AUTH_ERRORS = {
+ "401 Client Error": "Your Abnormal API token is invalid or expired. Create a new token and reconnect.",
+ "403 Client Error": "Abnormal denied access. Check your token permissions, product licenses, and IP allowlist.",
+}
+
+
+@frozen
+class AbnormalSecurityResumeConfig:
+ filter_value: str
+ paginator_state: dict[str, Any]
+
+
+def client_config(config: AbnormalSecuritySourceConfig, api_version: str | None = None) -> ClientConfig:
+ if config.region not in REGION_HOSTS:
+ raise ValueError("Select a supported Abnormal region: US or EU.")
+ version = api_version or "v1"
+ if version != "v1":
+ raise ValueError("Unsupported Abnormal API version. Use v1.")
+ return {
+ "base_url": f"{REGION_HOSTS[config.region]}/{version}/",
+ "auth": {"type": "bearer", "token": config.api_key},
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": 60,
+ "capture": False,
+ "paginator": {
+ "type": "cursor",
+ "cursor_path": "nextPageNumber",
+ "cursor_param": "pageNumber",
+ "raise_on_repeated_cursor": True,
+ },
+ }
+
+
+def validate_credentials(
+ config: AbnormalSecuritySourceConfig, team_id: int, api_version: str | None = None
+) -> tuple[bool, str | None]:
+ try:
+ resource = rest_api_resources(
+ {
+ "client": client_config(config, api_version),
+ "resources": [
+ {
+ "name": "credential_check",
+ "endpoint": {
+ "path": "threats",
+ "params": {
+ "pageSize": 1,
+ "filter": f"receivedTime lte {datetime.now(UTC).strftime('%Y-%m-%dT%H:%M:%SZ')}",
+ },
+ "data_selector": "threats",
+ "data_selector_required": True,
+ "paginator": "single_page",
+ },
+ }
+ ],
+ },
+ team_id,
+ "",
+ None,
+ )[0]
+ next(iter(resource), None)
+ except ValueError as error:
+ return False, str(error)
+ except HTTPError as error:
+ for pattern, message in AUTH_ERRORS.items():
+ if pattern in str(error):
+ return False, message
+ raise
+ return True, None
+
+
+def abnormal_security_source(
+ config: AbnormalSecuritySourceConfig,
+ manager: ResumableSourceManager[AbnormalSecurityResumeConfig],
+ inputs: SourceInputs,
+) -> SourceResponse:
+ endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)
+ resume = manager.load_state() if manager.can_resume() else None
+ if resume:
+ filter_value = resume.filter_value
+ else:
+ start = datetime(1970, 1, 1, tzinfo=UTC)
+ if endpoint.incremental_field and inputs.should_use_incremental_field:
+ watermark = inputs.db_incremental_field_last_value
+ if watermark is not None:
+ parsed = parse_datetime_value(watermark)
+ if parsed is None:
+ raise ValueError("Invalid Abnormal incremental timestamp. Reset the table and try again.")
+ start = parsed
+ lower = start.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ upper = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ # Without a filter, Abnormal returns only the top 100 records and ignores pagination.
+ filter_value = f"{endpoint.filter_field} gte {lower} lte {upper}"
+
+ parent_name = f"{inputs.schema_name}_ids" if endpoint.detail_path else inputs.schema_name
+ params: dict[str, Any] = {"filter": filter_value, "pageSize": 100, "pageNumber": 1}
+ if inputs.schema_name == "threats":
+ params["source"] = "all"
+ resources: list[str | EndpointResource] = [
+ {
+ "name": parent_name,
+ "endpoint": {
+ "path": endpoint.path,
+ "params": params,
+ "data_selector": endpoint.selector,
+ "data_selector_required": True,
+ },
+ }
+ ]
+ if endpoint.detail_path:
+ resources.append(
+ {
+ "name": inputs.schema_name,
+ "endpoint": {
+ "path": endpoint.detail_path,
+ "params": {"id": {"type": "resolve", "resource": parent_name, "field": endpoint.primary_key}},
+ "data_selector": "$",
+ # Threat details contain a limited message sample; the table grain is one campaign.
+ "paginator": "single_page",
+ },
+ }
+ )
+ rest_config: RESTAPIConfig = {"client": client_config(config, inputs.api_version), "resources": resources}
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ manager.save_state(AbnormalSecurityResumeConfig(filter_value=filter_value, paginator_state=state))
+
+ resource = rest_api_resources(
+ rest_config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )[-1]
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=lambda: resource,
+ primary_keys=[endpoint.primary_key],
+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,
+ partition_mode="datetime" if endpoint.partition_key else None,
+ partition_format="month" if endpoint.partition_key else None,
+ # The API does not guarantee ascending order, so the watermark must use the batch maximum.
+ sort_mode="desc",
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/canonical_descriptions.py
new file mode 100644
index 000000000000..4e4390bf0e28
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/canonical_descriptions.py
@@ -0,0 +1,43 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.settings import API_DOCS_URL
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "threats": {
+ "description": "Email threat campaigns detected by Abnormal, with recipient counts and a limited sample of messages.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "threatId": "Identifier of the threat campaign, which can affect multiple recipients.",
+ "recipientCount": "Number of distinct recipients who received messages from this campaign.",
+ "messages": "Message details returned by the API. The API limits this sample to 10 messages.",
+ "tenantId": "Identifier of the tenant associated with this campaign.",
+ "tenantName": "Short name of the tenant associated with this campaign.",
+ },
+ },
+ "cases": {
+ "description": "Account takeover cases detected by Abnormal. This table requires an Account Takeover license.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "caseId": "Unique identifier of the case.",
+ "description": "Description of the case.",
+ "severity_level": "Severity assigned to the case.",
+ "confidence": "Confidence assigned to the case.",
+ "last_modified": "Time when the case was last modified.",
+ "first_observed": "Time when suspicious activity was first observed.",
+ "created": "Time when the case was created.",
+ },
+ },
+ "vendor_cases": {
+ "description": "Vendor cases with security insights and a timeline of related events.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "vendorCaseId": "Unique identifier of the vendor case.",
+ "vendorDomain": "Domain of the vendor associated with the case.",
+ "firstObservedTime": "Time when the first message associated with the case arrived.",
+ "lastModifiedTime": "Time when the case details were last modified.",
+ "insights": "Security insights associated with the vendor case.",
+ "timeline": "Timeline of events associated with the vendor case.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/settings.py
new file mode 100644
index 000000000000..ccf5f5278db1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/settings.py
@@ -0,0 +1,52 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+
+API_DOCS_URL = "https://app.swaggerhub.com/apis-docs/abnormal-security/abx/1.5.0"
+REGION_HOSTS = {
+ "us": "https://api.abnormalplatform.com",
+ "eu": "https://eu.rest.abnormalsecurity.com",
+}
+
+
+@frozen
+class AbnormalEndpoint:
+ path: str
+ selector: str
+ primary_key: str
+ filter_field: str
+ incremental_field: str | None = None
+ partition_key: str | None = None
+ detail_path: str | None = None
+
+
+ENDPOINTS = {
+ "threats": AbnormalEndpoint(
+ path="threats",
+ selector="threats",
+ primary_key="threatId",
+ filter_field="receivedTime",
+ detail_path="threats/{id}",
+ ),
+ "cases": AbnormalEndpoint(
+ path="cases",
+ selector="cases",
+ primary_key="caseId",
+ filter_field="lastModifiedTime",
+ incremental_field="last_modified",
+ partition_key="created",
+ ),
+ "vendor_cases": AbnormalEndpoint(
+ path="vendor-cases",
+ selector="vendorCases",
+ primary_key="vendorCaseId",
+ filter_field="lastModifiedTime",
+ incremental_field="lastModifiedTime",
+ partition_key="firstObservedTime",
+ detail_path="vendor-cases/{id}",
+ ),
+}
+INCREMENTAL_FIELDS = {
+ name: [incremental_field(endpoint.incremental_field)] if endpoint.incremental_field else []
+ for name, endpoint in ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/source.py
index 42a6c8316d27..d3e526e883e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/source.py
@@ -1,8 +1,39 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.abnormal_security import (
+ AUTH_ERRORS,
+ AbnormalSecurityResumeConfig,
+ abnormal_security_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.settings import (
+ API_DOCS_URL,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.abnormalsecurity import (
AbnormalSecuritySourceConfig,
)
@@ -10,11 +41,20 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AbnormalSecuritySource(SimpleSource[AbnormalSecuritySourceConfig]):
+class AbnormalSecuritySource(ResumableSource[AbnormalSecuritySourceConfig, AbnormalSecurityResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v1",)
+ default_version = "v1"
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ABNORMALSECURITY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ return ["region"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -22,6 +62,80 @@ class AbnormalSecuritySource(SimpleSource[AbnormalSecuritySourceConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Abnormal Security (Abnormal AI)",
iconPath="/static/services/abnormal_security.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Create an API token in [Abnormal Settings > Integrations > Abnormal REST API]"
+ "(https://portal.abnormalsecurity.com/home/settings/integrations). "
+ "Select your account region. Allow PostHog's outbound IP addresses if your account restricts API access. "
+ "Cases require an Account Takeover license. "
+ "Threat rows contain campaign details and the API's limited message sample."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US", value="us"),
+ SourceFieldSelectConfigOption(label="EU", value="eu"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return dict(AUTH_ERRORS)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AbnormalSecuritySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=("cases", "vendor_cases"),
+ should_sync_default={"cases": False, "vendor_cases": False},
)
+
+ def validate_credentials(
+ self,
+ config: AbnormalSecuritySourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, team_id, api_version)
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[AbnormalSecurityResumeConfig]:
+ return ResumableSourceManager(inputs, AbnormalSecurityResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AbnormalSecuritySourceConfig,
+ resumable_source_manager: ResumableSourceManager[AbnormalSecurityResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return abnormal_security_source(config, resumable_source_manager, inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/tests/test_abnormal_security.py b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/tests/test_abnormal_security.py
new file mode 100644
index 000000000000..715da3c589f3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/tests/test_abnormal_security.py
@@ -0,0 +1,206 @@
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock
+
+import responses
+import structlog
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.abnormal_security import (
+ AbnormalSecurityResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.source import (
+ AbnormalSecuritySource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.abnormalsecurity import (
+ AbnormalSecuritySourceConfig,
+)
+
+BASE = "https://api.abnormalplatform.com/v1"
+
+
+def inputs(table: str, incremental: bool = False, watermark: Any = None) -> SourceInputs:
+ return SourceInputs(
+ schema_name=table,
+ schema_id="schema-test",
+ source_id="source-test",
+ team_id=1,
+ job_id="job-test",
+ logger=structlog.get_logger(),
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=watermark,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ reset_pipeline=False,
+ api_version="v1",
+ )
+
+
+def manager(resume: AbnormalSecurityResumeConfig | None = None) -> MagicMock:
+ result = MagicMock()
+ result.can_resume.return_value = resume is not None
+ result.load_state.return_value = resume
+ return result
+
+
+def sync_items(response: SourceResponse) -> Iterable[Any]:
+ return cast(Iterable[Any], response.items())
+
+
[email protected]("terminal", [{}, {"nextPageNumber": None}])
+def test_cases_pagination_and_auth(terminal: dict[str, Any]) -> None:
+ rows = [{"caseId": "case-a", "last_modified": "2025-01-01T00:00:00Z"}, {"caseId": "case-b"}]
+ responses.get(f"{BASE}/cases", json={"cases": rows[:1], "nextPageNumber": 2})
+ responses.get(f"{BASE}/cases", json={"cases": rows[1:], **terminal})
+ checkpoint = manager()
+ result = AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), checkpoint, inputs("cases")
+ )
+ assert [row for page in sync_items(result) for row in page] == rows
+ assert len(responses.calls) == 2
+ for number, call in enumerate(responses.calls, start=1):
+ assert call.request.headers["Authorization"] == "Bearer test-token"
+ query = parse_qs(urlparse(call.request.url).query)
+ assert query["pageNumber"] == [str(number)]
+ assert query["pageSize"] == ["100"]
+ assert query["filter"][0].startswith("lastModifiedTime gte 1970-01-01T00:00:00Z lte ")
+ assert checkpoint.save_state.call_args.args[0].paginator_state == {"cursor": 2}
+ assert not checkpoint.clear_state.called
+ assert result.on_complete is not None
+ result.on_complete()
+ checkpoint.clear_state.assert_called_once()
+
+
+ ("incremental", "watermark", "expected"),
+ [
+ (False, "2025-02-01T00:00:00Z", "1970-01-01T00:00:00Z"),
+ (True, None, "1970-01-01T00:00:00Z"),
+ (True, "2025-02-01T02:00:00+02:00", "2025-02-01T00:00:00Z"),
+ (True, datetime(2025, 2, 1, tzinfo=UTC), "2025-02-01T00:00:00Z"),
+ (True, datetime(2025, 2, 1), "2025-02-01T00:00:00Z"),
+ ],
+)
[email protected]("table", ["cases", "vendor_cases"])
+def test_incremental_filter(table: str, incremental: bool, watermark: Any, expected: str) -> None:
+ path, selector = ("cases", "cases") if table == "cases" else ("vendor-cases", "vendorCases")
+ responses.get(f"{BASE}/{path}", json={selector: []})
+ result = AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), manager(), inputs(table, incremental, watermark)
+ )
+ assert list(sync_items(result)) == []
+ query = parse_qs(urlparse(responses.calls[0].request.url).query)
+ assert query["filter"][0].startswith(f"lastModifiedTime gte {expected} lte ")
+ assert result.sort_mode == "desc"
+
+
+ ("table", "path", "selector", "primary_key", "details"),
+ [
+ (
+ "threats",
+ "threats",
+ "threats",
+ "threatId",
+ {"recipientCount": 12, "messages": [{"subject": "Test message"}]},
+ ),
+ (
+ "vendor_cases",
+ "vendor-cases",
+ "vendorCases",
+ "vendorCaseId",
+ {"vendorDomain": "example.com", "lastModifiedTime": "2025-01-01T00:00:00Z"},
+ ),
+ ],
+)
+def test_detail_fanout(table: str, path: str, selector: str, primary_key: str, details: dict[str, Any]) -> None:
+ responses.get(f"{BASE}/{path}", json={selector: [{primary_key: "item-a"}], "nextPageNumber": 2})
+ responses.get(f"{BASE}/{path}/item-a", json={primary_key: "item-a", **details})
+ responses.get(f"{BASE}/{path}", json={selector: [{primary_key: "item-b"}]})
+ responses.get(f"{BASE}/{path}/item-b", json={primary_key: "item-b", **details})
+ result = AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), manager(), inputs(table)
+ )
+ assert [row for page in sync_items(result) for row in page] == [
+ {primary_key: "item-a", **details},
+ {primary_key: "item-b", **details},
+ ]
+ assert len(responses.calls) == 4
+ assert result.primary_keys == [primary_key]
+ for index in (1, 3):
+ assert urlparse(responses.calls[index].request.url).query == ""
+
+
+def test_resume_preserves_filter_and_page() -> None:
+ saved_filter = "lastModifiedTime gte 2025-01-01T00:00:00Z lte 2025-02-01T00:00:00Z"
+ checkpoint = manager(AbnormalSecurityResumeConfig(filter_value=saved_filter, paginator_state={"cursor": 3}))
+ responses.get(f"{BASE}/cases", json={"cases": [{"caseId": "case-c"}]})
+ result = AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), checkpoint, inputs("cases", True, "2025-01-15T00:00:00Z")
+ )
+ assert list(sync_items(result)) == [[{"caseId": "case-c"}]]
+ query = parse_qs(urlparse(responses.calls[0].request.url).query)
+ assert query["pageNumber"] == ["3"]
+ assert query["filter"] == [saved_filter]
+
+
+def test_fanout_resume_skips_completed_details() -> None:
+ checkpoint = manager(
+ AbnormalSecurityResumeConfig(
+ filter_value="receivedTime gte 1970-01-01T00:00:00Z lte 2025-02-01T00:00:00Z",
+ paginator_state={"completed": ["threats/item-a"], "current": None, "child_state": None},
+ )
+ )
+ responses.get(f"{BASE}/threats", json={"threats": [{"threatId": "item-a"}, {"threatId": "item-b"}]})
+ responses.get(f"{BASE}/threats/item-b", json={"threatId": "item-b", "messages": []})
+ result = AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), checkpoint, inputs("threats")
+ )
+ assert list(sync_items(result)) == [[{"threatId": "item-b", "messages": []}]]
+ assert len(responses.calls) == 2
+
+
[email protected]("status", [401, 403])
+def test_sync_auth_errors_match_user_messages(status: int) -> None:
+ responses.get(f"{BASE}/cases", status=status, json={"detail": "denied"})
+ source = AbnormalSecuritySource()
+ result = source.source_for_pipeline(AbnormalSecuritySourceConfig(api_key="test-token"), manager(), inputs("cases"))
+ with pytest.raises(HTTPError) as error:
+ list(sync_items(result))
+ matches = [message for pattern, message in source.get_non_retryable_errors().items() if pattern in str(error.value)]
+ assert len(matches) == 1
+ assert "test-token" not in str(error.value)
+ assert len(responses.calls) == 1
+
+
[email protected]("watermark", ["not-a-date", 123])
+def test_invalid_watermark_fails_before_request(watermark: Any) -> None:
+ with pytest.raises(ValueError, match="Invalid Abnormal incremental timestamp"):
+ AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), manager(), inputs("cases", True, watermark)
+ )
+ assert len(responses.calls) == 0
+
+
[email protected]("body", [{}, {"error": "invalid_request"}])
+def test_missing_collection_does_not_erase_table(body: dict[str, Any]) -> None:
+ responses.get(f"{BASE}/cases", json=body)
+ result = AbnormalSecuritySource().source_for_pipeline(
+ AbnormalSecuritySourceConfig(api_key="test-token"), manager(), inputs("cases")
+ )
+ with pytest.raises(ValueError):
+ list(sync_items(result))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/tests/test_abnormal_security_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/tests/test_abnormal_security_source.py
new file mode 100644
index 000000000000..103822a82a01
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/abnormal_security/tests/test_abnormal_security_source.py
@@ -0,0 +1,56 @@
+from typing import Literal, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+
+import responses
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.abnormal_security.source import (
+ AbnormalSecuritySource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.abnormalsecurity import (
+ AbnormalSecuritySourceConfig,
+)
+
+
[email protected]("region, host", [("us", "api.abnormalplatform.com"), ("eu", "eu.rest.abnormalsecurity.com")])
[email protected]("status, expected", [(200, True), (401, False), (403, False)])
+def test_credentials(region: Literal["us", "eu"], host: str, status: int, expected: bool) -> None:
+ responses.get(f"https://{host}/v1/threats", status=status, json={"threats": [], "nextPageNumber": 2})
+ source = AbnormalSecuritySource()
+ valid, message = source.validate_credentials(AbnormalSecuritySourceConfig(api_key="test-token", region=region), 1)
+ assert valid is expected
+ if expected:
+ assert message is None
+ else:
+ assert message == source.get_non_retryable_errors()[f"{status} Client Error"]
+ assert len(responses.calls) == 1
+ request = responses.calls[0].request
+ assert request.headers["Authorization"] == "Bearer test-token"
+ query = parse_qs(urlparse(request.url).query)
+ assert query["pageSize"] == ["1"]
+ assert query["filter"][0].startswith("receivedTime lte ")
+
+
[email protected]("field, value", [("region", "https://example.com"), ("api_version", "v2")])
+def test_invalid_region_or_version_makes_no_request(field: str, value: str) -> None:
+ config = AbnormalSecuritySourceConfig(api_key="test-token")
+ version = None
+ if field == "region":
+ config.region = cast(Literal["us", "eu"], value)
+ else:
+ version = value
+ valid, message = AbnormalSecuritySource().validate_credentials(config, 1, api_version=version)
+ assert not valid
+ assert message
+ assert len(responses.calls) == 0
+
+
+def test_validation_does_not_mask_unrelated_http_errors() -> None:
+ responses.get("https://api.abnormalplatform.com/v1/threats", status=404, json={})
+ with pytest.raises(HTTPError):
+ AbnormalSecuritySource().validate_credentials(AbnormalSecuritySourceConfig(api_key="test-token"), 1)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/abnormalsecurity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/abnormalsecurity.py
index 2b29ec11d567..089304148c78 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/abnormalsecurity.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/abnormalsecurity.py
@@ -1,9 +1,12 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class AbnormalSecuritySourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu"] = config.value(default="us")