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 proofpoint tap import source (#112230)

Tom Owers8cd3918b76e8
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 acf218ddd801..af6ef94bb581 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -633,6 +633,7 @@ the row lists both.
| profound | HTTP | requests (rest_source.RESTClient) | ✅ |
| prompting_company | HTTP | requests | ✅ |
| promptwatch | HTTP | requests | ✅ |
+| proofpoint_tap | HTTP | requests | ✅ |
| propertyware | HTTP | requests + `rest_source.RESTClient` | ✅ |
| pulumi_cloud | HTTP | requests | ✅ |
| pylon | HTTP | requests | ✅ |
@@ -1339,7 +1340,6 @@ doesn't conflict with concurrent PRs.
- printavo
- procore
- productiv
-- proofpoint_tap
- pubnub
- quay
- quickbooks
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/proofpointtap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/proofpointtap.py
index 55758bccfdcc..b7cc5e5cbedc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/proofpointtap.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/proofpointtap.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ProofpointTapSourceConfig(config.Config):
- pass
+ service_principal: str
+ secret: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/canonical_descriptions.py
new file mode 100644
index 000000000000..0ab59c02e5dd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/canonical_descriptions.py
@@ -0,0 +1,47 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.settings import API_DOCS_URL
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "clicks_blocked": {
+ "description": "Blocked clicks on malicious URLs.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique click identifier.",
+ "clickTime": "Time of the click.",
+ "threatID": "Threat identifier.",
+ "query_end_time": "End of the query interval that returned this event, added by PostHog.",
+ },
+ },
+ "clicks_permitted": {
+ "description": "Permitted clicks on malicious URLs.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique click identifier.",
+ "clickTime": "Time of the click.",
+ "threatTime": "Time when Proofpoint identified the threat.",
+ "query_end_time": "End of the query interval that returned this event, added by PostHog.",
+ },
+ },
+ "messages_blocked": {
+ "description": "Quarantined messages with detected threats.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "GUID": "Unique message identifier in Proofpoint Protection Server.",
+ "messageTime": "Time of delivery or quarantine.",
+ "threatsInfoMap": "Threat details for this message.",
+ "query_end_time": "End of the query interval that returned this event, added by PostHog.",
+ },
+ },
+ "messages_delivered": {
+ "description": "Delivered messages with detected threats.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "GUID": "Unique message identifier in Proofpoint Protection Server.",
+ "messageTime": "Time of delivery or quarantine.",
+ "threatsInfoMap": "Threat details for this message.",
+ "query_end_time": "End of the query interval that returned this event, added by PostHog.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/proofpoint_tap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/proofpoint_tap.py
new file mode 100644
index 000000000000..4c980a2180fe
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/proofpoint_tap.py
@@ -0,0 +1,178 @@
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any, ClassVar
+
+from requests import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.proofpointtap import (
+ ProofpointTapSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.settings import (
+ AUTH_ERRORS,
+ BASE_URL,
+ ENDPOINTS,
+ MIN_WINDOW,
+ OVERLAP,
+ RETENTION,
+ WINDOW,
+)
+
+
+@frozen
+class TapCursor:
+ cursor_kind: ClassVar[str] = "proofpoint_tap_query_end"
+ query_end_time: str
+
+
+@frozen
+class TapResumeState:
+ next_start: str
+ end: str
+
+
+def parse_timestamp(value: str | datetime) -> datetime:
+ result = datetime.fromisoformat(value) if isinstance(value, str) else value
+ if result.tzinfo is None:
+ result = result.replace(tzinfo=UTC)
+ return result.astimezone(UTC)
+
+
+def get_resource(
+ config: ProofpointTapSourceConfig,
+ endpoint: str,
+ params: dict[str, Any],
+ team_id: int,
+ job_id: str,
+ api_version: str,
+) -> Resource:
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"{BASE_URL}/{api_version}/siem/",
+ "auth": {"type": "http_basic", "username": config.service_principal, "password": config.secret},
+ "paginator": "single_page",
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": 60,
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": settings.path,
+ "params": {"format": "json", **params},
+ "data_selector": "$",
+ "data_selector_required": True,
+ },
+ }
+ ],
+ }
+ return rest_api_resource(rest_config, team_id, job_id, None)
+
+
+def validate_credentials(
+ config: ProofpointTapSourceConfig, team_id: int, schema_name: str | None, api_version: str
+) -> tuple[bool, str | None]:
+ try:
+ list(get_resource(config, schema_name or "clicks_blocked", {"sinceSeconds": 30}, team_id, "", api_version))
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status == 403 and schema_name is None:
+ return True, None
+ if status is not None and status in AUTH_ERRORS:
+ return False, AUTH_ERRORS[status]
+ raise
+ return True, None
+
+
+def proofpoint_tap_source(
+ config: ProofpointTapSourceConfig,
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[TapResumeState],
+ cursor_manager: SourceCursorManager[TapCursor],
+ api_version: str,
+) -> SourceResponse:
+ settings = schema_for_resource(ENDPOINTS, inputs.schema_name)
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ now = datetime.now(UTC).replace(second=0, microsecond=0)
+ # Leave time for the first request before the oldest interval expires.
+ earliest = now - RETENTION + 2 * OVERLAP
+ end = now - OVERLAP
+ start = earliest
+ cursor = cursor_manager.load() if inputs.should_use_incremental_field else None
+ if cursor is not None:
+ start = max(earliest, parse_timestamp(cursor.query_end_time) - OVERLAP)
+ elif inputs.should_use_incremental_field and inputs.db_incremental_field_last_value is not None:
+ start = max(earliest, parse_timestamp(inputs.db_incremental_field_last_value) - OVERLAP)
+
+ resume = manager.load_state() if manager.can_resume() else None
+ if resume is not None:
+ start = max(earliest, parse_timestamp(resume.next_start))
+ end = min(end, parse_timestamp(resume.end))
+
+ last_end: datetime | None = None
+ while end - start >= MIN_WINDOW:
+ window_end = min(start + WINDOW, end)
+ resource = get_resource(
+ config,
+ inputs.schema_name,
+ {"interval": f"{start.isoformat()}/{window_end.isoformat()}"},
+ inputs.team_id,
+ inputs.job_id,
+ api_version,
+ )
+ payloads = [payload for page in resource for payload in page]
+ if len(payloads) != 1 or not isinstance(payloads[0], dict):
+ raise ValueError("Proofpoint TAP returned an invalid response. Retry the sync.")
+ payload = payloads[0]
+ raw_end = payload.get("queryEndTime")
+ rows = payload.get(settings.selector)
+ if (
+ not isinstance(raw_end, str)
+ or not isinstance(rows, list)
+ or any(not isinstance(row, dict) for row in rows)
+ ):
+ raise ValueError("Proofpoint TAP returned an invalid response. Retry the sync.")
+ query_end = parse_timestamp(raw_end)
+ if query_end != window_end:
+ raise ValueError("Proofpoint TAP returned an invalid query end time. Retry the sync.")
+ if any(not row.get(settings.primary_key) for row in rows):
+ raise ValueError("Proofpoint TAP returned an event without its unique ID. Retry the sync.")
+
+ # Event timestamps can predate detection, so only the queried interval can advance the cursor.
+ for row in rows:
+ row["query_end_time"] = query_end
+ manager.save_state(TapResumeState(next_start=query_end.isoformat(), end=end.isoformat()))
+ if rows:
+ yield rows
+ manager.safe_point()
+ last_end = query_end
+ start = query_end
+
+ if last_end is not None:
+ cursor_manager.stage(TapCursor(query_end_time=last_end.isoformat()))
+ elif resume is not None and start >= end:
+ cursor_manager.stage(TapCursor(query_end_time=end.isoformat()))
+
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=items,
+ primary_keys=[settings.primary_key],
+ partition_keys=[settings.event_time],
+ partition_mode="datetime",
+ partition_format="month",
+ sort_mode="desc",
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/settings.py
new file mode 100644
index 000000000000..4ea90b419cf8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/settings.py
@@ -0,0 +1,44 @@
+from datetime import timedelta
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+
+BASE_URL = "https://tap-api-v2.proofpoint.com"
+API_VERSION = "v2"
+API_DOCS_URL = "https://help.proofpoint.com/Threat_Insight_Dashboard/API_Documentation/SIEM_API"
+RETENTION = timedelta(days=7)
+WINDOW = timedelta(hours=1)
+MIN_WINDOW = timedelta(seconds=30)
+OVERLAP = timedelta(minutes=1)
+
+
+@frozen
+class TapEndpoint:
+ path: str
+ selector: str
+ primary_key: str
+ event_time: str
+
+
+ENDPOINTS = {
+ "clicks_blocked": TapEndpoint(
+ path="clicks/blocked", selector="clicksBlocked", primary_key="id", event_time="clickTime"
+ ),
+ "clicks_permitted": TapEndpoint(
+ path="clicks/permitted", selector="clicksPermitted", primary_key="id", event_time="clickTime"
+ ),
+ "messages_blocked": TapEndpoint(
+ path="messages/blocked", selector="messagesBlocked", primary_key="GUID", event_time="messageTime"
+ ),
+ "messages_delivered": TapEndpoint(
+ path="messages/delivered", selector="messagesDelivered", primary_key="GUID", event_time="messageTime"
+ ),
+}
+
+INCREMENTAL_FIELDS = {name: [incremental_field("query_end_time")] for name in ENDPOINTS}
+
+AUTH_ERRORS = {
+ 401: "Proofpoint TAP authentication failed. Check your service principal and secret.",
+ 403: "Your Proofpoint TAP credentials cannot access this customer's data. Check access in the TAP dashboard.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/source.py
index 6336a55e96f9..84d922bcd4d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/source.py
@@ -1,27 +1,141 @@
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,
+)
+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.cursor import CursorSource
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.proofpointtap import (
ProofpointTapSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.proofpoint_tap import (
+ TapCursor,
+ TapResumeState,
+ parse_timestamp,
+ proofpoint_tap_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.settings import (
+ API_DOCS_URL,
+ API_VERSION,
+ AUTH_ERRORS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ProofpointTapSource(SimpleSource[ProofpointTapSourceConfig]):
+class ProofpointTapSource(ResumableSource[ProofpointTapSourceConfig, TapResumeState], CursorSource[TapCursor]):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PROOFPOINTTAP
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERRORS[401],
+ "403 Client Error": AUTH_ERRORS[403],
+ "Service Id / Credentials authentication failed": AUTH_ERRORS[401],
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def cursor_class(self) -> type[TapCursor]:
+ return TapCursor
+
+ def merge_cursors(self, current: TapCursor, candidate: TapCursor) -> TapCursor:
+ return max((current, candidate), key=lambda cursor: parse_timestamp(cursor.query_end_time))
+
+ def get_schemas(
+ self,
+ config: ProofpointTapSourceConfig,
+ 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=ENDPOINTS)
+
+ def validate_credentials(
+ self,
+ config: ProofpointTapSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, team_id, schema_name, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TapResumeState]:
+ return ResumableSourceManager(inputs, TapResumeState)
+
+ def source_for_pipeline(
+ self,
+ config: ProofpointTapSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TapResumeState],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return proofpoint_tap_source(
+ config,
+ inputs,
+ resumable_source_manager,
+ self.get_cursor_manager(inputs),
+ self.resolve_api_version(inputs.api_version),
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.PROOFPOINTTAP,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Proofpoint, Inc. (Targeted Attack Protection)",
+ label="Proofpoint TAP",
+ caption="Create a service principal and secret in the TAP dashboard under Settings > Connected Applications. "
+ "A TAP subscription is required. The API retains seven days of events. Sync at least once each day.",
+ docsUrl=API_DOCS_URL,
iconPath="/static/services/proofpoint_tap.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="service_principal",
+ label="Service principal",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="secret",
+ label="Secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/tests/test_proofpoint_tap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/tests/test_proofpoint_tap.py
new file mode 100644
index 000000000000..2ffae5af9649
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/tests/test_proofpoint_tap.py
@@ -0,0 +1,270 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime, timedelta
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+import time_machine
+from unittest.mock import MagicMock, patch
+
+import responses
+from requests import HTTPError, PreparedRequest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.proofpointtap import (
+ ProofpointTapSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.proofpoint_tap import (
+ TapCursor,
+ TapResumeState,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.source import ProofpointTapSource
+
+NOW = datetime(2026, 1, 8, 12, tzinfo=UTC)
+BASE = "https://tap-api-v2.proofpoint.com/v2/siem"
+CONFIG = ProofpointTapSourceConfig.from_dict({"service_principal": "example-principal", "secret": "example-secret"})
+
+
+class Harness:
+ def __init__(
+ self,
+ endpoint: str = "clicks_blocked",
+ incremental: bool = True,
+ watermark: str | datetime | None = NOW - timedelta(hours=2),
+ stored: TapCursor | None = None,
+ resume: TapResumeState | None = None,
+ ) -> None:
+ self.source = ProofpointTapSource()
+ self.cursor = SourceCursorManager(TapCursor, stored, self.source)
+ self.manager = MagicMock(spec=ResumableSourceManager)
+ self.manager.can_resume.return_value = resume is not None
+ self.manager.load_state.return_value = resume
+ self.inputs = SourceInputs(
+ schema_name=endpoint,
+ schema_id="schema-test",
+ source_id="source-test",
+ team_id=1,
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=watermark,
+ db_incremental_field_earliest_value=None,
+ incremental_field="query_end_time",
+ incremental_field_type=None,
+ job_id="job-test",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ source_cursor=self.cursor,
+ )
+ self.response = self.source.source_for_pipeline(CONFIG, self.manager, self.inputs)
+
+ def rows(self) -> list[dict[str, Any]]:
+ return [row for batch in cast(Iterable[list[dict[str, Any]]], self.response.items()) for row in batch]
+
+
+def query(request: PreparedRequest) -> dict[str, list[str]]:
+ return parse_qs(urlparse(request.url or "").query)
+
+
+def add_windows(path: str, selector: str, rows: list[dict[str, Any]]) -> None:
+ def callback(request: PreparedRequest) -> tuple[int, dict[str, str], str]:
+ end = query(request)["interval"][0].split("/")[1]
+ return 200, {"Content-Type": "application/json"}, json.dumps({"queryEndTime": end, selector: rows})
+
+ responses.add_callback(responses.GET, f"{BASE}/{path}", callback=callback)
+
+
+ ("endpoint", "path", "selector", "key", "event_time"),
+ [
+ ("clicks_blocked", "clicks/blocked", "clicksBlocked", "id", "clickTime"),
+ ("clicks_permitted", "clicks/permitted", "clicksPermitted", "id", "clickTime"),
+ ("messages_blocked", "messages/blocked", "messagesBlocked", "GUID", "messageTime"),
+ ("messages_delivered", "messages/delivered", "messagesDelivered", "GUID", "messageTime"),
+ ],
+)
+@time_machine.travel(NOW, tick=False)
+def test_windows_auth_and_late_events(endpoint: str, path: str, selector: str, key: str, event_time: str) -> None:
+ old_event = "2025-12-20T05:00:00Z"
+ add_windows(path, selector, [{key: "event-a", event_time: old_event, "recipient": "[email protected]"}])
+ harness = Harness(endpoint=endpoint)
+ rows = harness.rows()
+
+ assert len(responses.calls) == 2
+ assert [query(call.request)["interval"][0] for call in responses.calls] == [
+ "2026-01-08T09:59:00+00:00/2026-01-08T10:59:00+00:00",
+ "2026-01-08T10:59:00+00:00/2026-01-08T11:59:00+00:00",
+ ]
+ assert all(query(call.request)["format"] == ["json"] for call in responses.calls)
+ assert responses.calls[0].request.headers["Authorization"] == ("Basic ZXhhbXBsZS1wcmluY2lwYWw6ZXhhbXBsZS1zZWNyZXQ=")
+ assert rows[0][event_time] == old_event
+ assert rows[-1]["query_end_time"] == NOW - timedelta(minutes=1)
+ assert harness.response.primary_keys == [key]
+ assert harness.response.partition_keys == [event_time]
+ assert harness.response.sort_mode == "desc"
+ assert harness.cursor.staged == TapCursor(query_end_time="2026-01-08T11:59:00+00:00")
+ assert harness.manager.save_state.call_count == 2
+ assert harness.manager.safe_point.call_count == 2
+ harness.manager.clear_state.assert_not_called()
+ assert harness.response.on_complete is not None
+ harness.response.on_complete()
+ harness.manager.clear_state.assert_called_once()
+
+
[email protected]("incremental", [False, True])
+@time_machine.travel(NOW, tick=False)
+def test_backfill_is_bounded_and_full_refresh_ignores_saved_cursor(incremental: bool) -> None:
+ add_windows("clicks/blocked", "clicksBlocked", [])
+ harness = Harness(
+ incremental=incremental,
+ watermark=None if incremental else NOW,
+ stored=None if incremental else TapCursor(query_end_time=NOW.isoformat()),
+ )
+ assert harness.rows() == []
+ assert len(responses.calls) == 168
+ intervals = [query(call.request)["interval"][0].split("/") for call in responses.calls]
+ assert intervals[0][0] == "2026-01-01T12:02:00+00:00"
+ assert intervals[-1][1] == "2026-01-08T11:59:00+00:00"
+ assert all(
+ timedelta(seconds=30) <= datetime.fromisoformat(b) - datetime.fromisoformat(a) <= timedelta(hours=1)
+ for a, b in intervals
+ )
+ assert harness.cursor.staged is not None
+ assert harness.manager.safe_point.call_count == 168
+
+
[email protected]("watermark", ["2025-01-01T00:00:00Z", datetime(2025, 1, 1), datetime(2025, 1, 1, tzinfo=UTC)])
+@time_machine.travel(NOW, tick=False)
+def test_expired_watermark_is_clamped_to_retention(watermark: str | datetime) -> None:
+ add_windows("clicks/blocked", "clicksBlocked", [])
+ harness = Harness(watermark=watermark)
+ harness.rows()
+ assert query(responses.calls[0].request)["interval"][0].startswith("2026-01-01T12:02:00+00:00/")
+ assert len(responses.calls) == 168
+
+
+@time_machine.travel(NOW, tick=False)
+def test_empty_windows_advance_durable_cursor_and_take_priority_over_row_watermark() -> None:
+ add_windows("clicks/blocked", "clicksBlocked", [])
+ harness = Harness(stored=TapCursor(query_end_time="2026-01-08T11:00:00Z"), watermark="2025-12-20T00:00:00Z")
+ assert harness.rows() == []
+ assert len(responses.calls) == 1
+ assert query(responses.calls[0].request)["interval"] == ["2026-01-08T10:59:00+00:00/2026-01-08T11:59:00+00:00"]
+ assert harness.cursor.staged == TapCursor(query_end_time="2026-01-08T11:59:00+00:00")
+
+
[email protected]("next_start", ["2026-01-08T11:00:00Z", "2026-01-08T11:30:00Z"])
+@time_machine.travel(NOW, tick=False)
+def test_resume_keeps_original_upper_bound_and_completed_cursor(next_start: str) -> None:
+ add_windows("clicks/blocked", "clicksBlocked", [])
+ harness = Harness(resume=TapResumeState(next_start=next_start, end="2026-01-08T11:30:00Z"))
+ assert harness.rows() == []
+ assert len(responses.calls) == (1 if "11:00" in next_start else 0)
+ if responses.calls:
+ assert query(responses.calls[0].request)["interval"] == ["2026-01-08T11:00:00+00:00/2026-01-08T11:30:00+00:00"]
+ assert harness.cursor.staged == TapCursor(query_end_time="2026-01-08T11:30:00+00:00")
+
+
[email protected]("watermark", [NOW, NOW + timedelta(days=1), "2026-01-08T11:59:50Z"])
+@time_machine.travel(NOW, tick=False)
+def test_no_request_for_future_or_short_interval(watermark: str | datetime) -> None:
+ harness = Harness(watermark=watermark)
+ assert harness.rows() == []
+ assert len(responses.calls) == 0
+ assert harness.cursor.staged is None
+
+
+ "payload",
+ [
+ {},
+ {"queryEndTime": "2026-01-08T10:59:00Z"},
+ {"queryEndTime": None, "clicksBlocked": []},
+ {"queryEndTime": "invalid-time", "clicksBlocked": []},
+ {"queryEndTime": "2026-01-08T10:59:00Z", "clicksBlocked": {}},
+ {"queryEndTime": "2026-01-08T10:59:00Z", "clicksBlocked": ["bad"]},
+ {"queryEndTime": "2026-01-08T10:59:00Z", "clicksBlocked": [{}]},
+ {"queryEndTime": "2026-01-08T09:59:00Z", "clicksBlocked": []},
+ {"queryEndTime": "2026-01-08T10:30:00Z", "clicksBlocked": []},
+ {"queryEndTime": "2026-01-08T12:00:00Z", "clicksBlocked": []},
+ ],
+)
+@time_machine.travel(NOW, tick=False)
+def test_bad_response_never_advances_state(payload: dict[str, Any]) -> None:
+ responses.get(f"{BASE}/clicks/blocked", json=payload)
+ harness = Harness()
+ with pytest.raises(ValueError):
+ harness.rows()
+ harness.manager.save_state.assert_not_called()
+ assert harness.cursor.staged is None
+
+
[email protected]("status", [401, 403, 429, 500])
+@time_machine.travel(NOW, tick=False)
+def test_error_classification_preserves_checkpoint(status: int) -> None:
+ responses.get(f"{BASE}/clicks/blocked", json={"queryEndTime": "2026-01-08T10:59:00Z", "clicksBlocked": []})
+ responses.get(
+ f"{BASE}/clicks/blocked",
+ status=status,
+ json={"message": "Error : Service Id / Credentials authentication failed"} if status == 401 else {},
+ )
+ harness = Harness()
+ expected = RESTClientRetryableError if status >= 429 else HTTPError
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client._retry_wait_seconds",
+ return_value=0,
+ ):
+ with patch("tenacity.nap.time.sleep"):
+ with pytest.raises(expected) as error:
+ harness.rows()
+ if status in (401, 403):
+ assert any(pattern in str(error.value) for pattern in harness.source.get_non_retryable_errors())
+ assert len(responses.calls) == 2
+ else:
+ assert len(responses.calls) > 2
+ assert harness.manager.save_state.call_count == 1
+ assert harness.manager.save_state.call_args.args[0].next_start == "2026-01-08T10:59:00+00:00"
+ assert harness.cursor.staged is None
+
+
+ ("status", "schema", "valid", "message"),
+ [
+ (200, None, True, None),
+ (401, None, False, "Check your service principal and secret"),
+ (403, None, True, None),
+ (403, "messages_blocked", False, "Check access in the TAP dashboard"),
+ ],
+)
+def test_credential_probe_status_mapping(status: int, schema: str | None, valid: bool, message: str | None) -> None:
+ path = "messages/blocked" if schema else "clicks/blocked"
+ selector = "messagesBlocked" if schema else "clicksBlocked"
+ responses.get(f"{BASE}/{path}", status=status, json={"queryEndTime": NOW.isoformat(), selector: []})
+ result, error = ProofpointTapSource().validate_credentials(CONFIG, 1, schema)
+ assert result is valid
+ if message is None:
+ assert error is None
+ else:
+ assert error is not None and message in error
+ assert len(responses.calls) == 1
+ assert query(responses.calls[0].request) == {"format": ["json"], "sinceSeconds": ["30"]}
+
+
+def test_unexpected_probe_error_is_not_bad_credentials() -> None:
+ responses.get(f"{BASE}/clicks/blocked", status=400, json={})
+ with pytest.raises(HTTPError):
+ ProofpointTapSource().validate_credentials(CONFIG, 1)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/tests/test_proofpoint_tap_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/tests/test_proofpoint_tap_source.py
new file mode 100644
index 000000000000..d9a87a4d764f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/proofpoint_tap/tests/test_proofpoint_tap_source.py
@@ -0,0 +1,19 @@
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.proofpoint_tap import TapCursor
+from products.warehouse_sources.backend.temporal.data_imports.sources.proofpoint_tap.source import ProofpointTapSource
+
+
+ ("candidate", "expected"),
+ [
+ ("2026-01-08T12:00:00Z", "2026-01-08T12:00:00Z"),
+ ("2026-01-08T10:00:00Z", "2026-01-08T11:00:00Z"),
+ ("2026-01-08T12:00:00+02:00", "2026-01-08T11:00:00Z"),
+ ],
+)
+def test_cursor_never_moves_back(candidate: str, expected: str) -> None:
+ cursor = ProofpointTapSource().merge_cursors(
+ TapCursor(query_end_time="2026-01-08T11:00:00Z"), TapCursor(query_end_time=candidate)
+ )
+ assert cursor.query_end_time == expected