: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 braze import source (#61586)
Tom Owersb2a7760a05bb
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 7b8b6d73bd2e..ac304014267f 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -49,6 +49,7 @@ the row lists both.| bamboohr | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |+| braze | HTTP | requests | ✅ || brevo | HTTP | requests | ✅ || buildbetter | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ |@@ -165,7 +166,6 @@ doesn't conflict with concurrent PRs.- bigcommerce- box- braintree-- braze- circleci- clickup- cockroachdbdiff --git a/posthog/temporal/data_imports/sources/braze/braze.py b/posthog/temporal/data_imports/sources/braze/braze.pynew file mode 100644index 000000000000..55488dbacab4--- /dev/null+++ b/posthog/temporal/data_imports/sources/braze/braze.py@@ -0,0 +1,230 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.braze.settings import BRAZE_ENDPOINTS, BrazeEndpointConfig+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5++# Shared so the source-layer 403 acceptance check can't drift from the message produced here.+BRAZE_FORBIDDEN_MSG = "Your Braze API key does not have permission for this endpoint"+HOST_NOT_ALLOWED_ERROR = "Braze REST endpoint URL is not allowed"+++class BrazeRetryableError(Exception):+ pass+++class BrazeHostNotAllowedError(Exception):+ pass+++class BrazeResumeConfig:+ # Page index (page pagination) or row offset (offset pagination) of the+ # last-yielded page, so a resume re-fetches it and merge dedupes on primary key.+ cursor: int+++def normalize_base_url(url: str) -> str:+ """Force https and strip any trailing slash so endpoint paths join cleanly.++ Forcing https prevents a downgrade to plaintext, matching the Okta/ServiceNow+ connectors that also take a user-supplied host.+ """+ url = re.sub(r"^https?://", "", url.strip(), flags=re.IGNORECASE)+ return f"https://{url.rstrip('/')}"+++def _host_from_url(base_url: str) -> str:+ return (urlparse(normalize_base_url(base_url)).hostname or "").lower()+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _format_modified_after(value: Any) -> str:+ """Format an incremental cursor value as an ISO-8601 string for Braze filters."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _build_params(config: BrazeEndpointConfig, cursor: int, modified_after: str | None) -> dict[str, Any]:+ params: dict[str, Any]+ if config.pagination == "page":+ params = {"page": cursor}+ else:+ params = {"limit": config.page_size, "offset": cursor}++ if modified_after and config.modified_after_param:+ params[config.modified_after_param] = modified_after++ return params+++def _next_cursor(config: BrazeEndpointConfig, cursor: int) -> int:+ return cursor + 1 if config.pagination == "page" else cursor + config.page_size+++def _normalize_items(config: BrazeEndpointConfig, items: list[Any]) -> list[dict[str, Any]]:+ if config.wrap_scalar_as:+ return [{config.wrap_scalar_as: item} for item in items]+ return [item for item in items if isinstance(item, dict)]+++def validate_credentials(+ api_key: str, base_url: str, path: str = "/campaigns/list", team_id: int | None = None+) -> tuple[bool, str | None]:+ """Probe a Braze list endpoint to confirm the REST API key is valid.++ Braze keys are scoped per endpoint, so a 403 means the key is genuine but+ lacks the probed scope — the caller decides whether to accept that.+ """+ # The REST endpoint URL is fully customer-controlled, so block hosts that resolve to+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ url = f"{normalize_base_url(base_url)}{path}?{urlencode({'page': 0})}"+ try:+ response = make_tracked_session(allow_redirects=False).get(url, headers=_get_headers(api_key), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Braze API key"+ if response.status_code == 403:+ return False, BRAZE_FORBIDDEN_MSG++ try:+ message = response.json().get("message", response.text)+ except Exception:+ message = response.text+ return False, message+++def get_rows(+ api_key: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrazeResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = BRAZE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ root = normalize_base_url(base_url)++ # Re-check at run time (not just at source-create) in case the URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)+ if not host_ok:+ raise BrazeHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ modified_after: str | None = None+ if config.modified_after_param and should_use_incremental_field and db_incremental_field_last_value:+ modified_after = _format_modified_after(db_incremental_field_last_value)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume_config.cursor if resume_config is not None else 0+ if resume_config is not None:+ logger.debug(f"Braze: resuming {endpoint} from cursor={cursor}")++ @retry(+ retry=retry_if_exception_type((BrazeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_cursor: int) -> dict[str, Any]:+ params = _build_params(config, page_cursor, modified_after)+ page_url = f"{root}{config.path}?{urlencode(params)}"+ response = make_tracked_session(allow_redirects=False).get(+ page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise BrazeRetryableError(f"Braze API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Braze API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(cursor)++ raw_items = data.get(config.data_key, [])+ if not raw_items:+ break++ yield _normalize_items(config, raw_items)++ # Save the cursor of the page we just yielded (not the next one) so a+ # resume re-fetches it; merge semantics on the primary key dedupe.+ resumable_source_manager.save_state(BrazeResumeConfig(cursor=cursor))++ cursor = _next_cursor(config, cursor)+++def braze_source(+ api_key: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrazeResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = BRAZE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ base_url=base_url,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ 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_key],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/braze/settings.py b/posthog/temporal/data_imports/sources/braze/settings.pynew file mode 100644index 000000000000..0e72940af1d0--- /dev/null+++ b/posthog/temporal/data_imports/sources/braze/settings.py@@ -0,0 +1,109 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Braze list endpoints paginate either with a 0-indexed ``page`` param+# (campaigns/canvas/segments/events) or a ``limit``/``offset`` pair+# (templates/content blocks). The cursor we persist for resume is the raw page+# index or row offset respectively.+PaginationStyle = Literal["page", "offset"]+++@dataclass+class BrazeEndpointConfig:+ name: str+ path: str+ # Key in the JSON response body holding the list of rows.+ data_key: str+ primary_key: str+ pagination: PaginationStyle+ page_size: int = 100+ # Stable (immutable) datetime field used for partitioning. Only set when the+ # response actually carries a creation timestamp — never an updated/last-edit+ # field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Server-side "modified since" query param. Set only for endpoints where Braze+ # genuinely filters by it (templates/email, content_blocks). When None the+ # endpoint is full-refresh only.+ modified_after_param: Optional[str] = None+ # events/list returns a bare list of event-name strings rather than objects;+ # wrap each string under this key so the row is a dict with a stable primary key.+ wrap_scalar_as: Optional[str] = None+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++BRAZE_ENDPOINTS: dict[str, BrazeEndpointConfig] = {+ "campaigns": BrazeEndpointConfig(+ name="campaigns",+ path="/campaigns/list",+ data_key="campaigns",+ primary_key="id",+ pagination="page",+ # /campaigns/list documents a `last_edit.time[gte]` filter, but its bracketed+ # param syntax is fragile and we couldn't curl-verify it filters server-side+ # (no API key available), so we ship full refresh. last_edit is also mutable,+ # so it can't serve as a partition key.+ ),+ "canvases": BrazeEndpointConfig(+ name="canvases",+ path="/canvas/list",+ data_key="canvases",+ primary_key="id",+ pagination="page",+ # See campaigns: a documented but unverified `last_edit.time[gte]` filter exists.+ ),+ "segments": BrazeEndpointConfig(+ name="segments",+ path="/segments/list",+ data_key="segments",+ primary_key="id",+ pagination="page",+ ),+ "events": BrazeEndpointConfig(+ name="events",+ path="/events/list",+ data_key="events",+ primary_key="event_name",+ pagination="page",+ page_size=250,+ wrap_scalar_as="event_name",+ ),+ "email_templates": BrazeEndpointConfig(+ name="email_templates",+ path="/templates/email/list",+ data_key="templates",+ primary_key="email_template_id",+ pagination="offset",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at")],+ modified_after_param="modified_after",+ ),+ "content_blocks": BrazeEndpointConfig(+ name="content_blocks",+ path="/content_blocks/list",+ data_key="content_blocks",+ primary_key="content_block_id",+ pagination="offset",+ partition_key="created_at",+ # The mutable field on a content block is `last_edited`; offer it as the+ # incremental cursor since the server-side `modified_after` filter keys off it.+ incremental_fields=[_datetime_field("last_edited")],+ modified_after_param="modified_after",+ ),+}++ENDPOINTS = tuple(BRAZE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BRAZE_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/braze/source.py b/posthog/temporal/data_imports/sources/braze/source.pyindex 1a5d5d6def08..6428b4e8bd7d 100644--- a/posthog/temporal/data_imports/sources/braze/source.py+++ b/posthog/temporal/data_imports/sources/braze/source.py@@ -1,19 +1,32 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.braze.braze import (+ BRAZE_FORBIDDEN_MSG,+ BrazeResumeConfig,+ braze_source,+ validate_credentials as validate_braze_credentials,+)+from posthog.temporal.data_imports.sources.braze.settings import BRAZE_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import BrazeSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class BrazeSource(SimpleSource[BrazeSourceConfig]):+class BrazeSource(ResumableSource[BrazeSourceConfig, BrazeResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BRAZE@@ -22,7 +35,114 @@ class BrazeSource(SimpleSource[BrazeSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.BRAZE,- iconPath="/static/services/braze.png",- fields=cast(list[FieldType], []),+ label="Braze",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Braze REST API key and endpoint to sync your Braze data into the PostHog Data warehouse.++You can create a REST API key in your Braze dashboard under **Settings → API Keys**. Grant the following endpoint permissions for the data you want to sync:+- `campaigns.list`+- `canvas.list`+- `segments.list`+- `events.list`+- `templates.email.list`+- `content_blocks.list`++Your REST endpoint must match your Braze dashboard's region — see [Braze's API overview](https://www.braze.com/docs/api/basics/#endpoints) for the list of endpoints.""",+ iconPath="/static/services/braze.png",+ docsUrl="https://posthog.com/docs/cdp/sources/braze",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="REST API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="url",+ label="REST endpoint URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://rest.iad-01.braze.com",+ secret=False,+ ),+ ],+ ),+ )++ @property+ def connection_host_fields(self) -> list[str]:+ # The REST API key is sent to whatever host `url` points at, so retargeting+ # it must re-require the key (prevents credential exfiltration to another host).+ return ["url"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Braze API key. Please generate a new REST API key and reconnect.",+ "403 Client Error": "Your Braze API key lacks permission for this endpoint. Grant the required endpoint permission and try again.",+ }++ def get_schemas(+ self,+ config: BrazeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: BrazeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in BRAZE_ENDPOINTS:+ return False, f"Unknown Braze schema: {schema_name!r}"+ path = BRAZE_ENDPOINTS[schema_name].path if schema_name is not None else "/campaigns/list"+ valid, error = validate_braze_credentials(config.api_key, config.url, path, team_id)++ # A scoped key may legitimately lack the probe endpoint's permission at+ # source-create time; only enforce per-endpoint scope when validating a+ # specific schema.+ if not valid and schema_name is None and error == BRAZE_FORBIDDEN_MSG:+ return True, None++ return valid, error++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrazeResumeConfig]:+ return ResumableSourceManager[BrazeResumeConfig](inputs, BrazeResumeConfig)++ def source_for_pipeline(+ self,+ config: BrazeSourceConfig,+ resumable_source_manager: ResumableSourceManager[BrazeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return braze_source(+ api_key=config.api_key,+ base_url=config.url,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ 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,)diff --git a/posthog/temporal/data_imports/sources/braze/tests/test_braze.py b/posthog/temporal/data_imports/sources/braze/tests/test_braze.pynew file mode 100644index 000000000000..ca2e941374cd--- /dev/null+++ b/posthog/temporal/data_imports/sources/braze/tests/test_braze.py@@ -0,0 +1,328 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.braze.braze import (+ BrazeHostNotAllowedError,+ BrazeResumeConfig,+ _build_params,+ _format_modified_after,+ _next_cursor,+ _normalize_items,+ braze_source,+ get_rows,+ normalize_base_url,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.braze.settings import BRAZE_ENDPOINTS, ENDPOINTS++BASE_URL = "https://rest.iad-01.braze.com"+++def _make_manager(resume_state: BrazeResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: dict[str, Any], status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = 200 <= status_code < 400+ return resp+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://rest.iad-01.braze.com", "https://rest.iad-01.braze.com"),+ ("https://rest.iad-01.braze.com/", "https://rest.iad-01.braze.com"),+ ("https://rest.iad-01.braze.com///", "https://rest.iad-01.braze.com"),+ # Plaintext is upgraded to https; a scheme-less host gets one.+ ("http://rest.iad-01.braze.com", "https://rest.iad-01.braze.com"),+ ("rest.iad-01.braze.com", "https://rest.iad-01.braze.com"),+ (" https://rest.iad-01.braze.com ", "https://rest.iad-01.braze.com"),+ ],+ )+ def test_normalizes_to_https(self, value, expected):+ assert normalize_base_url(value) == expected+++class TestFormatModifiedAfter:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ (date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("already-a-string", "already-a-string"),+ ],+ )+ def test_format(self, value, expected):+ assert _format_modified_after(value) == expected+++class TestBuildParams:+ def test_page_pagination(self):+ params = _build_params(BRAZE_ENDPOINTS["campaigns"], cursor=3, modified_after=None)+ assert params == {"page": 3}++ def test_offset_pagination(self):+ params = _build_params(BRAZE_ENDPOINTS["email_templates"], cursor=200, modified_after=None)+ assert params == {"limit": 100, "offset": 200}++ def test_modified_after_added_only_for_incremental_endpoint(self):+ params = _build_params(BRAZE_ENDPOINTS["email_templates"], cursor=0, modified_after="2026-01-01T00:00:00+00:00")+ assert params["modified_after"] == "2026-01-01T00:00:00+00:00"++ def test_modified_after_ignored_for_full_refresh_endpoint(self):+ # campaigns has no modified_after_param, so the cutoff must never leak into params.+ params = _build_params(BRAZE_ENDPOINTS["campaigns"], cursor=0, modified_after="2026-01-01T00:00:00+00:00")+ assert "modified_after" not in params+++class TestNextCursor:+ def test_page_increments_by_one(self):+ assert _next_cursor(BRAZE_ENDPOINTS["campaigns"], 4) == 5++ def test_offset_increments_by_page_size(self):+ assert _next_cursor(BRAZE_ENDPOINTS["email_templates"], 200) == 300+++class TestNormalizeItems:+ def test_wraps_scalar_event_names(self):+ items = _normalize_items(BRAZE_ENDPOINTS["events"], ["purchase", "login"])+ assert items == [{"event_name": "purchase"}, {"event_name": "login"}]++ def test_drops_non_dict_rows_for_object_endpoints(self):+ items = _normalize_items(BRAZE_ENDPOINTS["campaigns"], [{"id": "a"}, "garbage", {"id": "b"}])+ assert items == [{"id": "a"}, {"id": "b"}]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid Braze API key"),+ (403, False, "Your Braze API key does not have permission for this endpoint"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_status_mapping(self, mock_session, status_code, expected_valid, expected_message):+ mock_session.return_value.get.return_value = _response({"message": "x"}, status_code=status_code)++ valid, message = validate_credentials("key", BASE_URL)++ assert valid is expected_valid+ assert message == expected_message++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_uses_no_redirect_session(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=200)+ validate_credentials("key", BASE_URL)+ assert mock_session.call_args.kwargs["allow_redirects"] is False++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_swallows_request_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")+ valid, message = validate_credentials("key", BASE_URL)+ assert valid is False+ assert message == "boom"++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze._is_host_safe")+ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_blocks_internal_host_when_team_id_given(self, mock_session, mock_host_safe):+ mock_host_safe.return_value = (False, "host not allowed")++ valid, message = validate_credentials("key", "https://10.0.0.1", team_id=42)++ assert valid is False+ assert message == "host not allowed"+ # The host is rejected before any request is dispatched.+ mock_session.return_value.get.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze._is_host_safe")+ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_skips_host_check_when_team_id_omitted(self, mock_session, mock_host_safe):+ mock_session.return_value.get.return_value = _response({}, status_code=200)++ validate_credentials("key", BASE_URL)++ mock_host_safe.assert_not_called()+++class TestGetRows:+ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_page_pagination_walks_until_empty(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"campaigns": [{"id": "1"}, {"id": "2"}]}),+ _response({"campaigns": [{"id": "3"}]}),+ _response({"campaigns": []}),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", BASE_URL, "campaigns", mock.MagicMock(), manager, team_id=1))++ assert [item["id"] for batch in batches for item in batch] == ["1", "2", "3"]+ # page param walked 0, 1, 2+ pages = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert "page=0" in pages[0]+ assert "page=1" in pages[1]+ assert "page=2" in pages[2]++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_offset_pagination_advances_by_page_size(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"templates": [{"email_template_id": "a"}]}),+ _response({"templates": []}),+ ]++ manager = _make_manager()+ list(get_rows("key", BASE_URL, "email_templates", mock.MagicMock(), manager, team_id=1))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert "offset=0" in urls[0]+ assert "limit=100" in urls[0]+ assert "offset=100" in urls[1]++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_saves_current_cursor_after_each_yield(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"campaigns": [{"id": "1"}]}),+ _response({"campaigns": [{"id": "2"}]}),+ _response({"campaigns": []}),+ ]++ manager = _make_manager()+ list(get_rows("key", BASE_URL, "campaigns", mock.MagicMock(), manager, team_id=1))++ saved = [call.args[0].cursor for call in manager.save_state.call_args_list]+ # Saves the cursor of the page just yielded (0, then 1), not the next page.+ assert saved == [0, 1]++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"campaigns": [{"id": "9"}]}),+ _response({"campaigns": []}),+ ]++ manager = _make_manager(BrazeResumeConfig(cursor=5))+ list(get_rows("key", BASE_URL, "campaigns", mock.MagicMock(), manager, team_id=1))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "page=5" in first_url++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_empty_first_page_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _response({"campaigns": []})++ manager = _make_manager()+ batches = list(get_rows("key", BASE_URL, "campaigns", mock.MagicMock(), manager, team_id=1))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_incremental_applies_modified_after_filter(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"templates": [{"email_template_id": "a", "updated_at": "2026-02-01T00:00:00Z"}]}),+ _response({"templates": []}),+ ]++ manager = _make_manager()+ list(+ get_rows(+ "key",+ BASE_URL,+ "email_templates",+ mock.MagicMock(),+ manager,+ team_id=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="updated_at",+ )+ )++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "modified_after=2026-01-01" in first_url++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_full_refresh_endpoint_never_sends_modified_after(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"campaigns": [{"id": "1"}]}),+ _response({"campaigns": []}),+ ]++ manager = _make_manager()+ list(+ get_rows(+ "key",+ BASE_URL,+ "campaigns",+ mock.MagicMock(),+ manager,+ team_id=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="created_at",+ )+ )++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "modified_after" not in first_url++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_events_endpoint_wraps_scalar_rows(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"events": ["purchase", "login"]}),+ _response({"events": []}),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", BASE_URL, "events", mock.MagicMock(), manager, team_id=1))++ assert [item for batch in batches for item in batch] == [{"event_name": "purchase"}, {"event_name": "login"}]++ @mock.patch("posthog.temporal.data_imports.sources.braze.braze._is_host_safe")+ @mock.patch("posthog.temporal.data_imports.sources.braze.braze.make_tracked_session")+ def test_raises_when_host_not_allowed(self, mock_session, mock_host_safe):+ mock_host_safe.return_value = (False, "host not allowed")++ manager = _make_manager()+ with pytest.raises(BrazeHostNotAllowedError):+ list(get_rows("key", "https://10.0.0.1", "campaigns", mock.MagicMock(), manager, team_id=42))++ # No request is made once the host is rejected.+ mock_session.return_value.get.assert_not_called()+++class TestBrazeSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = BRAZE_ENDPOINTS[endpoint]+ response = braze_source("key", BASE_URL, endpoint, mock.MagicMock(), _make_manager(), team_id=1)++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(BRAZE_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ # Partition keys must be immutable creation timestamps, never updated/last-edit fields.+ if config.partition_key:+ assert config.partition_key == "created_at"diff --git a/posthog/temporal/data_imports/sources/braze/tests/test_braze_source.py b/posthog/temporal/data_imports/sources/braze/tests/test_braze_source.pynew file mode 100644index 000000000000..abdfc4f286d3--- /dev/null+++ b/posthog/temporal/data_imports/sources/braze/tests/test_braze_source.py@@ -0,0 +1,201 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.braze.braze import BrazeResumeConfig+from posthog.temporal.data_imports.sources.braze.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.braze.source import BrazeSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import BrazeSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++BASE_URL = "https://rest.iad-01.braze.com"+++class TestBrazeSource:+ def setup_method(self):+ self.source = BrazeSource()+ self.team_id = 123+ self.config = BrazeSourceConfig(api_key="key", url=BASE_URL)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.BRAZE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Braze"+ assert config.label == "Braze"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/braze.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "url"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_url_field_is_required_text(self):+ config = self.source.get_source_config+ url_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "url")+ assert url_field.type == SourceFieldInputConfigType.TEXT+ assert url_field.required is True+ assert url_field.secret is False++ def test_url_is_a_connection_host_field(self):+ # The API key is sent to the host in `url`, so retargeting it must re-require the secret.+ assert self.source.connection_host_fields == ["url"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://rest.iad-01.braze.com/campaigns/list?page=0",+ "403 Client Error: Forbidden for url: https://rest.iad-01.braze.com/events/list?page=0",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "500 Server Error for url: https://rest.iad-01.braze.com/campaigns/list",+ "429 Client Error: Too Many Requests",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ # Only templates/content blocks expose Braze's server-side `modified_after` filter.+ assert incremental == {"email_templates", "content_blocks"}++ def test_incremental_schemas_advertise_their_fields(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["email_templates"].incremental_fields == INCREMENTAL_FIELDS["email_templates"]+ assert schemas["content_blocks"].incremental_fields == INCREMENTAL_FIELDS["content_blocks"]+ assert schemas["campaigns"].incremental_fields == []+ assert schemas["campaigns"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["campaigns"])+ assert len(schemas) == 1+ assert schemas[0].name == "campaigns"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ ((False, "Invalid Braze API key"), False, "Invalid Braze API key"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.braze.source.validate_braze_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key, self.config.url, "/campaigns/list", self.team_id)++ @mock.patch("posthog.temporal.data_imports.sources.braze.source.validate_braze_credentials")+ def test_validate_credentials_probes_schema_specific_path(self, mock_validate):+ mock_validate.return_value = (True, None)++ self.source.validate_credentials(self.config, self.team_id, schema_name="email_templates")++ mock_validate.assert_called_once_with(+ self.config.api_key, self.config.url, "/templates/email/list", self.team_id+ )++ @mock.patch("posthog.temporal.data_imports.sources.braze.source.validate_braze_credentials")+ def test_validate_credentials_rejects_unknown_schema(self, mock_validate):+ is_valid, error_message = self.source.validate_credentials(+ self.config, self.team_id, schema_name="does_not_exist"+ )++ assert is_valid is False+ assert "does_not_exist" in (error_message or "")+ # Never probes the API for an unknown schema.+ mock_validate.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.braze.source.validate_braze_credentials")+ def test_validate_credentials_accepts_missing_scope_at_source_create(self, mock_validate):+ # A scoped key may lack the probe endpoint's permission at create time — accepted.+ mock_validate.return_value = (False, "Your Braze API key does not have permission for this endpoint")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None++ @mock.patch("posthog.temporal.data_imports.sources.braze.source.validate_braze_credentials")+ def test_validate_credentials_enforces_scope_for_specific_schema(self, mock_validate):+ mock_validate.return_value = (False, "Your Braze API key does not have permission for this endpoint")++ is_valid, error_message = self.source.validate_credentials(+ self.config, self.team_id, schema_name="email_templates"+ )++ assert is_valid is False+ assert error_message == "Your Braze API key does not have permission for this endpoint"++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BrazeResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.braze.source.braze_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_braze_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "email_templates"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "updated_at"+ inputs.team_id = 777+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_braze_source.assert_called_once()+ kwargs = mock_braze_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["base_url"] == BASE_URL+ assert kwargs["endpoint"] == "email_templates"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 777+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "updated_at"++ @mock.patch("posthog.temporal.data_imports.sources.braze.source.braze_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_braze_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "campaigns"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_braze_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex da8dd90fa7c7..2f7371eacbac 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -198,7 +198,8 @@ class BraintreeSourceConfig(config.Config):@config.configclass BrazeSourceConfig(config.Config):- pass+ api_key: str+ url: str@config.config