: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 plunk import source (#72621)
Tom Owersf699103e292f
diff --git a/products/warehouse_sources/backend/conftest.py b/products/warehouse_sources/backend/conftest.pyindex 9135316a1d50..0682dae03218 100644--- a/products/warehouse_sources/backend/conftest.py+++ b/products/warehouse_sources/backend/conftest.py@@ -5,6 +5,22 @@ from collections.abc import Generatorimport pytest+from django.db import connection++[email protected](wrapper=True)+def pytest_runtest_setup(item: pytest.Item) -> Generator[None]:+ # Some tests in this product run production code that calls close_old_connections() from+ # worker threads (the transaction=True duckgres backfill classes), which severs the shared+ # default connection. Under pytest-xdist the next test on the same worker — often a migration+ # TestCase whose setUp drives MigrationExecutor(connection) — would then fail in setUp with+ # "the connection is closed". Drop the dead handle before each test so Django reconnects.+ wrapped = connection.connection+ if wrapped is not None and wrapped.closed:+ connection.close()+ return (yield)++# Runs in a clean interpreter — the pytest process imports the google-ads SDK itself (via the# google_ads test modules), so we can't inspect this process's sys.modules._SDK_LEAK_CHECK = """diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0ecf5e19da4b..0d10583f5304 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -433,6 +433,7 @@ the row lists both.| platform_sh | HTTP | requests | ✅ || plausible | HTTP | requests | ✅ || plivo | HTTP | requests + `rest_source.RESTClient` | ✅ |+| plunk | HTTP | requests + `rest_source.RESTClient` | ✅ || polar | HTTP | requests | ✅ || plaid | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ |@@ -880,7 +881,6 @@ doesn't conflict with concurrent PRs.- pivotal_tracker- piwik- planetscale-- plunk- podium- polygondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plunk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plunk.pyindex b74aae816d1c..26bbb54e44cb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plunk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plunk.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass PlunkSourceConfig(config.Config):- pass+ api_key: str+ base_url: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/canonical_descriptions.pynew file mode 100644index 000000000000..7519af8512ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/canonical_descriptions.py@@ -0,0 +1,85 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://docs.useplunk.com/api-reference/overview"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "contacts": {+ "description": "A person who can receive emails from the project, with their subscription state and custom metadata.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the contact.",+ "email": "The contact's email address, stored lowercased and unique per project.",+ "subscribed": "Whether the contact is currently subscribed to marketing emails.",+ "data": "Custom metadata fields attached to the contact as a JSON object (e.g. name, plan).",+ "projectId": "Identifier of the Plunk project the contact belongs to.",+ "createdAt": "When the contact was created.",+ "updatedAt": "When the contact was last updated.",+ },+ },+ "campaigns": {+ "description": "A one-time email broadcast sent to all contacts, a segment, or a filtered audience, with its delivery and engagement counts.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the campaign.",+ "name": "Internal name of the campaign.",+ "description": "Optional internal description of the campaign.",+ "status": "Lifecycle status of the campaign (e.g. DRAFT, SCHEDULED, SENDING, SENT).",+ "subject": "Email subject line.",+ "body": "HTML body of the campaign email.",+ "from": "Sender email address.",+ "fromName": "Sender display name.",+ "replyTo": "Reply-to email address.",+ "type": "Whether the campaign is a MARKETING or TRANSACTIONAL email.",+ "audienceType": "How recipients are selected: ALL contacts, a saved SEGMENT, or a FILTERED ad-hoc condition.",+ "audienceCondition": "Filter condition used when the audience is FILTERED, as a JSON object.",+ "segmentId": "Identifier of the saved segment targeted when the audience is SEGMENT.",+ "scheduledFor": "When the campaign is scheduled to send, if scheduled.",+ "totalRecipients": "Number of contacts the campaign targets.",+ "sentCount": "Number of emails sent so far.",+ "deliveredCount": "Number of emails confirmed delivered.",+ "openedCount": "Number of emails opened.",+ "clickedCount": "Number of emails with a clicked link.",+ "bouncedCount": "Number of emails that bounced.",+ "projectId": "Identifier of the Plunk project the campaign belongs to.",+ "sentAt": "When the campaign finished sending.",+ "createdAt": "When the campaign was created.",+ "updatedAt": "When the campaign was last updated.",+ },+ },+ "templates": {+ "description": "A reusable email template with subject, HTML body, and sender details, referenced by campaigns and workflow steps.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the template.",+ "name": "Internal name of the template.",+ "description": "Optional internal description of the template.",+ "subject": "Email subject line, supporting {{variable}} placeholders.",+ "body": "HTML body of the template, supporting {{variable}} placeholders.",+ "from": "Sender email address.",+ "fromName": "Sender display name.",+ "replyTo": "Reply-to email address.",+ "type": "Whether the template is for MARKETING or TRANSACTIONAL email.",+ "projectId": "Identifier of the Plunk project the template belongs to.",+ "createdAt": "When the template was created.",+ "updatedAt": "When the template was last updated.",+ },+ },+ "segments": {+ "description": "A saved audience of contacts, either dynamic (filter-based) or static (manually managed), with its cached member count.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the segment.",+ "name": "Name of the segment.",+ "description": "Optional description of the segment.",+ "type": "Whether membership is DYNAMIC (evaluated from the filter condition) or STATIC (manually managed).",+ "condition": "Nested filter condition with AND/OR logic for dynamic segments, as a JSON object.",+ "trackMembership": "Whether segment entry/exit changes are tracked as events.",+ "memberCount": "Cached number of contacts currently in the segment.",+ "projectId": "Identifier of the Plunk project the segment belongs to.",+ "createdAt": "When the segment was created.",+ "updatedAt": "When the segment was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/plunk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/plunk.pynew file mode 100644index 000000000000..c65595a1188c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/plunk.py@@ -0,0 +1,379 @@+"""Plunk transport layer.++Plunk (useplunk.com) is an open-source email platform offered both as a hosted SaaS+(``https://next-api.useplunk.com``) and self-hosted (a customer-supplied host), so the API base URL+must be configurable. Auth is a project-scoped secret API key (``sk_*``) sent as a Bearer token; the+public ``pk_*`` key is only valid for client-side event tracking and is rejected by every list+endpoint.++Contacts are cursor-paginated (``limit``/``cursor``; the response's ``cursor`` field is omitted on+the last page). Campaigns and templates are page-number paginated (``page``/``pageSize`` with a+``totalPages`` count in the body). Segments come back as one bare JSON array.++Every stream is full-refresh: no list endpoint accepts a server-side updated-since/created-after+filter (verified against the Plunk API source), even though rows carry ``createdAt``/``updatedAt``.+"""++import re+import threading+import dataclasses+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests++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_adapter+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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.settings import (+ PLUNK_ENDPOINTS,+ PlunkEndpointConfig,+)++DEFAULT_BASE_URL = "https://next-api.useplunk.com"++HOST_NOT_ALLOWED_ERROR = "Plunk API URL is not allowed"+HTTP_NOT_ALLOWED_ERROR = "Plunk API URL must use HTTPS"+PUBLIC_KEY_ERROR = "This is a public API key (pk_*). Use your project's secret API key (sk_*) instead."++# The base URL can be a customer-controlled self-hosted host, so the sync path can't trust it to+# behave. `RESTClient` calls `session.send()` without a timeout and buffers the whole body via+# `.json()`, so a host that hangs, trickles bytes, or ships a huge (or gzip-bombed) 200 could pin an+# import worker or exhaust its memory. `_BoundedPlunkSession` pins a connect/read timeout and reads+# every body incrementally under a decoded-byte cap and a wall-clock deadline before handing it back.+DEFAULT_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0) # (connect, read)+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+_READ_CHUNK_BYTES = 1024 * 1024+# The per-read socket timeout only bounds the gap between bytes, so a host trickling one byte just+# under it could keep a worker busy indefinitely. This absolute wall-clock deadline caps how long a+# single body read may take end to end, even while a read is blocked mid-chunk.+MAX_RESPONSE_SECONDS = 600.0++# The credential probe runs inline in the source-create API request (a Django worker), not a sync+# worker, so it gets much tighter bounds: its only job is to read a status code and a small JSON+# error body, so a controlled host must not be able to hold or fatten the worker even briefly.+VALIDATION_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 10.0) # (connect, read)+VALIDATION_MAX_RESPONSE_BYTES = 5 * 1024 * 1024+VALIDATION_MAX_RESPONSE_SECONDS = 30.0+++class PlunkHostNotAllowedError(Exception):+ pass+++class PlunkResponseTooLargeError(Exception):+ pass+++class PlunkResponseTimeoutError(Exception):+ pass+++def _read_bounded(+ response: requests.Response, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS+) -> bytes:+ """Read a streamed response body under both a decoded-byte cap and a total-transfer deadline.++ The read runs on a worker thread bounded by ``join(timeout=max_seconds)``, so the deadline is+ enforced as absolute wall-clock time even while a read is blocked: ``iter_content`` fills a whole+ chunk before it yields, so a host that trickles bytes just under the per-read socket timeout+ could otherwise never let an in-loop deadline check run. ``iter_content`` decodes content+ encoding as it streams, so the cap counts decoded bytes and a gzip bomb can't slip past it. On+ timeout we close the response to unblock the pending socket read and let the daemon thread unwind.+ """+ box: dict[str, Any] = {}++ def _reader() -> None:+ try:+ total = 0+ chunks: list[bytes] = []+ for chunk in response.iter_content(chunk_size=_READ_CHUNK_BYTES):+ total += len(chunk)+ if total > max_bytes:+ box["error"] = PlunkResponseTooLargeError(+ f"Plunk API response exceeded the size limit ({max_bytes} bytes)"+ )+ return+ chunks.append(chunk)+ box["data"] = b"".join(chunks)+ except Exception as exc: # surfaced on the calling thread below+ box["error"] = exc++ thread = threading.Thread(target=_reader, name="plunk-read-bounded", daemon=True)+ thread.start()+ thread.join(timeout=max_seconds)+ if thread.is_alive():+ # Close the socket so the blocked read raises and the daemon thread can exit.+ response.close()+ raise PlunkResponseTimeoutError(f"Plunk API response exceeded the download time limit ({max_seconds:g}s)")+ if "error" in box:+ raise box["error"]+ return box.get("data", b"")+++class _BoundedPlunkSession(requests.Session):+ """Tracked, no-redirect session that streams every response under a size + time bound.++ `RESTClient` invokes `send()` without a timeout and later reads the full body via `.json()`, so+ on its own it offers no defense against a customer-controlled host that hangs or returns an+ unbounded body. This pins a default connect/read timeout, streams the body through+ `_read_bounded` under a decoded-byte cap and a wall-clock deadline, then re-buffers it so the+ rest of the REST client (`.json()`, `.content`) sees an ordinary buffered response. The probe in+ `validate_credentials` reuses it with tighter caps.+ """++ def __init__(self, *, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS) -> None:+ super().__init__()+ self._max_bytes = max_bytes+ self._max_seconds = max_seconds++ def send(self, request: requests.PreparedRequest, **kwargs: Any) -> requests.Response:+ # Never follow redirects: a validated host could 3xx to an internal address (SSRF). Pin the+ # timeout only when the caller didn't set one, and stream so the body is read incrementally.+ kwargs["allow_redirects"] = False+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT_SECONDS)+ kwargs["stream"] = True+ response = super().send(request, **kwargs)+ if response.is_redirect or response.is_permanent_redirect:+ # The caller rejects the 3xx itself; don't touch the (unconsumed) body.+ return response+ response._content = _read_bounded(response, self._max_bytes, self._max_seconds)+ response._content_consumed = True # type: ignore[attr-defined]+ return response+++def _make_bounded_session(+ api_key: str, *, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS+) -> requests.Session:+ session = _BoundedPlunkSession(max_bytes=max_bytes, max_seconds=max_seconds)+ adapter = make_tracked_adapter(redact_values=(api_key,))+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session+++class PlunkResumeConfig:+ # Exactly one of these is set, matching the endpoint's pagination style. Persisted after each+ # page is yielded, so a crash before the write re-yields the last page (merge dedupes on `id`).+ cursor: str = ""+ page: int = 0+++def normalize_base_url(base_url: Optional[str]) -> str:+ """Turn whatever the user typed into a ``<scheme>://<host>`` base URL.++ Blank → the hosted Plunk SaaS. Accepts bare hosts (``plunk.example.com``) and full URLs with or+ without a scheme.+ """+ raw = (base_url or "").strip()+ if not raw:+ raw = DEFAULT_BASE_URL+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):+ raw = f"https://{raw}"+ return raw.rstrip("/")+++def _host_of(base_url: str) -> str:+ # A real Plunk base URL is just `<scheme>://<host>[:port]`. `urlparse` and requests/urllib3+ # disagree on how to split an authority that carries userinfo, a backslash, or percent-encoding,+ # and the disagreement is an SSRF bypass: for `https://safe.example%[email protected]`, `urlparse`+ # reads host `safe.example` (validated) while requests connects to `127.0.0.1` (it keeps+ # `safe.example%5c` as userinfo — it does not decode `%5c`); a raw `\` flips the split the other+ # way. Rather than reconcile two parsers, reject any authority that isn't an unambiguous bare+ # host — none of these forms appear in a legitimate Plunk URL.+ netloc = urlparse(base_url).netloc+ if "@" in netloc or "\\" in netloc or "%" in netloc:+ return ""+ return (urlparse(base_url).hostname or "").lower()+++def _is_https(base_url: str) -> bool:+ # The secret key rides in the Authorization header, so refuse plaintext HTTP to keep an on-path+ # attacker from capturing it.+ return urlparse(base_url).scheme == "https"+++def _paginator_for(config: PlunkEndpointConfig) -> BasePaginator:+ if config.pagination == "cursor":+ # The response's `cursor` field is omitted (or null) once `hasMore` is false, which is+ # exactly the terminator this paginator keys off.+ return JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor")+ if config.pagination == "page":+ return PageNumberPaginator(base_page=1, page=1, page_param="page", total_path="totalPages")+ return SinglePagePaginator()+++def _error_message(response: requests.Response) -> str | None:+ # Plunk error bodies look like {"success": false, "error": {"code", "message", ...}}.+ try:+ error = (response.json() or {}).get("error") or {}+ return error.get("message")+ except Exception:+ return None+++def validate_credentials(+ base_url: Optional[str], api_key: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe the cheapest list endpoint to confirm the secret key is genuine.++ Plunk keys are project-scoped with no per-resource scopes, so one probe covers every endpoint;+ a 403 (project disabled, unverified email) blocks syncing regardless of schema and fails+ source-create with the API's own message.+ """+ if api_key.startswith("pk_"):+ return False, PUBLIC_KEY_ERROR++ resolved_base_url = normalize_base_url(base_url)+ host = _host_of(resolved_base_url)++ if not host:+ return False, "Invalid Plunk API URL"++ # The host is fully customer-controlled for self-hosted deployments, 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, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ # Refuse plaintext HTTP before the key-bearing request goes out, so a self-hosted URL can't+ # expose the secret key on the network.+ if not _is_https(resolved_base_url):+ return False, HTTP_NOT_ALLOWED_ERROR++ url = f"{resolved_base_url}/contacts?{urlencode({'limit': 1})}"+ try:+ # A bounded session (like the sync path, but with tight validation caps) streams the probe+ # body under a decoded-byte cap and an absolute deadline, so a controlled host can't hold or+ # fatten this inline API worker. `redact_values` masks the key from captured samples; the+ # session refuses redirects so the validated host can't 3xx to an internal address (SSRF).+ session = _make_bounded_session(+ api_key, max_bytes=VALIDATION_MAX_RESPONSE_BYTES, max_seconds=VALIDATION_MAX_RESPONSE_SECONDS+ )+ response = session.get(+ url,+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=VALIDATION_TIMEOUT_SECONDS,+ allow_redirects=False,+ )+ except (requests.exceptions.RequestException, PlunkResponseTooLargeError, PlunkResponseTimeoutError) as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Plunk secret API key. Copy the sk_* key from your Plunk project settings."++ return False, _error_message(response) or f"Plunk returned an unexpected status ({response.status_code})"+++def plunk_source(+ base_url: Optional[str],+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[PlunkResumeConfig],+) -> SourceResponse:+ config = PLUNK_ENDPOINTS[endpoint]+ resolved_base_url = normalize_base_url(base_url)+ host = _host_of(resolved_base_url)++ # Seed the paginator from any saved resume state; map back into the persisted dataclass on save.+ initial_paginator_state: Optional[dict[str, Any]] = None+ if config.pagination != "single" and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ if config.pagination == "cursor" and resume.cursor:+ initial_paginator_state = {"cursor": resume.cursor}+ elif config.pagination == "page" and resume.page:+ initial_paginator_state = {"page": resume.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; the hook fires AFTER a page is yielded so a crash+ # re-yields the last page (merge dedupes on the primary key) rather than skipping it.+ if not state:+ return+ if state.get("cursor"):+ resumable_source_manager.save_state(PlunkResumeConfig(cursor=str(state["cursor"])))+ elif state.get("page") is not None:+ resumable_source_manager.save_state(PlunkResumeConfig(page=int(state["page"])))++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": dict(config.params),+ "paginator": _paginator_for(config),+ }+ if config.pagination != "single":+ # Paginated responses wrap rows under `data`; the segments endpoint returns a bare array,+ # which the framework ingests as-is when no selector is set.+ endpoint_config["data_selector"] = "data"++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": resolved_base_url,+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal address,+ # bypassing the host validation done before the request (SSRF).+ "allow_redirects": False,+ # Bound the customer-controlled host: pin a connect/read timeout and read every body+ # under a decoded-byte cap and wall-clock deadline so it can't hang a worker or OOM it.+ "session": _make_bounded_session(api_key),+ },+ "resources": [+ {+ "name": endpoint,+ "endpoint": endpoint_config,+ }+ ],+ }++ def items() -> Any:+ # Re-check at run time (not just at source-create) in case the URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud. Refuse+ # plaintext HTTP before the key is used. Both raise before any request leaves the process.+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ raise PlunkHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ if not _is_https(resolved_base_url):+ raise PlunkHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ yield from rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None, # every Plunk endpoint is full refresh — no incremental watermark+ resume_hook=save_checkpoint if config.pagination != "single" else None,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=[config.primary_key],+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ 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,+ sort_mode=config.sort_mode,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/settings.pynew file mode 100644index 000000000000..a7bbab40315c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/settings.py@@ -0,0 +1,71 @@+from dataclasses import dataclass, field+from typing import Any, Literal++from products.warehouse_sources.backend.types import IncrementalField++# Plunk caps both `limit` (cursor-paginated endpoints) and `pageSize` (page-number endpoints)+# at 100; larger values are silently clamped server-side.+DEFAULT_PAGE_SIZE = 100++# How a list endpoint paginates:+# - "cursor": `limit` + `cursor` query params; response is `{data, total, cursor, hasMore}`+# where `cursor` is omitted on the last page.+# - "page": `page` + `pageSize` query params; response is `{data, total, page, pageSize, totalPages}`.+# - "single": the endpoint returns the whole collection as a bare JSON array in one response.+PaginationStyle = Literal["cursor", "page", "single"]+++@dataclass+class PlunkEndpointConfig:+ name: str+ # Path under the API base URL (Plunk's data endpoints carry no version prefix).+ path: str+ pagination: PaginationStyle+ primary_key: str = "id"+ # Static query params for every request. Plunk's list endpoints accept an explicit+ # `sort=createdAt&dir=asc`, which keeps pagination stable while rows are inserted mid-sync.+ params: dict[str, Any] = field(default_factory=dict)+ # A STABLE datetime field to partition by — never one that mutates on update.+ partition_key: str | None = "createdAt"+ # The order rows actually arrive in given `params` (or the endpoint's fixed default order).+ sort_mode: Literal["asc", "desc"] = "asc"+ # Plunk exposes no server-side updated-since/created-after filter on any list endpoint+ # (verified against the API source), so every endpoint is full-refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++PLUNK_ENDPOINTS: dict[str, PlunkEndpointConfig] = {+ "contacts": PlunkEndpointConfig(+ name="contacts",+ path="/contacts",+ pagination="cursor",+ params={"limit": DEFAULT_PAGE_SIZE, "sort": "createdAt", "dir": "asc"},+ ),+ "campaigns": PlunkEndpointConfig(+ name="campaigns",+ path="/campaigns",+ pagination="page",+ params={"pageSize": DEFAULT_PAGE_SIZE, "sort": "createdAt", "dir": "asc"},+ ),+ "templates": PlunkEndpointConfig(+ name="templates",+ path="/templates",+ pagination="page",+ params={"pageSize": DEFAULT_PAGE_SIZE, "sort": "createdAt", "dir": "asc"},+ ),+ # Returns every segment as a bare JSON array (newest first), so there is nothing to+ # paginate or partition — projects hold at most a handful of segments.+ "segments": PlunkEndpointConfig(+ name="segments",+ path="/segments",+ pagination="single",+ partition_key=None,+ sort_mode="desc",+ ),+}++ENDPOINTS = tuple(PLUNK_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PLUNK_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/source.pyindex 7bbf27afab8c..20f587d894a7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/source.py@@ -1,30 +1,143 @@-from typing import cast+from typing import Optional, castfrom 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,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.plunk import PlunkSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.plunk import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ PlunkResumeConfig,+ plunk_source,+ validate_credentials as validate_plunk_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PlunkSource(SimpleSource[PlunkSourceConfig]):+class PlunkSource(ResumableSource[PlunkSourceConfig, PlunkResumeConfig]):+ # Plunk's data endpoints carry no version prefix (only the public send/track endpoints+ # are versioned), so the source is unversioned.+ api_docs_url = "https://docs.useplunk.com/api-reference/overview"+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PLUNK+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored secret key is sent; retargeting it must re-require the key.+ return ["base_url"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Plunk secret API key. Copy the sk_* key from your Plunk project settings and reconnect.",+ "403 Client Error": "Plunk rejected the request. Check that your project is active and your account email is verified.",+ HOST_NOT_ALLOWED_ERROR: "The Plunk API URL is not allowed. Please use a publicly reachable host.",+ HTTP_NOT_ALLOWED_ERROR: "The Plunk API URL must use HTTPS. Please update the API URL to use https://.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: PlunkSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # No Plunk list endpoint accepts a server-side timestamp filter, so every+ # endpoint is full-refresh only (INCREMENTAL_FIELDS is empty per endpoint).+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: PlunkSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_plunk_credentials(config.base_url, config.api_key, schema_name, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PlunkResumeConfig]:+ return ResumableSourceManager[PlunkResumeConfig](inputs, PlunkResumeConfig)++ def source_for_pipeline(+ self,+ config: PlunkSourceConfig,+ resumable_source_manager: ResumableSourceManager[PlunkResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return plunk_source(+ base_url=config.base_url,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PLUNK,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Plunk",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["useplunk", "email marketing"],+ caption="""Enter your Plunk secret API key to pull your contacts, campaigns, templates, and segments into the PostHog Data warehouse.++You can find your secret API key (it starts with `sk_`) in your Plunk project settings under **Project Settings > API Keys**. The public key (`pk_`) cannot read data.++Self-hosted users should set the API URL to their own Plunk API host (for example `https://plunk-api.example.com`). Leave it blank to use the hosted Plunk (`https://next-api.useplunk.com`).""",iconPath="/static/services/plunk.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/plunk",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sk_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API URL (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://next-api.useplunk.com",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/tests/test_plunk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/tests/test_plunk.pynew file mode 100644index 000000000000..7fef2065c25a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/tests/test_plunk.py@@ -0,0 +1,490 @@+import io+import json+import threading+from typing import Any, cast+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import TrackedHTTPAdapter+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk import plunk as plunk_module+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.plunk import (+ DEFAULT_TIMEOUT_SECONDS,+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ PUBLIC_KEY_ERROR,+ PlunkHostNotAllowedError,+ PlunkResponseTimeoutError,+ PlunkResponseTooLargeError,+ PlunkResumeConfig,+ _make_bounded_session,+ _read_bounded,+ normalize_base_url,+ plunk_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.settings import PLUNK_ENDPOINTS++# The sync path runs through a bounded session built by `_make_bounded_session`; patch that so the+# pagination tests can drive `session.send` directly (RESTClient uses the session it's handed).+CLIENT_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.plunk.plunk._make_bounded_session"+)+++def _response(*, status_code: int = 200, body: Any = None) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode() if body is not None else b""+ return resp+++def _cursor_page(rows: list[dict[str, Any]], *, cursor: str | None = None, has_more: bool = False) -> Response:+ # Plunk omits the `cursor` key entirely on the last page (undefined is dropped by JSON+ # serialization server-side), so only include it when set.+ body: dict[str, Any] = {"data": rows, "total": len(rows), "hasMore": has_more}+ if cursor is not None:+ body["cursor"] = cursor+ return _response(body=body)+++def _numbered_page(rows: list[dict[str, Any]], *, page: int, total_pages: int) -> Response:+ return _response(body={"data": rows, "total": 0, "page": page, "pageSize": 100, "totalPages": total_pages})+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[requests.PreparedRequest]:+ """Wire a mock session; delegate prepare_request to a real session so auth + params are applied."""+ session.headers = {}+ real = requests.Session()+ prepared: list[requests.PreparedRequest] = []++ def _prepare(request: Any) -> requests.PreparedRequest:+ real.headers.clear()+ real.headers.update(session.headers)+ p = real.prepare_request(request)+ prepared.append(p)+ return p++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return prepared+++def _make_manager(resume_state: PlunkResumeConfig | 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 _source(manager: mock.MagicMock, *, base_url: str | None = None, endpoint: str = "contacts") -> Any:+ return plunk_source(+ base_url=base_url,+ api_key="sk_test",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _qs(prepared: requests.PreparedRequest) -> dict[str, list[str]]:+ assert prepared.url is not None+ return parse_qs(urlparse(prepared.url).query)+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, "https://next-api.useplunk.com"),+ ("", "https://next-api.useplunk.com"),+ (" ", "https://next-api.useplunk.com"),+ ("https://next-api.useplunk.com/", "https://next-api.useplunk.com"),+ ("plunk.example.com", "https://plunk.example.com"),+ ("http://plunk.example.com/", "http://plunk.example.com"),+ ],+ )+ def test_normalize(self, raw, expected):+ assert normalize_base_url(raw) == expected++ @pytest.mark.parametrize(+ "url, expected_host",+ [+ ("https://plunk.example.com", "plunk.example.com"),+ ("https://plunk.example.com:8443", "plunk.example.com"),+ ],+ )+ def test_host_of_plain_authority(self, url, expected_host):+ assert plunk_module._host_of(url) == expected_host++ @pytest.mark.parametrize(+ "url",+ [+ # urlparse and requests/urllib3 split these authorities differently, so validating the+ # urlparse host lets a request reach a different address (SSRF). urllib3 does NOT decode+ # `%5c`, so `safe.example%5c` stays userinfo and requests connects to `127.0.0.1`, while+ # a raw `\` is a path separator and flips the split the other way. Reject them outright.+ "https://safe.example%[email protected]",+ "https://safe.example%[email protected]",+ "https://127.0.0.1\\@example.com",+ "https://user:[email protected]",+ ],+ )+ def test_host_of_rejects_ambiguous_authority(self, url):+ assert plunk_module._host_of(url) == ""+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(plunk_module, "_make_bounded_session", return_value=session)++ def _resp(self, *, status_code=200, json_data=None):+ response = mock.MagicMock()+ response.status_code = status_code+ response.is_redirect = status_code in (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ response.json.return_value = json_data+ return response++ def test_success(self):+ with self._patch_session(self._resp(status_code=200)):+ assert validate_credentials(None, "sk_test") == (True, None)++ def test_invalid_key_401(self):+ with self._patch_session(self._resp(status_code=401)):+ valid, msg = validate_credentials(None, "sk_bad")+ assert valid is False+ assert "Invalid Plunk secret API key" in (msg or "")++ def test_public_key_rejected_before_any_request(self):+ # The pk_* key only works for event tracking; catching it locally gives a clearer error+ # than the API's 401 and never sends the key anywhere.+ with self._patch_session(self._resp(status_code=200)) as patched:+ assert validate_credentials(None, "pk_test") == (False, PUBLIC_KEY_ERROR)+ patched.return_value.get.assert_not_called()++ def test_403_surfaces_api_error_message(self):+ # Plunk 403s (project disabled, unverified email) block syncing outright, so source-create+ # must fail with the API's own explanation.+ response = self._resp(+ status_code=403,+ json_data={"success": False, "error": {"code": "FORBIDDEN", "message": "Please verify your email"}},+ )+ with self._patch_session(response):+ valid, msg = validate_credentials(None, "sk_test")+ assert valid is False+ assert msg == "Please verify your email"++ def test_request_exception_returns_failure(self):+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials(None, "sk_test")+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ with self._patch_session(self._resp(status_code=302)) as patched:+ valid, msg = validate_credentials(None, "sk_test")+ assert valid is False+ assert msg == HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host_before_request(self):+ with (+ mock.patch.object(plunk_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(self._resp(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("https://10.0.0.1", "sk_test", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()++ @pytest.mark.parametrize(+ "url",+ ["https://safe.example%[email protected]", "https://safe.example%[email protected]"],+ )+ def test_rejects_ambiguous_authority_before_request(self, url):+ # The urlparse host (`safe.example`) is not the address requests reaches (`127.0.0.1`), so+ # validation must fail before the key-bearing probe goes out (SSRF bypass guard).+ with self._patch_session(self._resp(status_code=200)) as patched:+ valid, msg = validate_credentials(url, "sk_test", team_id=99)+ assert valid is False+ assert msg == "Invalid Plunk API URL"+ patched.return_value.get.assert_not_called()++ def test_rejects_plaintext_http_before_sending_key(self):+ with self._patch_session(self._resp(status_code=200)) as patched:+ valid, msg = validate_credentials("http://plunk.example.com", "sk_test")+ assert valid is False+ assert msg == HTTP_NOT_ALLOWED_ERROR+ patched.return_value.get.assert_not_called()++ def test_probe_hits_configured_host_with_bearer_key(self):+ with self._patch_session(self._resp(status_code=200)) as patched:+ validate_credentials("https://plunk.example.com", "sk_test")+ call = patched.return_value.get.call_args+ assert call.args[0].startswith("https://plunk.example.com/contacts")+ assert call.kwargs["headers"]["Authorization"] == "Bearer sk_test"+ # The key is handed to the session factory (which wires it into sample redaction), and+ # the probe runs under tight validation caps so a controlled host can't hold the worker.+ assert patched.call_args.args[0] == "sk_test"+ assert patched.call_args.kwargs["max_bytes"] == plunk_module.VALIDATION_MAX_RESPONSE_BYTES+ assert patched.call_args.kwargs["max_seconds"] == plunk_module.VALIDATION_MAX_RESPONSE_SECONDS++ def test_probe_surfaces_oversized_or_stalled_body_as_failure(self):+ # A controlled host that overruns the validation caps fails source-create rather than+ # propagating as an unhandled 500 out of the inline probe.+ with self._patch_session(raises=plunk_module.PlunkResponseTooLargeError("too big")):+ valid, msg = validate_credentials("https://plunk.example.com", "sk_test")+ assert valid is False+ assert "too big" in (msg or "")+++class TestSourceResponseShape:+ @pytest.mark.parametrize("endpoint", list(PLUNK_ENDPOINTS.keys()))+ def test_response_shape(self, endpoint):+ config = PLUNK_ENDPOINTS[endpoint]+ response = _source(_make_manager(), endpoint=endpoint)+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == config.sort_mode+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestCursorPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_cursor_until_omitted(self, MockSession):+ session = MockSession.return_value+ prepared = _wire(+ session,+ [+ _cursor_page([{"id": "1"}, {"id": "2"}], cursor="c_2", has_more=True),+ _cursor_page([{"id": "3"}]),+ ],+ )+ rows = _rows(_source(_make_manager()))++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ first_qs, second_qs = _qs(prepared[0]), _qs(prepared[1])+ # First request carries the stable ascending sort and page size; no cursor yet.+ assert first_qs["limit"] == ["100"]+ assert first_qs["sort"] == ["createdAt"]+ assert first_qs["dir"] == ["asc"]+ assert "cursor" not in first_qs+ assert second_qs["cursor"] == ["c_2"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_cursor_after_yielding(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _cursor_page([{"id": "1"}], cursor="c_1", has_more=True),+ _cursor_page([{"id": "2"}]),+ ],+ )+ manager = _make_manager()+ _rows(_source(manager))++ # State is saved once (after page 1, pointing at the next cursor); the last page is terminal.+ assert manager.save_state.call_count == 1+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, PlunkResumeConfig)+ assert saved.cursor == "c_1"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, MockSession):+ session = MockSession.return_value+ prepared = _wire(session, [_cursor_page([{"id": "9"}])])+ rows = _rows(_source(_make_manager(PlunkResumeConfig(cursor="c_9"))))++ assert _qs(prepared[0])["cursor"] == ["c_9"]+ assert [r["id"] for r in rows] == ["9"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sends_bearer_key_and_redacts_it(self, MockSession):+ session = MockSession.return_value+ prepared = _wire(session, [_cursor_page([{"id": "1"}])])+ _rows(_source(_make_manager()))++ assert prepared[0].headers["Authorization"] == "Bearer sk_test"+ # The key is handed to the session factory, which wires it into the tracked adapter's+ # value redaction (asserted directly in TestBoundedSession).+ assert MockSession.call_args.args == ("sk_test",)+ assert session.send.call_args.kwargs["allow_redirects"] is False+++class TestPageNumberPagination:+ @pytest.mark.parametrize("endpoint", ["campaigns", "templates"])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_via_total_pages(self, MockSession, endpoint):+ session = MockSession.return_value+ prepared = _wire(+ session,+ [+ _numbered_page([{"id": "1"}], page=1, total_pages=2),+ _numbered_page([{"id": "2"}], page=2, total_pages=2),+ ],+ )+ rows = _rows(_source(_make_manager(), endpoint=endpoint))++ assert [r["id"] for r in rows] == ["1", "2"]+ first_qs = _qs(prepared[0])+ assert first_qs["page"] == ["1"]+ assert first_qs["pageSize"] == ["100"]+ assert first_qs["sort"] == ["createdAt"]+ assert first_qs["dir"] == ["asc"]+ assert _qs(prepared[1])["page"] == ["2"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_next_page_after_yielding_and_resumes(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _numbered_page([{"id": "1"}], page=1, total_pages=2),+ _numbered_page([{"id": "2"}], page=2, total_pages=2),+ ],+ )+ manager = _make_manager()+ _rows(_source(manager, endpoint="campaigns"))++ assert manager.save_state.call_count == 1+ saved = manager.save_state.call_args.args[0]+ assert saved.page == 2++ session_two = mock.MagicMock()+ with mock.patch(CLIENT_SESSION_PATCH, return_value=session_two):+ prepared = _wire(session_two, [_numbered_page([{"id": "2"}], page=2, total_pages=2)])+ rows = _rows(_source(_make_manager(PlunkResumeConfig(page=2)), endpoint="campaigns"))++ assert _qs(prepared[0])["page"] == ["2"]+ assert [r["id"] for r in rows] == ["2"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_page_terminates(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_numbered_page([], page=1, total_pages=5)])+ manager = _make_manager()+ rows = _rows(_source(manager, endpoint="templates"))++ assert rows == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()+++class TestSegments:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_bare_array_ingested_in_single_request(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response(body=[{"id": "s1"}, {"id": "s2"}])])+ manager = _make_manager()+ rows = _rows(_source(manager, endpoint="segments"))++ assert [r["id"] for r in rows] == ["s1", "s2"]+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()+++class TestHostSafety:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_raises_when_host_not_allowed_at_sync_time(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_cursor_page([{"id": "1"}])])+ with mock.patch.object(plunk_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(PlunkHostNotAllowedError):+ _rows(_source(_make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_raises_on_plaintext_http_before_sending_key(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_cursor_page([{"id": "1"}])])+ with pytest.raises(PlunkHostNotAllowedError):+ _rows(_source(_make_manager(), base_url="http://plunk.example.com"))+ session.send.assert_not_called()+++class _FakeStreamResponse:+ """Minimal streamed `requests.Response` stand-in: yields fixed chunks and records close()."""++ def __init__(self, chunks: list[bytes], *, block: bool = False) -> None:+ self._chunks = chunks+ self._block = block+ self._released = threading.Event()+ self.closed = False++ def iter_content(self, chunk_size: int = 1) -> Any:+ yield from self._chunks+ if self._block:+ # Never completes on its own; only close() releases it. Models a host that stops mid-body.+ self._released.wait()++ def close(self) -> None:+ self.closed = True+ self._released.set()+++class TestReadBounded:+ def test_reads_full_body_under_cap(self):+ response = _FakeStreamResponse([b"hel", b"lo"])+ assert _read_bounded(cast(requests.Response, response), max_bytes=100) == b"hello"++ def test_raises_when_body_exceeds_byte_cap(self):+ # The cap is what stops a huge (or gzip-bombed) body from exhausting a worker's memory.+ response = _FakeStreamResponse([b"a" * 8, b"b" * 8])+ with pytest.raises(PlunkResponseTooLargeError):+ _read_bounded(cast(requests.Response, response), max_bytes=10)++ def test_times_out_and_closes_a_stalled_body(self):+ # A host that stalls mid-body must not pin the worker: the deadline fires and the socket is+ # closed. max_seconds=0 makes the join return immediately while the reader is still blocked.+ response = _FakeStreamResponse([b"partial"], block=True)+ with pytest.raises(PlunkResponseTimeoutError):+ _read_bounded(cast(requests.Response, response), max_bytes=100, max_seconds=0)+ assert response.closed is True+++class TestBoundedSession:+ def test_send_pins_default_timeout_and_rebuffers_body(self):+ session = _make_bounded_session("sk_test")+ captured: dict[str, Any] = {}++ def fake_super_send(request, **kwargs):+ captured.update(kwargs)+ resp = requests.Response()+ resp.status_code = 200+ resp.raw = io.BytesIO(b'{"data": []}')+ return resp++ with mock.patch.object(requests.Session, "send", side_effect=fake_super_send):+ response = session.send(requests.PreparedRequest())++ # A timeout is pinned when the caller passes none, redirects are refused, and the body is+ # streamed — then re-buffered so RESTClient's `.json()` still works.+ assert captured["timeout"] == DEFAULT_TIMEOUT_SECONDS+ assert captured["allow_redirects"] is False+ assert captured["stream"] is True+ assert response.json() == {"data": []}++ def test_factory_wires_key_redaction_into_adapter(self):+ session = _make_bounded_session("sk_secret")+ adapter = cast(TrackedHTTPAdapter, session.get_adapter("https://plunk.example.com"))+ assert adapter._redact_values == ("sk_secret",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/tests/test_plunk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/tests/test_plunk_source.pynew file mode 100644index 000000000000..3bba122315c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plunk/tests/test_plunk_source.py@@ -0,0 +1,118 @@+import pytest+from unittest import mock++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.generated_configs.plunk import PlunkSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.plunk import PlunkResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.plunk.source import PlunkSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPlunkSource:+ def setup_method(self):+ self.source = PlunkSource()+ self.team_id = 123+ self.config = PlunkSourceConfig(api_key="sk_test", base_url=None)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PLUNK++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Plunk"+ assert config.label == "Plunk"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/plunk.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/plunk"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "base_url"]++ api_key_field, base_url_field = config.fields+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ assert isinstance(base_url_field, SourceFieldInputConfig)+ assert base_url_field.type == SourceFieldInputConfigType.TEXT+ assert base_url_field.secret is False+ assert base_url_field.required is False++ def test_connection_host_fields_force_secret_reentry(self):+ # The secret key is sent to base_url, so retargeting it must re-require the key.+ assert self.source.connection_host_fields == ["base_url"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints_full_refresh(self):+ # No Plunk list endpoint accepts a server-side timestamp filter, so every stream must+ # ship full-refresh only — flipping one to incremental would corrupt sync watermarks.+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ @pytest.mark.parametrize(+ "names, expected",+ [+ (["contacts"], {"contacts"}),+ (["nope"], set()),+ ],+ )+ def test_get_schemas_filtered_by_names(self, names, expected):+ assert {s.name for s in self.source.get_schemas(self.config, self.team_id, names=names)} == expected++ def test_lists_tables_without_credentials(self):+ # Static endpoint catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.plunk.source.validate_plunk_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate):+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="contacts")++ assert result == (True, None)+ mock_validate.assert_called_once_with(self.config.base_url, self.config.api_key, "contacts", self.team_id)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PlunkResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.plunk.source.plunk_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_plunk_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "contacts"+ inputs.team_id = 42+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_plunk_source.assert_called_once()+ kwargs = mock_plunk_source.call_args.kwargs+ assert kwargs["base_url"] == self.config.base_url+ assert kwargs["api_key"] == "sk_test"+ assert kwargs["endpoint"] == "contacts"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42++ def test_canonical_descriptions_match_endpoint_catalog(self):+ # Descriptions are keyed by schema name; a rename in settings.py must not silently+ # orphan the curated docs.+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)