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 formbricks import source (#69337)

Tom Owers89388329f8f1
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 04c7c176069c..b2e89b45c33d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -182,6 +182,7 @@ the row lists both.
| flexmail | HTTP | requests | ✅ |
| float_app | HTTP | requests | ✅ |
| fly_io | HTTP | requests | ✅ |
+| formbricks | HTTP | requests | ✅ |
| front | HTTP | requests | ✅ |
| fulcrum | HTTP | requests | ✅ |
| fullstory | HTTP | requests | ✅ |
@@ -572,6 +573,7 @@ doesn't conflict with concurrent PRs.
- flexmail
- flexport
- flowlu
+- fly_io
- formbricks
- freeagent
- freightview
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py
index 4c014a381ce6..a86f223da27d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py
@@ -93,6 +93,7 @@ def record_request(
exception: BaseException | None = None,
redact_values: tuple[str, ...] = (),
capture: bool = True,
+ streamed: bool = False,
) -> None:
"""Log + meter a single outbound request. Never raises.
@@ -100,7 +101,9 @@ def record_request(
captured sample, on top of the name-based scrubbers. `capture=False` keeps the
request metered and logged but excludes it from HTTP sample capture — for auth
exchanges whose request/response bodies inherently carry secrets the name-based
- scrubbers can't recognise (e.g. a freshly minted session token).
+ scrubbers can't recognise (e.g. a freshly minted session token). `streamed=True`
+ means the caller requested `stream=True`, so the body hasn't been read yet and the
+ sampler must not force-buffer it (the caller size-caps and reads its own body).
"""
elapsed_ms = max(0, int((time.monotonic() - started_at_monotonic) * 1000))
method = (request.method or "GET").upper()
@@ -130,7 +133,13 @@ def record_request(
_emit_metrics(record, host=host, ctx=ctx)
if capture:
_maybe_capture_sample(
- request, response, record=record, ctx=ctx, exception=exception, redact_values=redact_values
+ request,
+ response,
+ record=record,
+ ctx=ctx,
+ exception=exception,
+ redact_values=redact_values,
+ streamed=streamed,
)
@@ -188,10 +197,18 @@ def _maybe_capture_sample(
ctx: JobContext | None,
exception: BaseException | None,
redact_values: tuple[str, ...] = (),
+ streamed: bool = False,
) -> None:
if ctx is None or exception is not None:
return
try:
- maybe_capture(request=request, response=response, record=record, ctx=ctx, redact_values=redact_values)
+ maybe_capture(
+ request=request,
+ response=response,
+ record=record,
+ ctx=ctx,
+ redact_values=redact_values,
+ streamed=streamed,
+ )
except Exception:
_fallback_logger.debug("Failed to capture HTTP sample", exc_info=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py
index 1b013f3e9d21..7d955a01335e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py
@@ -71,6 +71,7 @@ MAX_CONFIG_TTL_SECONDS = 24 * 60 * 60
_REDACTED_HEADER = "REDACTED"
_REDACTED_FORM_VALUE = "REDACTED"
+_STREAMED_BODY_OMITTED = "<streamed response body omitted from sample>"
_AUTH_HEADER_NAMES: frozenset[str] = frozenset(
{
"authorization",
@@ -169,11 +170,14 @@ def maybe_capture(
record: RequestRecord,
ctx: JobContext,
redact_values: tuple[str, ...] = (),
+ streamed: bool = False,
) -> None:
"""Entry point used by the observer. No-op when no rule matches.
`redact_values` are credential strings masked from the captured sample on
- top of the name-based header/URL/body scrubbers.
+ top of the name-based header/URL/body scrubbers. `streamed=True` means the
+ caller requested `stream=True` and hasn't read the body yet, so the sample
+ omits it rather than force-buffering a potentially unbounded body.
"""
if response is None:
return
@@ -196,7 +200,7 @@ def maybe_capture(
if not _try_reserve_slot(config.capture_id, rule_index, rule.limit):
return
- payload = _build_sample_payload(request=request, response=response, record=record, ctx=ctx)
+ payload = _build_sample_payload(request=request, response=response, record=record, ctx=ctx, streamed=streamed)
if redact_values:
# Final value-based pass over the fully serialized sample: catches the
# credential wherever it landed (query param, custom header, cookie,
@@ -246,11 +250,16 @@ def _build_sample_payload(
response: Response,
record: RequestRecord,
ctx: JobContext,
+ streamed: bool = False,
) -> str:
request_headers = _scrub_headers(dict(request.headers or {}))
response_headers = _scrub_headers(dict(response.headers or {}))
request_body = _scrub_body(request.body)
- response_body = _scrub_body(_safe_response_text(response))
+ # A streamed response body hasn't been read yet; reading it here would force a potentially
+ # unbounded, source-controlled body into memory and consume the stream out from under the
+ # caller. The caller size-caps and reads its own body, so the sample records only that it was
+ # omitted (mirrors _response_size, which likewise refuses to touch a streamed .content).
+ response_body = _STREAMED_BODY_OMITTED if streamed else _scrub_body(_safe_response_text(response))
sample = {
"captured_at_unix_ms": int(time.time() * 1000),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py
index 505be9549433..dead09c152ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py
@@ -90,6 +90,7 @@ class TrackedHTTPAdapter(HTTPAdapter):
exception=exception,
redact_values=self._redact_values,
capture=self._capture,
+ streamed=stream,
)
except Exception:
# Belt-and-braces: record_request should never raise, but if
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py
index 47307ae3e0bb..5b8921260b81 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_sampling.py
@@ -1,7 +1,7 @@
import json
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, PropertyMock, patch
from requests import PreparedRequest, Response
@@ -411,6 +411,25 @@ def test_sample_payload_preserves_json_body_keys():
assert parsed["request"]["body"]["id"] == 42
+def test_sample_payload_omits_streamed_response_body():
+ # A streamed (stream=True) body hasn't been read yet; sampling it would force a potentially
+ # unbounded, source-controlled body into memory and consume the stream. The sample must record
+ # the omission without ever touching response.text.
+ request = _make_request(url="https://formbricks.example.com/api/v2/management/responses")
+ response = _make_response(status=200)
+ with patch.object(type(response), "text", new_callable=PropertyMock) as mock_text:
+ mock_text.side_effect = AssertionError("streamed response body must not be read for a sample")
+ payload = _build_sample_payload(
+ request=request,
+ response=response,
+ record=_make_record(),
+ ctx=_make_ctx(),
+ streamed=True,
+ )
+ parsed = json.loads(payload)
+ assert parsed["response"]["body"] == sampling._STREAMED_BODY_OMITTED
+
+
# ---------------------------------------------------------------------------
# Header scrubbing
# ---------------------------------------------------------------------------
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/canonical_descriptions.py
new file mode 100644
index 000000000000..11cd4cb54c60
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/canonical_descriptions.py
@@ -0,0 +1,104 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "surveys": {
+ "description": "A survey in the environment, including its questions, triggers, and display settings.",
+ "docs_url": "https://formbricks.com/docs/api-reference/management-api--survey/get-all-surveys",
+ "columns": {
+ "id": "Unique identifier of the survey.",
+ "name": "Display name of the survey.",
+ "type": "How the survey is delivered, e.g. link or app.",
+ "status": "Lifecycle status of the survey, e.g. draft, inProgress, paused, or completed.",
+ "questions": "Legacy question list, derived from blocks for backwards compatibility.",
+ "blocks": "The survey's elements in the newer block structure.",
+ "triggers": "Action classes that trigger the survey to be shown.",
+ "displayOption": "How often the survey is displayed to the same person.",
+ "recontactDays": "Number of days before the same person can be asked again.",
+ "createdAt": "Timestamp when the survey was created.",
+ "updatedAt": "Timestamp when the survey was last updated.",
+ },
+ },
+ "responses": {
+ "description": "A single response to a survey, including the submitted answers and respondent metadata.",
+ "docs_url": "https://formbricks.com/docs/api-v2-reference/management-api--responses/get-responses",
+ "columns": {
+ "id": "Unique identifier of the response.",
+ "surveyId": "Identifier of the survey the response belongs to.",
+ "contactId": "Identifier of the contact who responded, if identified.",
+ "finished": "Whether the respondent completed the survey.",
+ "data": "Map of question identifier to the submitted answer.",
+ "variables": "Survey variable values captured with the response.",
+ "ttc": "Time-to-completion per question, in milliseconds.",
+ "meta": "Respondent metadata such as browser, OS, and location.",
+ "contactAttributes": "Attributes of the contact at the time of the response.",
+ "language": "Language the survey was answered in.",
+ "createdAt": "Timestamp when the response was created.",
+ "updatedAt": "Timestamp when the response was last updated.",
+ },
+ },
+ "contacts": {
+ "description": "A contact (person) tracked in the environment, identified by an optional user id.",
+ "docs_url": "https://formbricks.com/docs/api-reference/management-api--contacts/get-all-contacts",
+ "columns": {
+ "id": "Unique identifier of the contact.",
+ "userId": "External user identifier assigned by your application, if any.",
+ "createdAt": "Timestamp when the contact was created.",
+ "updatedAt": "Timestamp when the contact was last updated.",
+ },
+ },
+ "contact_attributes": {
+ "description": "An attribute value set on a contact, linking a contact to an attribute key.",
+ "docs_url": "https://formbricks.com/docs/api-reference/management-api--contact-attributes/get-all-contact-attributes",
+ "columns": {
+ "id": "Unique identifier of the contact attribute record.",
+ "contactId": "Identifier of the contact the attribute belongs to.",
+ "attributeKeyId": "Identifier of the attribute key this value is for.",
+ "value": "The attribute value.",
+ "createdAt": "Timestamp when the attribute was created.",
+ "updatedAt": "Timestamp when the attribute was last updated.",
+ },
+ },
+ "contact_attribute_keys": {
+ "description": "An attribute key definition describing a piece of data that can be stored on contacts.",
+ "docs_url": "https://formbricks.com/docs/api-v2-reference/management-api--contact-attribute-keys/get-contact-attribute-keys",
+ "columns": {
+ "id": "Unique identifier of the attribute key.",
+ "key": "Machine name of the attribute, e.g. email.",
+ "name": "Human-readable name of the attribute.",
+ "description": "Description of what the attribute stores.",
+ "type": "Whether the attribute is a default or custom key.",
+ "isUnique": "Whether values for this key must be unique across contacts.",
+ "createdAt": "Timestamp when the attribute key was created.",
+ "updatedAt": "Timestamp when the attribute key was last updated.",
+ },
+ },
+ "action_classes": {
+ "description": "An action class (user action) that can trigger surveys, defined by code or no-code config.",
+ "docs_url": "https://formbricks.com/docs/api-reference/management-api--action-class/get-all-action-classes",
+ "columns": {
+ "id": "Unique identifier of the action class.",
+ "name": "Display name of the action, e.g. New Session.",
+ "description": "Description of when the action fires.",
+ "type": "How the action is tracked: automatic, code, or noCode.",
+ "noCodeConfig": "Configuration for no-code actions, if any.",
+ "createdAt": "Timestamp when the action class was created.",
+ "updatedAt": "Timestamp when the action class was last updated.",
+ },
+ },
+ "webhooks": {
+ "description": "A webhook registered in the environment, fired when responses are created, updated, or finished.",
+ "docs_url": "https://formbricks.com/docs/api-v2-reference/management-api--webhooks/get-webhooks",
+ "columns": {
+ "id": "Unique identifier of the webhook.",
+ "name": "Display name of the webhook.",
+ "url": "URL the webhook payload is delivered to.",
+ "source": "What created the webhook: user, zapier, make, or n8n.",
+ "triggers": "Response events that fire the webhook.",
+ "surveyIds": "Surveys the webhook is limited to; empty means all surveys.",
+ "createdAt": "Timestamp when the webhook was created.",
+ "updatedAt": "Timestamp when the webhook was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/formbricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/formbricks.py
new file mode 100644
index 000000000000..cdf61fb6f896
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/formbricks.py
@@ -0,0 +1,408 @@
+import re
+import json
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qsl, urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.settings import (
+ FORMBRICKS_ENDPOINTS,
+ FormbricksEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# v2 list endpoints accept a limit of 1-250; the largest page minimises round trips.
+PAGE_SIZE = 250
+# The host is customer-controlled, so a malicious or misconfigured server could stream an
+# unbounded body and exhaust a shared worker (requests buffers the whole body into memory by
+# default, and the read timeout only guards idle gaps, not a steady large transfer). Cap what we
+# read into memory. Generous enough for a full v1 collection page; anything past it is refused.
+MAX_RESPONSE_BYTES = 256 * 1024 * 1024
+RESPONSE_CHUNK_BYTES = 256 * 1024
+# Wall-clock budget for downloading one page's body. requests' timeout only bounds each individual
+# socket read, so a host that dribbles the body slowly could hold the connection (and a shared
+# worker) open far longer than any read timeout while staying under MAX_RESPONSE_BYTES. This caps
+# total transfer time — 256 MiB in 300s is a ~0.85 MiB/s floor, far below any real API response and
+# far above a slow-drip stall.
+MAX_DOWNLOAD_SECONDS = 300
+
+DEFAULT_HOST = "https://app.formbricks.com"
+HOST_NOT_ALLOWED_ERROR = "Formbricks host is not allowed"
+HTTP_NOT_ALLOWED_ERROR = "Formbricks host must use HTTPS"
+RESPONSE_TOO_LARGE_ERROR = "Formbricks response body was too large"
+RESPONSE_TOO_SLOW_ERROR = "Formbricks response download was too slow"
+# Cheap probe returning the environment/project the API key is scoped to.
+DEFAULT_PROBE_PATH = "/api/v1/management/me"
+
+
+class FormbricksRetryableError(Exception):
+ pass
+
+
+class FormbricksHostNotAllowedError(Exception):
+ pass
+
+
+class FormbricksResponseTooLargeError(Exception):
+ pass
+
+
+class FormbricksResponseTooSlowError(Exception):
+ pass
+
+
+def _read_capped_body(response: requests.Response) -> bytes:
+ """Stream the body into memory, aborting past MAX_RESPONSE_BYTES or MAX_DOWNLOAD_SECONDS.
+
+ The host is customer-controlled, so a body must never be buffered unbounded (size cap) nor be
+ allowed to hold the connection open indefinitely by dribbling under the per-read timeout (time
+ cap). Both are non-retryable: re-fetching the same page yields the same oversized/slow body.
+ """
+ chunks: list[bytes] = []
+ total = 0
+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS
+ try:
+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):
+ if time.monotonic() > deadline:
+ raise FormbricksResponseTooSlowError(
+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {MAX_DOWNLOAD_SECONDS}s download budget"
+ )
+ if not chunk:
+ continue
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise FormbricksResponseTooLargeError(
+ f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes"
+ )
+ chunks.append(chunk)
+ finally:
+ response.close()
+ return b"".join(chunks)
+
+
+class FormbricksResumeConfig:
+ # Full URL of the next page to fetch. limit/skip and any incremental window params are baked
+ # into the URL, so a crashed sync resumes the exact request sequence it was running; merge
+ # dedupes the re-pulled page on the primary key.
+ next_url: str
+
+
+def normalize_host(host: str | None) -> str:
+ """Turn whatever the user typed into a bare Formbricks base URL.
+
+ Accepts ``app.formbricks.com``, ``https://formbricks.example.com/``, or
+ ``https://formbricks.example.com/api`` and returns ``https://formbricks.example.com``.
+ Defaults to https when no scheme is given, and to Formbricks Cloud when empty.
+ """
+ host = (host or "").strip()
+ if not host:
+ return DEFAULT_HOST
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ host = host.rstrip("/")
+ host = re.sub(r"/api(/v[12])?$", "", host, flags=re.IGNORECASE)
+ return host.rstrip("/")
+
+
+def _host_only(host: str | None) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def _is_https(host: str | None) -> bool:
+ # The API key rides in the x-api-key header, so refuse plaintext HTTP to keep an on-path
+ # attacker from capturing it.
+ return urlparse(normalize_host(host)).scheme == "https"
+
+
+def _is_same_host(url: str, host: str | None) -> bool:
+ """Whether ``url`` points at the configured Formbricks host over HTTPS.
+
+ Resume URLs come from Redis and could otherwise be replayed against a different host after the
+ source's host field is edited, so we pin them to the validated host before sending the API key.
+ """
+ try:
+ parsed = urlparse(url)
+ configured = urlparse(normalize_host(host))
+ return (
+ parsed.scheme == "https"
+ and (parsed.hostname or "").lower() == (configured.hostname or "").lower()
+ and (parsed.port or 443) == (configured.port or 443)
+ )
+ except Exception:
+ return False
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"x-api-key": api_key, "Accept": "application/json"}
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Formbricks date filters want ISO 8601; we normalize to UTC with a literal Z."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _build_initial_params(
+ config: FormbricksEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ if not config.paginated:
+ # v1 list endpoints return the whole collection and document no query params.
+ return {}
+
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "skip": 0}
+ sort_field = "createdAt"
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None and config.incremental_fields:
+ field_name = incremental_field or config.default_incremental_field or "createdAt"
+ allowed = {f["field"] for f in config.incremental_fields}
+ if field_name not in allowed:
+ raise ValueError(
+ f"Unsupported Formbricks incremental field '{field_name}' for endpoint '{config.name}'. "
+ f"Expected one of: {sorted(allowed)}."
+ )
+ params["startDate"] = _format_incremental_value(db_incremental_field_last_value)
+ params["filterDateField"] = field_name
+ sort_field = field_name
+
+ # Ascending sort on the filter field keeps skip-based pages stable while rows are inserted
+ # mid-sync and lets the pipeline checkpoint the incremental watermark after every batch. Only
+ # sent to endpoints that document sortBy/order, so a strict validator can't 400 on the others.
+ if config.supports_sort:
+ params["sortBy"] = sort_field
+ params["order"] = "asc"
+ return params
+
+
+def _build_url(host: str | None, path: str, params: dict[str, Any]) -> str:
+ url = f"{normalize_host(host)}{path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+def _advance_skip(url: str) -> str:
+ """Return ``url`` with its ``skip`` offset advanced by one page."""
+ parsed = urlparse(url)
+ params = dict(parse_qsl(parsed.query))
+ limit = int(params.get("limit", PAGE_SIZE))
+ params["skip"] = str(int(params.get("skip", 0)) + limit)
+ return parsed._replace(query=urlencode(params)).geturl()
+
+
+@retry(
+ retry=retry_if_exception_type((FormbricksRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ # Don't follow redirects: a customer-controlled host could 3xx at an internal address (SSRF).
+ # stream=True so the body isn't buffered until we cap it — see _read_capped_body.
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ response.close()
+ raise FormbricksRetryableError(f"Formbricks API error (retryable): status={response.status_code}, url={url}")
+
+ if response.is_redirect or response.is_permanent_redirect:
+ response.close()
+ raise FormbricksHostNotAllowedError(
+ f"{HOST_NOT_ALLOWED_ERROR}: Formbricks API returned an unexpected redirect "
+ f"(status={response.status_code}); refusing to follow it"
+ )
+
+ body = _read_capped_body(response)
+
+ if not response.ok:
+ logger.error(
+ f"Formbricks API error: status={response.status_code}, body={body.decode(errors='replace')}, url={url}"
+ )
+ response.raise_for_status()
+
+ try:
+ data = json.loads(body or b"null")
+ except ValueError:
+ raise FormbricksRetryableError(f"Formbricks returned a non-JSON payload for {url}")
+ # Both v1 and v2 management endpoints wrap rows in {"data": [...]}.
+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):
+ raise FormbricksRetryableError(f"Formbricks returned an unexpected payload for {url}: {type(data).__name__}")
+
+ return data["data"]
+
+
+def get_rows(
+ host: str | None,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FormbricksResumeConfig],
+ 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 = FORMBRICKS_ENDPOINTS[endpoint]
+
+ # The API key rides in a header, so refuse plaintext HTTP at run time too in case the host was
+ # edited after source creation. Non-retryable — see get_non_retryable_errors().
+ if not _is_https(host):
+ raise FormbricksHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)
+
+ # Re-check at run time (not just at source-create) in case the host was edited or now resolves
+ # to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_host_only(host), team_id)
+ if not host_ok:
+ raise FormbricksHostNotAllowedError(
+ f"{HOST_NOT_ALLOWED_ERROR}: {host_err}" if host_err else HOST_NOT_ALLOWED_ERROR
+ )
+
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ url = _build_url(host, config.path, params)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and _is_same_host(resume.next_url, host):
+ url = resume.next_url
+ logger.debug(f"Formbricks: resuming {endpoint} from URL {url}")
+ elif resume is not None:
+ logger.warning("Formbricks: ignoring resume URL whose host does not match the configured host")
+
+ if not config.paginated:
+ items = _fetch_page(session, url, logger)
+ if items:
+ yield items
+ return
+
+ while True:
+ items = _fetch_page(session, url, logger)
+ if items:
+ yield items
+
+ # A short (or empty) page means we've reached the end of the collection.
+ if len(items) < PAGE_SIZE:
+ break
+
+ next_url = _advance_skip(url)
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes any re-pulled rows on the primary key.
+ resumable_source_manager.save_state(FormbricksResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def formbricks_source(
+ host: str | None,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FormbricksResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = FORMBRICKS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ api_key=api_key,
+ 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_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def check_access(host: str | None, api_key: str, team_id: Optional[int] = None) -> tuple[int, Optional[str]]:
+ """Probe the `me` endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection or host problem, other HTTP status otherwise.
+ """
+ if not _is_https(host):
+ return 0, HTTP_NOT_ALLOWED_ERROR
+
+ # The host is customer-controlled (self-hosted Formbricks), 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_only(host), team_id)
+ if not host_ok:
+ return 0, host_err or HOST_NOT_ALLOWED_ERROR
+
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ # stream=True so a customer-controlled host can't force us to buffer an unbounded probe
+ # body: we only ever inspect the status line here, never the body.
+ response = session.get(
+ f"{normalize_host(host)}{DEFAULT_PROBE_PATH}", timeout=15, allow_redirects=False, stream=True
+ )
+ except Exception as e:
+ return 0, f"Could not connect to Formbricks: {e}"
+
+ try:
+ if response.is_redirect or response.is_permanent_redirect:
+ return 0, (
+ "The Formbricks instance URL returned an unexpected redirect. Enter just your instance URL "
+ "(for example https://app.formbricks.com or https://formbricks.example.com) and make sure it "
+ "points directly at Formbricks rather than a login or proxy page."
+ )
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Formbricks returned HTTP {response.status_code}"
+
+ return 200, None
+ finally:
+ response.close()
+
+
+def validate_credentials(host: str | None, api_key: str, team_id: Optional[int] = None) -> tuple[bool, str | None]:
+ if not api_key:
+ return False, "Missing Formbricks API key"
+
+ status, message = check_access(host, api_key, team_id)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Formbricks API key"
+ return False, message or "Could not validate Formbricks API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/settings.py
new file mode 100644
index 000000000000..823e26a4f301
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/settings.py
@@ -0,0 +1,89 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class FormbricksEndpointConfig:
+ name: str
+ # Full request path including the /api/v1 or /api/v2 prefix. v1 and v2 management APIs
+ # coexist; v2 is the paginated surface, but several resources are only listable on v1.
+ path: str
+ # v2 management list endpoints paginate with limit/skip and wrap rows in {"data": [...],
+ # "meta": {...}}; v1 list endpoints return the whole collection in one {"data": [...]}
+ # response and document no pagination params.
+ paginated: bool = False
+ # Only endpoints that document sortBy/order (responses) get them. Sending them to paginated
+ # endpoints whose docs are silent (contact_attribute_keys, webhooks) risks a non-retryable
+ # 400 from a strict validator; those small reference tables can rely on limit/skip alone.
+ supports_sort: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ partition_key: Optional[str] = None
+ # Formbricks ids are cuids, unique per resource collection.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Incremental sync is only declared on `responses`: the v2 endpoint documents a server-side
+# startDate/filterDateField window plus sortBy/order, so the filter and an ascending sort can be
+# applied on every page. The other resources are small reference tables where a full refresh is
+# cheaper than trusting an unverified filter. Verified against the public API docs; we have no
+# live credentials, so behavior that docs leave ambiguous is handled conservatively.
+FORMBRICKS_ENDPOINTS: dict[str, FormbricksEndpointConfig] = {
+ "surveys": FormbricksEndpointConfig(
+ name="surveys",
+ path="/api/v1/management/surveys",
+ ),
+ "responses": FormbricksEndpointConfig(
+ name="responses",
+ path="/api/v2/management/responses",
+ paginated=True,
+ supports_sort=True,
+ incremental_fields=[
+ _datetime_incremental_field("updatedAt"),
+ _datetime_incremental_field("createdAt"),
+ ],
+ # Responses mutate after creation (partial responses finish later), so updatedAt is the
+ # default cursor that catches edits as well as new rows.
+ default_incremental_field="updatedAt",
+ partition_key="createdAt",
+ ),
+ "contacts": FormbricksEndpointConfig(
+ name="contacts",
+ path="/api/v1/management/contacts",
+ ),
+ "contact_attributes": FormbricksEndpointConfig(
+ name="contact_attributes",
+ path="/api/v1/management/contact-attributes",
+ ),
+ "contact_attribute_keys": FormbricksEndpointConfig(
+ name="contact_attribute_keys",
+ path="/api/v2/management/contact-attribute-keys",
+ paginated=True,
+ ),
+ "action_classes": FormbricksEndpointConfig(
+ name="action_classes",
+ path="/api/v1/management/action-classes",
+ ),
+ "webhooks": FormbricksEndpointConfig(
+ name="webhooks",
+ path="/api/v2/management/webhooks",
+ paginated=True,
+ ),
+}
+
+ENDPOINTS = tuple(FORMBRICKS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FORMBRICKS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/source.py
index ec15b220dd1a..840713bf70db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/source.py
@@ -1,30 +1,161 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.formbricks import (
+ HOST_NOT_ALLOWED_ERROR,
+ HTTP_NOT_ALLOWED_ERROR,
+ RESPONSE_TOO_LARGE_ERROR,
+ RESPONSE_TOO_SLOW_ERROR,
+ FormbricksResumeConfig,
+ formbricks_source,
+ validate_credentials as validate_formbricks_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.settings import (
+ ENDPOINTS,
+ FORMBRICKS_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FormbricksSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FormbricksSource(SimpleSource[FormbricksSourceConfig]):
+class FormbricksSource(ResumableSource[FormbricksSourceConfig, FormbricksResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FORMBRICKS
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `host` determines where the stored API key is sent, so retargeting it
+ # must re-require the key.
+ return ["host"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FORMBRICKS,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Formbricks",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Sync surveys, responses, contacts, and more from Formbricks into the PostHog Data warehouse.
+
+Create an API key under **Organization settings → API keys** in Formbricks. API keys are scoped to a single environment, so the connector imports that environment's data.
+For self-hosted Formbricks, set your instance URL (for example `https://formbricks.example.com`); leave it empty for Formbricks Cloud.""",
iconPath="/static/services/formbricks.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/formbricks",
+ keywords=["surveys", "feedback", "forms"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Formbricks instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://app.formbricks.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Formbricks API key is invalid or has been revoked. Generate a new key under Organization settings → API keys, then reconnect.",
+ "403 Client Error": "Your Formbricks API key does not have access to this data. Check the key's environment permissions, then reconnect.",
+ HOST_NOT_ALLOWED_ERROR: "The Formbricks host is not allowed. Please use a publicly reachable instance URL.",
+ HTTP_NOT_ALLOWED_ERROR: "The Formbricks host must use HTTPS. Please update the instance URL to use https://.",
+ RESPONSE_TOO_LARGE_ERROR: "Formbricks returned a response that was too large to process. Please contact support if this persists.",
+ RESPONSE_TOO_SLOW_ERROR: "Formbricks took too long to send a response. Check that the instance URL points at a healthy Formbricks server, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: FormbricksSourceConfig,
+ 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 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: FormbricksSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key grants access to its whole environment, so one probe validates every schema.
+ return validate_formbricks_credentials(config.host, config.api_key, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FormbricksResumeConfig]:
+ return ResumableSourceManager[FormbricksResumeConfig](inputs, FormbricksResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FormbricksSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FormbricksResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in FORMBRICKS_ENDPOINTS:
+ raise ValueError(f"Unknown Formbricks schema '{inputs.schema_name}'")
+
+ return formbricks_source(
+ host=config.host,
+ api_key=config.api_key,
+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/tests/test_formbricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/tests/test_formbricks.py
new file mode 100644
index 000000000000..0073da37c119
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/tests/test_formbricks.py
@@ -0,0 +1,438 @@
+import json
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks import formbricks
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.formbricks import (
+ DEFAULT_HOST,
+ HTTP_NOT_ALLOWED_ERROR,
+ PAGE_SIZE,
+ FormbricksHostNotAllowedError,
+ FormbricksResumeConfig,
+ FormbricksRetryableError,
+ _advance_skip,
+ _build_initial_params,
+ _build_url,
+ check_access,
+ formbricks_source,
+ get_rows,
+ normalize_host,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.settings import (
+ ENDPOINTS,
+ FORMBRICKS_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = formbricks._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+RESPONSES_CONFIG = FORMBRICKS_ENDPOINTS["responses"]
+SURVEYS_CONFIG = FORMBRICKS_ENDPOINTS["surveys"]
+WEBHOOKS_CONFIG = FORMBRICKS_ENDPOINTS["webhooks"]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: FormbricksResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[FormbricksResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> FormbricksResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: FormbricksResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _full_page(start: int) -> list[dict]:
+ return [{"id": f"resp_{start + i}"} for i in range(PAGE_SIZE)]
+
+
+class TestNormalizeHost:
+ @parameterized.expand(
+ [
+ ("empty_defaults_to_cloud", "", DEFAULT_HOST),
+ ("none_defaults_to_cloud", None, DEFAULT_HOST),
+ ("bare_host_gets_https", "formbricks.example.com", "https://formbricks.example.com"),
+ ("trailing_slash_stripped", "https://formbricks.example.com/", "https://formbricks.example.com"),
+ ("api_suffix_stripped", "https://formbricks.example.com/api", "https://formbricks.example.com"),
+ ("api_v1_suffix_stripped", "https://formbricks.example.com/api/v1", "https://formbricks.example.com"),
+ ("http_scheme_preserved", "http://formbricks.internal", "http://formbricks.internal"),
+ ]
+ )
+ def test_normalize_host(self, _name: str, host: str | None, expected: str) -> None:
+ assert normalize_host(host) == expected
+
+
+class TestBuildInitialParams:
+ def test_unpaginated_endpoint_sends_no_params(self) -> None:
+ assert _build_initial_params(SURVEYS_CONFIG, False, None, None) == {}
+
+ def test_full_refresh_pins_stable_ascending_order(self) -> None:
+ params = _build_initial_params(RESPONSES_CONFIG, False, None, None)
+ assert params == {"limit": PAGE_SIZE, "skip": 0, "sortBy": "createdAt", "order": "asc"}
+
+ def test_paginated_without_sort_support_omits_sort_params(self) -> None:
+ # webhooks documents no sortBy/order, so sending them risks a non-retryable 400.
+ params = _build_initial_params(WEBHOOKS_CONFIG, False, None, None)
+ assert params == {"limit": PAGE_SIZE, "skip": 0}
+
+ @parameterized.expand([("updated_at", "updatedAt"), ("created_at", "createdAt")])
+ def test_incremental_filters_and_sorts_on_chosen_field(self, _name: str, field: str) -> None:
+ params = _build_initial_params(RESPONSES_CONFIG, True, datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), field)
+ assert params["startDate"] == "2026-01-02T03:04:05Z"
+ assert params["filterDateField"] == field
+ assert params["sortBy"] == field
+ assert params["order"] == "asc"
+
+ def test_incremental_defaults_to_updated_at(self) -> None:
+ params = _build_initial_params(RESPONSES_CONFIG, True, datetime(2026, 1, 1, tzinfo=UTC), None)
+ assert params["filterDateField"] == "updatedAt"
+
+ def test_incremental_without_last_value_falls_back_to_full_refresh(self) -> None:
+ params = _build_initial_params(RESPONSES_CONFIG, True, None, "updatedAt")
+ assert "startDate" not in params
+
+ def test_unknown_incremental_field_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unsupported Formbricks incremental field"):
+ _build_initial_params(RESPONSES_CONFIG, True, datetime(2026, 1, 1, tzinfo=UTC), "finished")
+
+
+class TestAdvanceSkip:
+ def test_advances_skip_by_limit_and_preserves_params(self) -> None:
+ url = _build_url(None, RESPONSES_CONFIG.path, _build_initial_params(RESPONSES_CONFIG, False, None, None))
+ advanced = _advance_skip(url)
+ assert f"skip={PAGE_SIZE}" in advanced
+ assert f"limit={PAGE_SIZE}" in advanced
+ assert "sortBy=createdAt" in advanced
+ assert advanced.startswith(f"{DEFAULT_HOST}{RESPONSES_CONFIG.path}")
+
+ def test_advances_from_nonzero_skip(self) -> None:
+ assert "skip=500" in _advance_skip(f"{DEFAULT_HOST}/api/v2/management/responses?limit=250&skip=250")
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str, list[dict]],
+ endpoint: str = "responses",
+ host: str | None = None,
+ **kwargs: Any,
+ ) -> tuple[list[dict], list[str]]:
+ fetched_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> list[dict]:
+ fetched_urls.append(url)
+ return pages[url]
+
+ monkeypatch.setattr(formbricks, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(formbricks, "make_tracked_session", lambda **_: MagicMock())
+ monkeypatch.setattr(formbricks, "_is_host_safe", lambda host, team_id: (True, None))
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ host=host,
+ api_key="fb-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ team_id=1,
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, fetched_urls
+
+ def _initial_url(self, endpoint: str = "responses", **kwargs: Any) -> str:
+ config = FORMBRICKS_ENDPOINTS[endpoint]
+ return _build_url(
+ None,
+ config.path,
+ _build_initial_params(
+ config,
+ kwargs.get("should_use_incremental_field", False),
+ kwargs.get("db_incremental_field_last_value"),
+ kwargs.get("incremental_field"),
+ ),
+ )
+
+ def test_short_first_page_yields_and_stops_without_saving(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ url = self._initial_url()
+ rows, fetched = self._collect(manager, monkeypatch, {url: [{"id": "a"}, {"id": "b"}]})
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ assert fetched == [url]
+ assert manager.saved == []
+
+ def test_full_page_advances_skip_until_short_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first = self._initial_url()
+ second = _advance_skip(first)
+ rows, fetched = self._collect(manager, monkeypatch, {first: _full_page(0), second: [{"id": "last"}]})
+ assert len(rows) == PAGE_SIZE + 1
+ assert fetched == [first, second]
+ # State is saved after yielding the full page, pointing at the next page.
+ assert [s.next_url for s in manager.saved] == [second]
+
+ def test_resumes_from_saved_url_on_same_host(self, monkeypatch: Any) -> None:
+ resume_url = f"{DEFAULT_HOST}/api/v2/management/responses?limit=250&skip=500&sortBy=createdAt&order=asc"
+ manager = _FakeResumableManager(FormbricksResumeConfig(next_url=resume_url))
+ rows, fetched = self._collect(manager, monkeypatch, {resume_url: [{"id": "resumed"}]})
+ assert rows == [{"id": "resumed"}]
+ assert fetched == [resume_url]
+
+ def test_ignores_resume_url_on_different_host(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(
+ FormbricksResumeConfig(next_url="https://attacker.example.com/api/v2/management/responses?skip=500")
+ )
+ url = self._initial_url()
+ _, fetched = self._collect(manager, monkeypatch, {url: []})
+ assert fetched == [url]
+
+ def test_unpaginated_endpoint_fetches_once_without_params(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ url = f"{DEFAULT_HOST}{SURVEYS_CONFIG.path}"
+ rows, fetched = self._collect(manager, monkeypatch, {url: [{"id": "s1"}]}, endpoint="surveys")
+ assert rows == [{"id": "s1"}]
+ assert fetched == [url]
+ assert manager.saved == []
+
+ def test_incremental_run_sends_window_on_first_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ kwargs: dict[str, Any] = {
+ "should_use_incremental_field": True,
+ "db_incremental_field_last_value": datetime(2026, 1, 1, tzinfo=UTC),
+ "incremental_field": "updatedAt",
+ }
+ url = self._initial_url(**kwargs)
+ _, fetched = self._collect(manager, monkeypatch, {url: []}, **kwargs)
+ assert "startDate=2026-01-01T00%3A00%3A00Z" in fetched[0]
+ assert "filterDateField=updatedAt" in fetched[0]
+ assert "sortBy=updatedAt" in fetched[0]
+
+ def test_plaintext_http_host_is_rejected(self, monkeypatch: Any) -> None:
+ with pytest.raises(FormbricksHostNotAllowedError, match=HTTP_NOT_ALLOWED_ERROR):
+ self._collect(_FakeResumableManager(), monkeypatch, {}, host="http://formbricks.internal")
+
+ def test_unsafe_host_is_rejected(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(formbricks, "make_tracked_session", lambda **_: MagicMock())
+ monkeypatch.setattr(formbricks, "_is_host_safe", lambda host, team_id: (False, "internal IP"))
+ with pytest.raises(FormbricksHostNotAllowedError, match="internal IP"):
+ next(
+ iter(
+ get_rows(
+ host="https://formbricks.internal",
+ api_key="fb-key",
+ endpoint="responses",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ team_id=1,
+ )
+ )
+ )
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None, redirect: bool = False) -> MagicMock:
+ payload = body if body is not None else {"data": []}
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.is_redirect = redirect
+ response.is_permanent_redirect = False
+ # The source streams the body and caps it, so feed bytes via iter_content rather than .json().
+ response.iter_content.return_value = [json.dumps(payload).encode()]
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ with pytest.raises(FormbricksRetryableError):
+ _fetch_page_unwrapped(self._session_returning(status), "https://x/api", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(self._session_returning(status), "https://x/api", MagicMock())
+
+ def test_redirect_is_refused(self) -> None:
+ with pytest.raises(FormbricksHostNotAllowedError):
+ _fetch_page_unwrapped(self._session_returning(302, redirect=True), "https://x/api", MagicMock())
+
+ @parameterized.expand(
+ [
+ ("bare_list", [{"id": "1"}]),
+ ("missing_data_key", {"meta": {"total": 0}}),
+ ]
+ )
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ with pytest.raises(FormbricksRetryableError):
+ _fetch_page_unwrapped(self._session_returning(200, body), "https://x/api", MagicMock())
+
+ def test_success_returns_data_rows(self) -> None:
+ body = {"data": [{"id": "1"}], "meta": {"total": 1, "limit": 50, "offset": 0}}
+ assert _fetch_page_unwrapped(self._session_returning(200, body), "https://x/api", MagicMock()) == [{"id": "1"}]
+
+ def test_does_not_follow_redirects(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "https://x/api", MagicMock())
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_oversized_body_is_refused_and_connection_closed(self, monkeypatch: Any) -> None:
+ # A customer-controlled host must not be able to stream an unbounded body into worker memory.
+ monkeypatch.setattr(formbricks, "MAX_RESPONSE_BYTES", 10)
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.is_redirect = False
+ response.is_permanent_redirect = False
+ response.iter_content.return_value = [b"x" * 6, b"x" * 6]
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(formbricks.FormbricksResponseTooLargeError):
+ _fetch_page_unwrapped(session, "https://x/api", MagicMock())
+ response.close.assert_called_once()
+
+ def test_slow_download_is_refused_and_connection_closed(self, monkeypatch: Any) -> None:
+ # A host that dribbles the body must not hold the connection past the wall-clock budget.
+ monkeypatch.setattr(formbricks, "MAX_DOWNLOAD_SECONDS", -1)
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.is_redirect = False
+ response.is_permanent_redirect = False
+ response.iter_content.return_value = [b"x" * 10]
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(formbricks.FormbricksResponseTooSlowError):
+ _fetch_page_unwrapped(session, "https://x/api", MagicMock())
+ response.close.assert_called_once()
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ def _response(self, status: int, redirect: bool = False) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ response.is_redirect = redirect
+ response.is_permanent_redirect = False
+ return response
+
+ @parameterized.expand(
+ [
+ ("ok", 200, 200, None),
+ ("unauthorized", 401, 401, None),
+ ("forbidden", 403, 403, None),
+ ("server_error", 500, 500, "Formbricks returned HTTP 500"),
+ ]
+ )
+ @patch(f"{formbricks.__name__}._is_host_safe", return_value=(True, None))
+ @patch(f"{formbricks.__name__}.make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ expected_status: int,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ _mock_host_safe: MagicMock,
+ ) -> None:
+ mock_session.return_value = self._session(self._response(status))
+ assert check_access(None, "fb-key", team_id=1) == (expected_status, expected_message)
+
+ @patch(f"{formbricks.__name__}._is_host_safe", return_value=(True, None))
+ @patch(f"{formbricks.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock, _mock_host_safe: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access(None, "fb-key", team_id=1)
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @patch(f"{formbricks.__name__}._is_host_safe", return_value=(True, None))
+ @patch(f"{formbricks.__name__}.make_tracked_session")
+ def test_redirect_maps_to_actionable_message(self, mock_session: MagicMock, _mock_host_safe: MagicMock) -> None:
+ mock_session.return_value = self._session(self._response(302, redirect=True))
+ status, message = check_access(None, "fb-key", team_id=1)
+ assert status == 0
+ assert message is not None and "unexpected redirect" in message
+
+ def test_plaintext_http_host_fails_before_any_request(self) -> None:
+ status, message = check_access("http://formbricks.internal", "fb-key", team_id=1)
+ assert status == 0
+ assert message == HTTP_NOT_ALLOWED_ERROR
+
+ @patch(f"{formbricks.__name__}._is_host_safe", return_value=(False, "internal IP"))
+ def test_unsafe_host_fails_before_any_request(self, _mock_host_safe: MagicMock) -> None:
+ status, message = check_access("https://formbricks.internal", "fb-key", team_id=1)
+ assert status == 0
+ assert message == "internal IP"
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Formbricks API key"),
+ ("forbidden", 403, False, "Invalid Formbricks API key"),
+ ("server_error", 500, False, "Formbricks returned HTTP 500"),
+ ]
+ )
+ @patch(f"{formbricks.__name__}._is_host_safe", return_value=(True, None))
+ @patch(f"{formbricks.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ _mock_host_safe: MagicMock,
+ ) -> None:
+ mock_session.return_value = self._session(self._response(status))
+ assert validate_credentials(None, "fb-key", team_id=1) == (expected_valid, expected_message)
+
+ def test_validate_credentials_requires_api_key(self) -> None:
+ assert validate_credentials(None, "", team_id=1) == (False, "Missing Formbricks API key")
+
+
+class TestFormbricksSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = formbricks_source(
+ host=None,
+ api_key="fb-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ if endpoint == "responses":
+ # Responses can grow large, so they partition on the stable creation timestamp.
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+ else:
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/tests/test_formbricks_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/tests/test_formbricks_source.py
new file mode 100644
index 000000000000..b10b6cb5a8e6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/formbricks/tests/test_formbricks_source.py
@@ -0,0 +1,167 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.formbricks import (
+ FormbricksResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.source import FormbricksSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FormbricksSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestFormbricksSource:
+ def setup_method(self) -> None:
+ self.source = FormbricksSource()
+ self.team_id = 123
+ self.config = FormbricksSourceConfig(api_key="fb-key", host="https://formbricks.example.com")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.FORMBRICKS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Formbricks"
+ assert config.label == "Formbricks"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/formbricks"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["host", "api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_host_field_is_optional_connection_target(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "host")
+ assert field.required is False
+ assert field.secret is False
+ # The base URL field must stay named `host`: the update serializer treats `host` as a
+ # connection target and forces secrets to be re-entered when it changes. Renaming it
+ # without adding it to connection_host_fields would let an editor retarget the stored
+ # API key at a server they control.
+ assert field.name == "host"
+
+ def test_connection_host_fields_cover_host(self) -> None:
+ # `host` decides where the stored API key gets sent, so changing it must force re-entry.
+ assert self.source.connection_host_fields == ["host"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_responses_supports_incremental(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ by_name = {s.name: s for s in schemas}
+ assert by_name["responses"].supports_incremental is True
+ assert {f["field"] for f in by_name["responses"].incremental_fields} == {"createdAt", "updatedAt"}
+ for name, schema in by_name.items():
+ if name == "responses":
+ continue
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["surveys", "nope"])
+ assert [s.name for s in schemas] == ["surveys"]
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://app.formbricks.com/api/v2/management/responses",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://formbricks.example.com/api/v1/management/surveys",
+ ),
+ ("host_not_allowed", "Formbricks host is not allowed: internal IP"),
+ ("plaintext_http", "Formbricks host must use HTTPS"),
+ ]
+ )
+ def test_non_retryable_errors_match_permanent_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://app.formbricks.com"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://app.formbricks.com"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.source.validate_formbricks_credentials"
+ )
+ def test_validate_credentials_delegates_with_host_and_key(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid Formbricks API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("https://formbricks.example.com", "fb-key", self.team_id)
+ assert result == (False, "Invalid Formbricks API key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FormbricksResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.source.formbricks_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "responses"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "updatedAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["host"] == "https://formbricks.example.com"
+ assert kwargs["api_key"] == "fb-key"
+ assert kwargs["endpoint"] == "responses"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == self.team_id
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "updatedAt"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.formbricks.source.formbricks_source")
+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "responses"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Formbricks schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 49711dd54d47..c411aa8b0373 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1372,7 +1372,8 @@ class FlyIoSourceConfig(config.Config):
@config.config
class FormbricksSourceConfig(config.Config):
- pass
+ api_key: str
+ host: str | None = None
@config.config