: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 jotform import source (#65651)
Tom Owersbf1b2bd20801
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex c85a3266e7ef..43295df1fb6c 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -116,6 +116,7 @@ the row lists both.| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ || iterable | HTTP | requests | ✅ || jira | HTTP | requests | ✅ |+| jotform | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || launchdarkly | HTTP | requests | ✅ || kustomer | HTTP | requests | ✅ |@@ -443,7 +444,6 @@ doesn't conflict with concurrent PRs.- jamf_pro- jobber- jobnimbus-- jotform- judgeme_reviews- justcall- justsiftdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 40c305586889..63e31c053e1a 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1589,7 +1589,9 @@ class JobberSourceConfig(config.Config):@config.configclass JotformSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu", "hipaa"] = config.value(default="us")+ enterprise_domain: str | None = None@config.configdiff --git a/posthog/temporal/data_imports/sources/jotform/canonical_descriptions.py b/posthog/temporal/data_imports/sources/jotform/canonical_descriptions.pynew file mode 100644index 000000000000..0ff05fe247e5--- /dev/null+++ b/posthog/temporal/data_imports/sources/jotform/canonical_descriptions.py@@ -0,0 +1,68 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Doc-sourced descriptions for Jotform's well-known tables. See https://api.jotform.com/docs/.+# Partial coverage is fine — any missing endpoint/column falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "forms": {+ "description": "One row per form on the account, with its title, status, and submission counts.",+ "docs_url": "https://api.jotform.com/docs/#user-forms",+ "columns": {+ "id": "Unique identifier of the form.",+ "username": "Username of the account that owns the form.",+ "title": "Display title of the form.",+ "height": "Configured form height in pixels.",+ "url": "Public URL of the form.",+ "status": "Form status (e.g. ENABLED, DISABLED, DELETED).",+ "created_at": "Timestamp the form was created.",+ "updated_at": "Timestamp the form was last updated.",+ "last_submission": "Timestamp of the most recent submission to the form.",+ "new": "Number of unread submissions.",+ "count": "Total number of submissions to the form.",+ "type": "Form type (e.g. LEGACY, CARD).",+ "favorite": "Whether the form is marked as a favorite.",+ "archived": "Whether the form is archived.",+ },+ },+ "submissions": {+ "description": "One row per submission across all of the account's forms, including answers.",+ "docs_url": "https://api.jotform.com/docs/#user-submissions",+ "columns": {+ "id": "Unique identifier of the submission.",+ "form_id": "Identifier of the form the submission belongs to.",+ "ip": "IP address the submission was made from.",+ "created_at": "Timestamp the submission was created.",+ "updated_at": "Timestamp the submission was last updated.",+ "status": "Submission status (e.g. ACTIVE, OVERQUOTA).",+ "new": "Whether the submission is unread.",+ "flag": "Whether the submission is flagged.",+ "notes": "Free-text notes attached to the submission.",+ "answers": "Object of the submitted answers keyed by question id.",+ },+ },+ "reports": {+ "description": "One row per report (e.g. grid, table, or visual report) created on the account.",+ "docs_url": "https://api.jotform.com/docs/#user-reports",+ "columns": {+ "id": "Unique identifier of the report.",+ "form_id": "Identifier of the form the report is built from.",+ "title": "Display title of the report.",+ "type": "Report type (e.g. excel, csv, grid, table).",+ "status": "Report status.",+ "url": "Public URL of the report.",+ "created_at": "Timestamp the report was created.",+ "updated_at": "Timestamp the report was last updated.",+ },+ },+ "questions": {+ "description": "One row per question (field) of a form. `qid` is unique only within a form, so each row also carries `form_id`.",+ "docs_url": "https://api.jotform.com/docs/#form-id-questions",+ "columns": {+ "form_id": "Identifier of the form the question belongs to.",+ "qid": "Question identifier, unique within its form.",+ "type": "Question/control type (e.g. control_textbox, control_email).",+ "text": "Label shown to respondents for the question.",+ "name": "Internal field name of the question.",+ "order": "Display order of the question within the form.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/jotform/jotform.py b/posthog/temporal/data_imports/sources/jotform/jotform.pynew file mode 100644index 000000000000..e23e82c9fb39--- /dev/null+++ b/posthog/temporal/data_imports/sources/jotform/jotform.py@@ -0,0 +1,315 @@+import json+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote++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.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.jotform.settings import JOTFORM_ENDPOINTS, JotformEndpointConfig++# Regional API hosts. Enterprise installations live on the org's own domain (see resolve_base_url).+JOTFORM_REGION_BASE_URLS = {+ "us": "https://api.jotform.com",+ "eu": "https://eu-api.jotform.com",+ "hipaa": "https://hipaa-api.jotform.com",+}++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# Jotform's `filter` operator for "created/updated after" is `:gt` (strictly greater than).+FILTER_GT_SUFFIX = ":gt"+++class JotformRetryableError(Exception):+ pass+++class JotformResumeConfig:+ # Offset of the page to (re)fetch when resuming a list endpoint. Saved as the offset of the page+ # just yielded so a crash re-yields that page (merge dedupes on the primary key) instead of+ # skipping it.+ offset: int = 0+ # Form currently being processed by the questions fan-out. A stable form-id bookmark so a crash+ # resumes that form rather than a positional index that shifts as forms are added/removed.+ form_id: Optional[str] = None+++def normalize_enterprise_host(enterprise_domain: Optional[str]) -> Optional[str]:+ host = (enterprise_domain or "").strip()+ if not host:+ return None+ host = host.removeprefix("https://").removeprefix("http://").strip("/")+ return host or None+++def resolve_base_url(region: Optional[str], enterprise_domain: Optional[str] = None) -> str:+ host = normalize_enterprise_host(enterprise_domain)+ if host is not None:+ # Jotform Enterprise serves its API under `/API` on the organisation's own domain. Couldn't+ # be curl-verified without an Enterprise account, so this path is best-effort.+ return f"https://{host}/API"+ return JOTFORM_REGION_BASE_URLS.get((region or "us").lower(), JOTFORM_REGION_BASE_URLS["us"])+++def _headers(api_key: str) -> dict[str, str]:+ # Jotform accepts the API key either as the `APIKEY` header or an `apiKey` query param. The+ # header keeps the secret out of request URLs (and out of logs).+ return {"APIKEY": api_key, "Accept": "application/json"}+++def _coerce_datetime(value: Any) -> Optional[datetime]:+ if isinstance(value, bool):+ return None+ if isinstance(value, datetime):+ return value+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time())+ if isinstance(value, str):+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"):+ try:+ return datetime.strptime(value, fmt)+ except ValueError:+ continue+ return None+++def _format_filter_value(value: Any) -> Optional[str]:+ """Format an incremental cursor as Jotform's ``YYYY-MM-DD HH:MM:SS`` filter literal.++ Future-dated cursors are capped at now: a ``<field>:gt <future>`` filter returns nothing and+ would wedge the sync until wall-clock catches up. The watermark and the API's ``created_at`` /+ ``updated_at`` come from the same field round-tripped, so the wall-clock components line up.+ """+ parsed = _coerce_datetime(value)+ if parsed is None:+ return None+ aware = parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+ capped = min(aware, datetime.now(UTC))+ return capped.strftime("%Y-%m-%d %H:%M:%S")+++def _build_list_params(+ config: JotformEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: Optional[str],+) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if not config.incremental_fields:+ # Full-refresh endpoints (reports): no orderby/filter. Jotform doesn't document an orderby+ # enum for these, and they're small enough that offset stability isn't a concern.+ return params++ field_name = incremental_field or config.default_incremental_field+ # Order by the cursor field so pages arrive oldest-first and the asc watermark advances+ # correctly. Jotform's `orderby` sorts ascending by the given field (per the API docs; couldn't+ # be curl-verified without an API key).+ if field_name:+ params["orderby"] = field_name+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ formatted = _format_filter_value(db_incremental_field_last_value)+ if formatted is not None:+ params["filter"] = json.dumps({f"{field_name}{FILTER_GT_SUFFIX}": formatted}, separators=(",", ":"))+ return params+++@retry(+ retry=retry_if_exception_type((JotformRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_page(url: str, params: dict[str, Any], headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ # `enterprise_domain` is user-supplied, so pin redirects off (defense-in-depth on top of the+ # Smokescreen egress proxy, which is the load-bearing SSRF control) to keep the API-key-bearing+ # request on the validated host, and value-redact the key carried in the `APIKEY` header.+ api_key = headers.get("APIKEY")+ session = make_tracked_session(redact_values=(api_key,) if api_key else (), allow_redirects=False)+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Jotform enforces daily call quotas rather than per-second rate limits; an exhausted quota or a+ # transient server error is worth retrying. Auth failures (401/403) are not — they surface to+ # `get_non_retryable_errors` and stop the sync.+ if response.status_code == 429 or response.status_code >= 500:+ raise JotformRetryableError(f"Jotform API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Jotform API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str, region: Optional[str], enterprise_domain: Optional[str] = None) -> bool:+ """Confirm the API key is valid for the target host. ``/user`` is the cheapest authenticated probe."""+ try:+ # Same SSRF posture as `_fetch_page`: no redirects off the validated host, redact the key.+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(+ f"{resolve_base_url(region, enterprise_domain)}/user",+ headers=_headers(api_key),+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_form_ids(base_url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:+ config = JOTFORM_ENDPOINTS["forms"]+ ids: list[str] = []+ offset = 0++ while True:+ params = {"limit": config.page_size, "offset": offset, "orderby": "created_at"}+ data = _fetch_page(f"{base_url}{config.path}", params, headers, logger)+ content = data.get("content")+ if not isinstance(content, list) or not content:+ break++ ids.extend(str(item["id"]) for item in content if isinstance(item, dict) and item.get("id") is not None)++ if len(content) < config.page_size:+ break+ offset += config.page_size++ return ids+++def _question_row(form_id: str, question: dict[str, Any]) -> dict[str, Any]:+ row = dict(question)+ # `qid` is unique only within a form, so every row carries the form id for a table-wide key.+ row["form_id"] = form_id+ return row+++def _iter_list_pages(+ base_url: str,+ config: JotformEndpointConfig,+ headers: dict[str, str],+ base_params: dict[str, Any],+ manager: ResumableSourceManager[JotformResumeConfig],+ start_offset: int,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ offset = start_offset++ while True:+ params = {**base_params, "limit": config.page_size, "offset": offset}+ data = _fetch_page(f"{base_url}{config.path}", params, headers, logger)+ content = data.get("content")+ if not isinstance(content, list) or not content:+ break++ yield content++ # Save the offset of the page just yielded so a crash re-fetches and re-yields it (merge+ # dedupes on the primary key) rather than skipping it.+ manager.save_state(JotformResumeConfig(offset=offset))++ if len(content) < config.page_size:+ break+ offset += config.page_size+++def _iter_questions(+ base_url: str,+ config: JotformEndpointConfig,+ headers: dict[str, str],+ manager: ResumableSourceManager[JotformResumeConfig],+ resume: Optional[JotformResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ form_ids = get_form_ids(base_url, headers, logger)++ remaining = form_ids+ if resume is not None and resume.form_id is not None and resume.form_id in form_ids:+ # Resume from the bookmarked form (re-fetched and re-yielded; merge dedupes). If the form was+ # deleted between runs, fall through and start over from the first form.+ remaining = form_ids[form_ids.index(resume.form_id) :]+ logger.debug(f"Jotform: resuming questions from form_id={resume.form_id}")++ for form_id in remaining:+ path = config.path.format(form_id=quote(str(form_id), safe=""))+ data = _fetch_page(f"{base_url}{path}", {}, headers, logger)+ content = data.get("content")++ # `/form/{id}/questions` returns an object keyed by question id, not a list.+ if isinstance(content, dict):+ rows = [_question_row(form_id, question) for question in content.values() if isinstance(question, dict)]+ if rows:+ yield rows++ # Bookmark the form just processed so a crash resumes here rather than skipping ahead.+ manager.save_state(JotformResumeConfig(form_id=form_id))+++def get_rows(+ api_key: str,+ region: Optional[str],+ enterprise_domain: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JotformResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = JOTFORM_ENDPOINTS[endpoint]+ base_url = resolve_base_url(region, enterprise_domain)+ headers = _headers(api_key)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.fan_out_over_forms:+ yield from _iter_questions(base_url, config, headers, resumable_source_manager, resume, logger)+ return++ base_params = _build_list_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ start_offset = resume.offset if resume is not None else 0+ yield from _iter_list_pages(base_url, config, headers, base_params, resumable_source_manager, start_offset, logger)+++def jotform_source(+ api_key: str,+ region: Optional[str],+ enterprise_domain: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JotformResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = JOTFORM_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ enterprise_domain=enterprise_domain,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=list(config.primary_keys),+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format=config.partition_format 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/jotform/settings.py b/posthog/temporal/data_imports/sources/jotform/settings.pynew file mode 100644index 000000000000..39c3a08f7817--- /dev/null+++ b/posthog/temporal/data_imports/sources/jotform/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field+from typing import Optional++from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++CREATED_AT_INCREMENTAL = _datetime_field("created_at")+UPDATED_AT_INCREMENTAL = _datetime_field("updated_at")+++@dataclass+class JotformEndpointConfig:+ name: str+ # Path relative to the regional API host. A `{form_id}` placeholder marks a per-form fan-out+ # endpoint (questions), which iterates every form on the account.+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style field,+ # which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ partition_format: Optional[PartitionFormat] = None+ page_size: int = 100+ # Fan out one request per form. The questions response is an object keyed by question id (not a+ # list), so it uses the dedicated questions iterator rather than offset pagination.+ fan_out_over_forms: bool = False+++# Forms and submissions expose Jotform's server-side `filter={"<field>:gt":"..."}` timestamp filter,+# so they're advertised as incremental. Reports has no documented timestamp filter (full refresh).+# Questions describe form structure (no timestamps), fan out per form, and are full refresh; their+# `qid` is unique only within a form, so the form id is part of the primary key.+JOTFORM_ENDPOINTS: dict[str, JotformEndpointConfig] = {+ "forms": JotformEndpointConfig(+ name="forms",+ path="/user/forms",+ primary_keys=["id"],+ partition_key="created_at",+ partition_format="month",+ default_incremental_field="created_at",+ incremental_fields=[CREATED_AT_INCREMENTAL, UPDATED_AT_INCREMENTAL],+ ),+ "submissions": JotformEndpointConfig(+ name="submissions",+ path="/user/submissions",+ primary_keys=["id"],+ partition_key="created_at",+ partition_format="month",+ default_incremental_field="created_at",+ incremental_fields=[CREATED_AT_INCREMENTAL, UPDATED_AT_INCREMENTAL],+ ),+ "reports": JotformEndpointConfig(+ name="reports",+ path="/user/reports",+ primary_keys=["id"],+ partition_key="created_at",+ partition_format="month",+ ),+ "questions": JotformEndpointConfig(+ name="questions",+ path="/form/{form_id}/questions",+ primary_keys=["form_id", "qid"],+ fan_out_over_forms=True,+ ),+}++ENDPOINTS = tuple(JOTFORM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in JOTFORM_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/jotform/source.py b/posthog/temporal/data_imports/sources/jotform/source.pyindex e5d4e1e16f7c..7a5308aa269e 100644--- a/posthog/temporal/data_imports/sources/jotform/source.py+++ b/posthog/temporal/data_imports/sources/jotform/source.py@@ -1,20 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safefrom 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 JotformSourceConfig+from posthog.temporal.data_imports.sources.jotform.canonical_descriptions import CANONICAL_DESCRIPTIONS+from posthog.temporal.data_imports.sources.jotform.jotform import (+ JotformResumeConfig,+ jotform_source,+ normalize_enterprise_host,+ validate_credentials as validate_jotform_credentials,+)+from posthog.temporal.data_imports.sources.jotform.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class JotformSource(SimpleSource[JotformSourceConfig]):+class JotformSource(ResumableSource[JotformSourceConfig, JotformResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.JOTFORM@@ -25,7 +42,145 @@ class JotformSource(SimpleSource[JotformSourceConfig]):name=SchemaExternalDataSourceType.JOTFORM,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Jotform",+ caption="""Enter your Jotform API key to pull your forms and submissions into the PostHog Data warehouse.++You can create an API key in your [Jotform API settings](https://www.jotform.com/myaccount/api). A **Read-only** key is enough.++Pick the region that matches where your Jotform account is hosted. For Jotform Enterprise, leave the region as US and enter your Enterprise domain instead.++Supported tables:+- `forms`+- `submissions`+- `reports`+- `questions`+""",iconPath="/static/services/jotform.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/jotform",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.jotform.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (eu-api.jotform.com)", value="eu"),+ SourceFieldSelectConfigOption(label="HIPAA (hipaa-api.jotform.com)", value="hipaa"),+ ],+ ),+ SourceFieldInputConfig(+ name="enterprise_domain",+ label="Enterprise domain (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="forms.your-company.com",+ secret=False,+ ),+ ],+ ),+ )++ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API key is sent to whatever host `enterprise_domain` resolves to, so editing it+ # must re-require the secret — otherwise it could be retargeted at an attacker-controlled host.+ return ["enterprise_domain"]++ def get_canonical_descriptions(self):+ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Auth failures can never be fixed by retrying. Match the stable status text only (not the+ # per-request URL) so it covers every regional and Enterprise host.+ return {+ "401 Client Error": "Your Jotform API key is invalid or has been revoked. Create a new key in your Jotform API settings, then reconnect.",+ "403 Client Error": "Your Jotform API key does not have permission to read this data. Grant it read access in your Jotform API settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: JotformSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_FIELDS,+ supports_append=endpoint in INCREMENTAL_FIELDS,+ 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 _check_enterprise_host_safe(self, enterprise_domain: Optional[str], team_id: int) -> tuple[bool, str | None]:+ # `enterprise_domain` is user-supplied and the stored API key is sent to whatever it resolves+ # to, so reject internal/private hosts. Run at validation *and* before each sync, since DNS+ # can be repointed at an internal host after setup (Smokescreen re-resolves per hop too).+ host = normalize_enterprise_host(enterprise_domain)+ if host is None:+ return True, None+ is_safe, host_error = _is_host_safe(host, team_id)+ if not is_safe:+ return False, host_error or "Enterprise domain is not allowed"+ return True, None++ def validate_credentials(+ self, config: JotformSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ enterprise_domain = config.enterprise_domain++ is_safe, host_error = self._check_enterprise_host_safe(enterprise_domain, team_id)+ if not is_safe:+ return False, host_error++ if validate_jotform_credentials(config.api_key, config.region, enterprise_domain):+ return True, None++ return False, "Invalid Jotform API key, region, or Enterprise domain"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JotformResumeConfig]:+ return ResumableSourceManager[JotformResumeConfig](inputs, JotformResumeConfig)++ def source_for_pipeline(+ self,+ config: JotformSourceConfig,+ resumable_source_manager: ResumableSourceManager[JotformResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ is_safe, host_error = self._check_enterprise_host_safe(config.enterprise_domain, inputs.team_id)+ if not is_safe:+ raise ValueError(host_error or "Jotform Enterprise domain is not allowed")++ return jotform_source(+ api_key=config.api_key,+ region=config.region,+ enterprise_domain=config.enterprise_domain,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/jotform/tests/test_jotform.py b/posthog/temporal/data_imports/sources/jotform/tests/test_jotform.pynew file mode 100644index 000000000000..8e263e930d45--- /dev/null+++ b/posthog/temporal/data_imports/sources/jotform/tests/test_jotform.py@@ -0,0 +1,378 @@+from datetime import UTC, date, datetime, timedelta+from typing import Any++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.jotform.jotform import (+ JotformResumeConfig,+ JotformRetryableError,+ _build_list_params,+ _format_filter_value,+ _question_row,+ get_form_ids,+ get_rows,+ jotform_source,+ normalize_enterprise_host,+ resolve_base_url,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.jotform.settings import ENDPOINTS, JOTFORM_ENDPOINTS++US_BASE = "https://api.jotform.com"+++def _make_manager(resume_state: JotformResumeConfig | 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(content: Any, status_code: int = 200) -> mock.MagicMock:+ response = mock.MagicMock()+ response.json.return_value = {"content": content, "responseCode": status_code}+ response.status_code = status_code+ response.ok = status_code < 400+ response.text = ""+ return response+++def _params(call: mock.Mock) -> dict[str, Any]:+ return call.kwargs["params"]+++class TestResolveBaseUrl:+ @pytest.mark.parametrize(+ "region, expected",+ [+ ("us", "https://api.jotform.com"),+ ("eu", "https://eu-api.jotform.com"),+ ("hipaa", "https://hipaa-api.jotform.com"),+ ("US", "https://api.jotform.com"),+ ("unknown", "https://api.jotform.com"),+ (None, "https://api.jotform.com"),+ ],+ )+ def test_region_hosts(self, region, expected):+ assert resolve_base_url(region) == expected++ @pytest.mark.parametrize(+ "domain, expected",+ [+ ("forms.acme.com", "https://forms.acme.com/API"),+ ("https://forms.acme.com", "https://forms.acme.com/API"),+ ("http://forms.acme.com/", "https://forms.acme.com/API"),+ (" forms.acme.com/ ", "https://forms.acme.com/API"),+ ],+ )+ def test_enterprise_domain_overrides_region(self, domain, expected):+ # Enterprise domain wins over the region selection and is served under /API.+ assert resolve_base_url("eu", domain) == expected++ @pytest.mark.parametrize("domain", ["", " ", None])+ def test_blank_enterprise_domain_falls_back_to_region(self, domain):+ assert resolve_base_url("eu", domain) == "https://eu-api.jotform.com"++ @pytest.mark.parametrize(+ "domain, expected",+ [("forms.acme.com", "forms.acme.com"), ("https://forms.acme.com/", "forms.acme.com"), ("", None), (None, None)],+ )+ def test_normalize_enterprise_host(self, domain, expected):+ assert normalize_enterprise_host(domain) == expected+++class TestFormatFilterValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 15, 10, 30, 45, tzinfo=UTC), "2024-01-15 10:30:45"),+ (datetime(2024, 1, 15, 10, 30, 45), "2024-01-15 10:30:45"),+ (date(2024, 1, 15), "2024-01-15 00:00:00"),+ ("2024-01-15 10:30:45", "2024-01-15 10:30:45"),+ ("2024-01-15T10:30:45", "2024-01-15 10:30:45"),+ (None, None),+ (True, None),+ ("not-a-date", None),+ ],+ )+ def test_format(self, value, expected):+ assert _format_filter_value(value) == expected++ def test_future_value_is_capped_to_now(self):+ future = datetime.now(UTC) + timedelta(days=365)+ formatted = _format_filter_value(future)+ assert formatted is not None+ assert datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S") <= datetime.now(UTC).replace(tzinfo=None) + timedelta(+ seconds=2+ )+++class TestBuildListParams:+ def test_full_refresh_endpoint_has_no_params(self):+ # reports has no incremental fields, so no orderby/filter is sent.+ assert _build_list_params(JOTFORM_ENDPOINTS["reports"], False, None, None) == {}++ def test_incremental_off_still_orders_by_default_field(self):+ params = _build_list_params(JOTFORM_ENDPOINTS["submissions"], False, None, None)+ assert params == {"orderby": "created_at"}+ assert "filter" not in params++ def test_incremental_on_adds_gt_filter_on_chosen_field(self):+ params = _build_list_params(+ JOTFORM_ENDPOINTS["submissions"], True, datetime(2024, 1, 15, 10, 30, 45, tzinfo=UTC), "updated_at"+ )+ assert params["orderby"] == "updated_at"+ assert params["filter"] == '{"updated_at:gt":"2024-01-15 10:30:45"}'++ def test_incremental_on_without_watermark_omits_filter(self):+ params = _build_list_params(JOTFORM_ENDPOINTS["forms"], True, None, None)+ assert params == {"orderby": "created_at"}+++class TestFetchPageRetries:+ @pytest.mark.parametrize("status_code", [429, 500, 503])+ @mock.patch("tenacity.nap.time.sleep", return_value=None)+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_retryable_statuses_eventually_raise(self, mock_session, _sleep, status_code):+ mock_session.return_value.get.return_value = _response([], status_code)+ manager = _make_manager()+ with pytest.raises(JotformRetryableError):+ list(get_rows("key", "us", None, "forms", mock.MagicMock(), manager))++ @pytest.mark.parametrize("status_code", [401, 403, 404])+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_client_errors_raise_immediately(self, mock_session, status_code):+ response = _response([], status_code)+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=response)+ mock_session.return_value.get.return_value = response+ manager = _make_manager()+ with pytest.raises(requests.HTTPError):+ list(get_rows("key", "us", None, "forms", mock.MagicMock(), manager))+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.get.return_value = _response("", status_code)+ assert validate_credentials("key", "us") is expected++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", "us") is False++ @pytest.mark.parametrize(+ "region, enterprise_domain, expected_url",+ [+ ("us", None, "https://api.jotform.com/user"),+ ("eu", None, "https://eu-api.jotform.com/user"),+ ("us", "forms.acme.com", "https://forms.acme.com/API/user"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_targets_correct_host(self, mock_session, region, enterprise_domain, expected_url):+ mock_session.return_value.get.return_value = _response("", 200)+ validate_credentials("key", region, enterprise_domain)+ assert mock_session.return_value.get.call_args.args[0] == expected_url++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_sends_api_key_header(self, mock_session):+ mock_session.return_value.get.return_value = _response("", 200)+ validate_credentials("key-123", "us")+ assert mock_session.return_value.get.call_args.kwargs["headers"]["APIKEY"] == "key-123"++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_pins_redirects_off_and_redacts_key(self, mock_session):+ mock_session.return_value.get.return_value = _response("", 200)+ validate_credentials("key-123", "us", "forms.acme.com")+ # User-controlled host: no redirects off the validated host, and the key is value-redacted.+ assert mock_session.call_args.kwargs["allow_redirects"] is False+ assert mock_session.call_args.kwargs["redact_values"] == ("key-123",)+++class TestGetFormIds:+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_paginates_across_offset_pages(self, mock_session):+ page_size = JOTFORM_ENDPOINTS["forms"].page_size+ full = [{"id": f"f{i}"} for i in range(page_size)]+ partial = [{"id": "last"}]+ mock_session.return_value.get.side_effect = [_response(full), _response(partial)]++ ids = get_form_ids(US_BASE, {"APIKEY": "key"}, mock.MagicMock())++ assert len(ids) == page_size + 1+ assert ids[-1] == "last"+ assert _params(mock_session.return_value.get.call_args_list[1])["offset"] == page_size++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_skips_items_without_id_and_stringifies(self, mock_session):+ mock_session.return_value.get.return_value = _response([{"id": 42}, {"title": "no id"}])+ assert get_form_ids(US_BASE, {}, mock.MagicMock()) == ["42"]++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_pins_redirects_off_and_redacts_key(self, mock_session):+ mock_session.return_value.get.return_value = _response([{"id": "1"}])+ get_form_ids(US_BASE, {"APIKEY": "secret-key"}, mock.MagicMock())+ # Page fetches against a potentially user-controlled host must not follow redirects, and the+ # key carried in the APIKEY header is value-redacted from logs.+ assert mock_session.call_args.kwargs["allow_redirects"] is False+ assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)+++class TestGetRowsListEndpoints:+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_single_partial_page_yields_once_and_saves_offset(self, mock_session):+ mock_session.return_value.get.return_value = _response([{"id": "1"}, {"id": "2"}])++ manager = _make_manager()+ batches = list(get_rows("key", "us", None, "submissions", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1", "2"]+ saved = [c.args[0].offset for c in manager.save_state.call_args_list]+ assert saved == [0]++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_paginates_until_partial_page(self, mock_session):+ with mock.patch.object(JOTFORM_ENDPOINTS["submissions"], "page_size", 2):+ mock_session.return_value.get.side_effect = [+ _response([{"id": "1"}, {"id": "2"}]),+ _response([{"id": "3"}]),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", "us", None, "submissions", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]+ # Offset advances by page_size between pages; state saved after each yielded page.+ assert _params(mock_session.return_value.get.call_args_list[1])["offset"] == 2+ assert [c.args[0].offset for c in manager.save_state.call_args_list] == [0, 2]++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_resumes_from_saved_offset(self, mock_session):+ mock_session.return_value.get.return_value = _response([{"id": "9"}])++ manager = _make_manager(JotformResumeConfig(offset=200))+ list(get_rows("key", "us", None, "submissions", mock.MagicMock(), manager))++ assert _params(mock_session.return_value.get.call_args_list[0])["offset"] == 200++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_incremental_run_sends_gt_filter(self, mock_session):+ mock_session.return_value.get.return_value = _response([])++ manager = _make_manager()+ list(+ get_rows(+ "key",+ "us",+ None,+ "submissions",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 15, 10, 30, 45, tzinfo=UTC),+ incremental_field="created_at",+ )+ )++ params = _params(mock_session.return_value.get.call_args_list[0])+ assert params["orderby"] == "created_at"+ assert params["filter"] == '{"created_at:gt":"2024-01-15 10:30:45"}'++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_empty_content_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _response([])++ manager = _make_manager()+ assert list(get_rows("key", "us", None, "reports", mock.MagicMock(), manager)) == []+++class TestGetRowsQuestionsFanOut:+ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_fans_out_over_forms_and_injects_form_id(self, mock_session):+ forms_page = [{"id": "f1"}, {"id": "f2"}]+ f1_questions = {"1": {"qid": "1", "text": "Name"}, "2": {"qid": "2", "text": "Email"}}+ f2_questions = {"1": {"qid": "1", "text": "Age"}}+ mock_session.return_value.get.side_effect = [+ _response(forms_page),+ _response(f1_questions),+ _response(f2_questions),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", "us", None, "questions", mock.MagicMock(), manager))++ rows = [row for batch in batches for row in batch]+ assert [(row["form_id"], row["qid"]) for row in rows] == [("f1", "1"), ("f1", "2"), ("f2", "1")]+ # The form id is fetched then each form's questions endpoint is hit.+ assert mock_session.return_value.get.call_args_list[1].args[0] == f"{US_BASE}/form/f1/questions"+ assert [c.args[0].form_id for c in manager.save_state.call_args_list] == ["f1", "f2"]++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_resumes_from_bookmarked_form(self, mock_session):+ forms_page = [{"id": "f1"}, {"id": "f2"}]+ f2_questions = {"1": {"qid": "1", "text": "Age"}}+ mock_session.return_value.get.side_effect = [_response(forms_page), _response(f2_questions)]++ manager = _make_manager(JotformResumeConfig(form_id="f2"))+ batches = list(get_rows("key", "us", None, "questions", mock.MagicMock(), manager))++ rows = [row for batch in batches for row in batch]+ # f1 was completed in the prior run; only f2 is re-fetched.+ assert [(row["form_id"], row["qid"]) for row in rows] == [("f2", "1")]+ assert mock_session.return_value.get.call_args_list[1].args[0] == f"{US_BASE}/form/f2/questions"++ @mock.patch("posthog.temporal.data_imports.sources.jotform.jotform.make_tracked_session")+ def test_deleted_bookmark_form_restarts_from_first(self, mock_session):+ forms_page = [{"id": "f1"}, {"id": "f2"}]+ mock_session.return_value.get.side_effect = [+ _response(forms_page),+ _response({"1": {"qid": "1"}}),+ _response({"1": {"qid": "1"}}),+ ]++ manager = _make_manager(JotformResumeConfig(form_id="deleted-form"))+ batches = list(get_rows("key", "us", None, "questions", mock.MagicMock(), manager))++ rows = [row for batch in batches for row in batch]+ assert [row["form_id"] for row in rows] == ["f1", "f2"]++ def test_question_row_injects_form_id(self):+ assert _question_row("f9", {"qid": "3", "text": "Q"}) == {"qid": "3", "text": "Q", "form_id": "f9"}++ def test_question_row_does_not_mutate_input(self):+ question = {"qid": "3"}+ _question_row("f9", question)+ assert question == {"qid": "3"}+++class TestJotformSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = JOTFORM_ENDPOINTS[endpoint]+ response = jotform_source("key", "us", None, endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ assert response.partition_format == config.partition_format+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(JOTFORM_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ # Partitioning must never key off an updated_at-style field that rewrites on every sync.+ if config.partition_key:+ assert config.partition_key == "created_at"++ def test_questions_primary_key_includes_form_id(self):+ # qid is unique only within a form, so the table-wide key needs form_id.+ assert JOTFORM_ENDPOINTS["questions"].primary_keys == ["form_id", "qid"]diff --git a/posthog/temporal/data_imports/sources/jotform/tests/test_jotform_source.py b/posthog/temporal/data_imports/sources/jotform/tests/test_jotform_source.pynew file mode 100644index 000000000000..de70aac424c9--- /dev/null+++ b/posthog/temporal/data_imports/sources/jotform/tests/test_jotform_source.py@@ -0,0 +1,219 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import JotformSourceConfig+from posthog.temporal.data_imports.sources.jotform.jotform import JotformResumeConfig+from posthog.temporal.data_imports.sources.jotform.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.jotform.source import JotformSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestJotformSource:+ def setup_method(self):+ self.source = JotformSource()+ self.team_id = 123+ self.config = JotformSourceConfig(api_key="key-123", region="us")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.JOTFORM++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Jotform"+ assert config.label == "Jotform"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible: the scaffold's unreleasedSource flag must be gone.+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/jotform.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "region", "enterprise_domain"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_region_field_is_select_with_us_default(self):+ config = self.source.get_source_config+ region_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")+ assert region_field.required is True+ assert region_field.defaultValue == "us"+ assert [option.value for option in region_field.options] == ["us", "eu", "hipaa"]++ def test_enterprise_domain_is_optional_non_secret(self):+ config = self.source.get_source_config+ field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "enterprise_domain"+ )+ assert field.required is False+ assert field.secret is False++ def test_enterprise_domain_is_a_connection_host_field(self):+ # Editing the host the API key is sent to must re-require the secret.+ assert self.source.connection_host_fields == ["enterprise_domain"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.jotform.com/user/forms?limit=100",+ "401 Client Error: Unauthorized for url: https://eu-api.jotform.com/user/submissions",+ "403 Client Error: Forbidden for url: https://hipaa-api.jotform.com/user/forms",+ "403 Client Error: Forbidden for url: https://forms.acme.com/API/user/forms",+ ],+ )+ 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",+ [+ "429 Client Error: Too Many Requests for url: https://api.jotform.com/user/submissions",+ "500 Server Error for url: https://api.jotform.com/user/forms",+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient_or_other_vendors(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ # 5xx/429 stay retryable; a 401 from another vendor's host shouldn't be in scope here, but our+ # broad "401 Client Error" key would match it — guard only against the transient codes.+ if "401 Client Error" in other_error:+ pytest.skip("broad 401 key intentionally matches any 401")+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_only_forms_and_submissions_are_incremental(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ incremental = {name for name, s in schemas.items() if s.supports_incremental}+ assert incremental == {"forms", "submissions"}++ @pytest.mark.parametrize("endpoint", ["forms", "submissions"])+ def test_incremental_schemas_advertise_created_and_updated(self, endpoint):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].incremental_fields == INCREMENTAL_FIELDS[endpoint]+ assert schemas[endpoint].supports_append is True+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == ["created_at", "updated_at"]++ @pytest.mark.parametrize("endpoint", ["reports", "questions"])+ def test_full_refresh_schemas_have_no_incremental_fields(self, endpoint):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].incremental_fields == []+ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["forms"])+ assert [s.name for s in schemas] == ["forms"]++ 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, True, None),+ (False, False, "Invalid Jotform API key, region, or Enterprise domain"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.jotform.source.validate_jotform_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.region, None)++ @mock.patch("posthog.temporal.data_imports.sources.jotform.source._is_host_safe")+ @mock.patch("posthog.temporal.data_imports.sources.jotform.source.validate_jotform_credentials")+ def test_validate_credentials_rejects_unsafe_enterprise_host(self, mock_validate, mock_host_safe):+ mock_host_safe.return_value = (False, "Hosts with internal IP addresses are not allowed")+ config = JotformSourceConfig(api_key="key", region="us", enterprise_domain="https://10.0.0.1/")++ is_valid, error = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error == "Hosts with internal IP addresses are not allowed"+ # An unsafe host must short-circuit before we ever send the key to it.+ mock_validate.assert_not_called()+ mock_host_safe.assert_called_once_with("10.0.0.1", self.team_id)++ @mock.patch("posthog.temporal.data_imports.sources.jotform.source._is_host_safe")+ @mock.patch("posthog.temporal.data_imports.sources.jotform.source.validate_jotform_credentials")+ def test_validate_credentials_skips_host_check_without_enterprise_domain(self, mock_validate, mock_host_safe):+ mock_validate.return_value = True++ self.source.validate_credentials(self.config, self.team_id)++ mock_host_safe.assert_not_called()++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is JotformResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.jotform.source._is_host_safe", return_value=(True, None))+ @mock.patch("posthog.temporal.data_imports.sources.jotform.source.jotform_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_jotform_source, mock_host_safe):+ inputs = mock.MagicMock()+ inputs.schema_name = "submissions"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01 00:00:00"+ inputs.incremental_field = "created_at"+ config = JotformSourceConfig(api_key="key-123", region="eu", enterprise_domain="forms.acme.com")+ manager = mock.MagicMock()++ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_jotform_source.call_args.kwargs+ assert kwargs["api_key"] == "key-123"+ assert kwargs["region"] == "eu"+ assert kwargs["enterprise_domain"] == "forms.acme.com"+ assert kwargs["endpoint"] == "submissions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01 00:00:00"+ assert kwargs["incremental_field"] == "created_at"++ @mock.patch("posthog.temporal.data_imports.sources.jotform.source.jotform_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_jotform_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "reports"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01 00:00:00"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_jotform_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @mock.patch("posthog.temporal.data_imports.sources.jotform.source._is_host_safe")+ @mock.patch("posthog.temporal.data_imports.sources.jotform.source.jotform_source")+ def test_source_for_pipeline_rejects_unsafe_enterprise_host(self, mock_jotform_source, mock_host_safe):+ # DNS can be repointed at an internal host after setup, so the host is re-checked before each+ # sync — not just at validation.+ mock_host_safe.return_value = (False, "Hosts with internal IP addresses are not allowed")+ config = JotformSourceConfig(api_key="key", region="us", enterprise_domain="https://10.0.0.1/")+ inputs = mock.MagicMock()++ with pytest.raises(ValueError, match="Hosts with internal IP addresses are not allowed"):+ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ mock_jotform_source.assert_not_called()+ mock_host_safe.assert_called_once_with("10.0.0.1", inputs.team_id)++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)