: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 folk import source (#107239)
Tom Owers854e0811310c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 643b1305db05..20df2d6a9593 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -306,6 +306,7 @@ the row lists both.| flowlu | HTTP | requests | ✅ || flutterwave | HTTP | requests + `rest_source.RESTClient` | ✅ || fly_io | HTTP | requests | ✅ |+| folk | HTTP | requests + `rest_source.RESTClient` | ✅ || formbricks | HTTP | requests | ✅ || framer | WebSocket (devalue RPC) | websockets (bespoke client) | ⚠️ WebSocket || fred | HTTP | requests | ✅ |@@ -1041,7 +1042,6 @@ doesn't conflict with concurrent PRs.- flexport- flowlu- fly_io-- folk- formbricks- fortnox- fourthwalldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/canonical_descriptions.pynew file mode 100644index 000000000000..f0b50c3c6bc0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/canonical_descriptions.py@@ -0,0 +1,125 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS = "https://developer.folk.app/api-reference/overview"++# Descriptions are sourced from Folk's public API reference (developer.folk.app). Partial coverage+# is fine — any endpoint, column, or table-level description not listed here falls back to LLM+# enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "people": {+ "description": "Contacts in the Folk workspace, with their profile details, associated companies and groups, and per-group custom field values.",+ "docs_url": "https://developer.folk.app/api-reference/people/list-people",+ "columns": {+ "id": "Unique identifier for the person.",+ "first_name": "The first name of the person.",+ "last_name": "The last name of the person.",+ "full_name": "The full name of the person.",+ "description": "A short description of the person.",+ "birthday": "The birthday of the person, in ISO format.",+ "gender": "The gender of the person (Female, Male, Unknown, Other, or null).",+ "job_title": "The job title of the person.",+ "created_at": "The date and time the person was created, in ISO format.",+ "created_by": "The workspace user who created the person.",+ "groups": "The groups associated with the person.",+ "companies": "The companies associated with the person; the first is the person's primary company.",+ "addresses": "Postal addresses on the person's profile.",+ "emails": "Email addresses on the person's profile.",+ "phones": "Phone numbers on the person's profile.",+ "urls": "Websites and social profiles on the person's profile.",+ "custom_field_values": "Custom field values, keyed per group the person belongs to.",+ "interaction_metadata": "First and last interaction timestamps, for the workspace and for the API key's user.",+ "strongest_connection": "Per group, the workspace member with the strongest connection to the person.",+ },+ },+ "companies": {+ "description": "Companies in the Folk workspace, with firmographics, associated groups, and per-group custom field values.",+ "docs_url": "https://developer.folk.app/api-reference/companies/list-companies",+ "columns": {+ "id": "Unique identifier for the company.",+ "name": "The name of the company.",+ "description": "A short description of the company.",+ "funding_raised": "The amount in USD of funding raised by the company.",+ "last_funding_date": "The date of the last funding round for the company.",+ "industry": "The industry the company operates in.",+ "foundation_year": "The foundation year of the company.",+ "employee_range": "The employee range of the company (e.g. 1-10, 11-50, 51-200).",+ "groups": "The groups associated with the company.",+ "addresses": "Postal addresses on the company's profile.",+ "emails": "Email addresses on the company's profile.",+ "phones": "Phone numbers on the company's profile.",+ "urls": "Websites and social profiles on the company's profile.",+ "created_at": "The date and time the company was created, in ISO format.",+ "created_by": "The workspace user who created the company.",+ "custom_field_values": "Custom field values, keyed per group the company belongs to.",+ },+ },+ "groups": {+ "description": "Groups (contact lists / pipelines) in the Folk workspace. The API returns the groups the API key's user can access.",+ "docs_url": "https://developer.folk.app/api-reference/groups/list-groups",+ "columns": {+ "id": "Unique identifier for the group.",+ "name": "The name of the group.",+ "visibility": "The visibility of the group: public (all workspace users), private (explicit members only), or shared (members and invitees).",+ "created_by": "The workspace user who created the group.",+ },+ },+ "users": {+ "description": "Workspace members (Folk users), referenced by created-by fields, assignments, and interaction metadata.",+ "docs_url": "https://developer.folk.app/api-reference/users/list-users",+ "columns": {+ "id": "Unique identifier for the user.",+ "full_name": "The full name of the user.",+ "email": "The email address of the user.",+ },+ },+ "notes": {+ "description": "Notes attached to people, companies, or deals in the Folk workspace.",+ "docs_url": "https://developer.folk.app/api-reference/notes/list-notes",+ "columns": {+ "id": "Unique identifier for the note.",+ "entity": "The person, company, or deal the note is attached to.",+ "content": "The content of the note, in plain text or markdown.",+ "visibility": "The visibility of the note: public (all workspace users) or private (author only).",+ "author": "The workspace user who wrote the note.",+ "created_at": "The date and time the note was created, in ISO format.",+ "parent_note": "The parent note, if this note is a reply to another note.",+ },+ },+ "tasks": {+ "description": "Tasks created in the Folk workspace, with due dates, completion state, and assigned users.",+ "docs_url": "https://developer.folk.app/api-reference/tasks/list-tasks",+ "columns": {+ "id": "Unique identifier for the task.",+ "title": "The title of the task.",+ "description": "The description of the task, in markdown format.",+ "entity": "The person, company, or deal the task is connected to.",+ "recurrence_frequency": "The recurrence frequency of the task (weekday, weekly, biweekly, monthly, quarterly, yearly), or null if non-recurring.",+ "due_at": "The due date of the task.",+ "due_time": "The due time of the task.",+ "completed_at": "The date and time the task was completed, or null if not yet completed.",+ "is_public": "Whether the task is visible to all workspace members or only to its assigned users.",+ "assigned_users": "The users assigned to this task.",+ "created_by": "The workspace user who created the task.",+ "created_at": "The date and time the task was created.",+ "updated_at": "The date and time the task was last updated.",+ },+ },+ "reminders": {+ "description": "Reminders attached to people, companies, or deals in the Folk workspace, with their recurrence rules and trigger times.",+ "docs_url": "https://developer.folk.app/api-reference/reminders/list-reminders",+ "columns": {+ "id": "Unique identifier for the reminder.",+ "name": "The name of the reminder.",+ "entity": "The person, company, or deal the reminder is attached to.",+ "recurrence_rule": "The recurrence rule of the reminder, in iCalendar (RFC 5545) format.",+ "visibility": "The visibility of the reminder: public (all workspace users) or private (current user only).",+ "assigned_users": "The workspace users notified when the reminder triggers.",+ "next_trigger_time": "The next trigger time of the reminder.",+ "last_trigger_time": "The last trigger time of the reminder.",+ "created_by": "The workspace user who created the reminder.",+ "created_at": "The date and time the reminder was created, in ISO format.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/folk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/folk.pynew file mode 100644index 000000000000..7bbef769b95e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/folk.py@@ -0,0 +1,156 @@+import dataclasses+from typing import Any, Optional+from urllib.parse import urlsplit++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponsePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.settings import FOLK_BASE_URL, FOLK_ENDPOINTS++# Documented maximum on every list endpoint (the default is 20).+FOLK_PAGE_SIZE = 100+++class FolkUntrustedURLError(Exception):+ pass+++def _validate_pagination_url(url: str) -> str:+ """Pin every authenticated request to the Folk API origin.++ Both resumed `next_url` values (loaded from Redis) and upstream `pagination.nextLink` URLs are+ followed verbatim with the customer's bearer token. Validating the scheme, host, and `/v1/`+ path prefix keeps a poisoned resume state or a hostile upstream response from retargeting the+ request at another host and leaking the token (SSRF). Returns the URL unchanged when trusted.+ """+ parts = urlsplit(url)+ is_trusted = parts.scheme == "https" and parts.netloc == "api.folk.app" and parts.path.startswith("/v1/")+ if not is_trusted:+ raise FolkUntrustedURLError("Refusing to follow a pagination URL outside the Folk API")+ return url+++class FolkPaginator(JSONResponsePaginator):+ """Follows the envelope's `data.pagination.nextLink` URL, refusing any URL off the Folk API+ origin, whether it arrived in a response body or was seeded from saved resume state.++ The last page omits `nextLink` from the `pagination` object, which ends the walk."""++ def __init__(self) -> None:+ super().__init__(next_url_path="data.pagination.nextLink")++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if self._next_url is not None:+ _validate_pagination_url(self._next_url)++ def set_resume_state(self, state: dict[str, Any]) -> None:+ super().set_resume_state(state)+ if self._next_url is not None:+ _validate_pagination_url(self._next_url)++[email protected](frozen=True)+class FolkResumeConfig:+ # Full next-page URL from the response's `data.pagination.nextLink` field (omitted on the last+ # page). It carries the opaque cursor and the limit, so following it resumes the walk exactly.+ next_url: str | None = None+++def probe_credentials(api_key: str, endpoint: str | None = None) -> int | None:+ """Cheap probe of the Folk API. Returns the HTTP status code, or None on a connection failure.++ Probes the given endpoint's own path when set (one row, to confirm access to that resource),+ else `/v1/users/me`, the cheapest call that confirms the key is genuine."""+ config = FOLK_ENDPOINTS.get(endpoint) if endpoint else None+ url = f"{FOLK_BASE_URL}{config.path}?limit=1" if config else f"{FOLK_BASE_URL}/v1/users/me"+ _ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ url,+ headers={"Authorization": f"Bearer {api_key}"},+ )+ return status+++def folk_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FolkResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = schema_for_resource(FOLK_ENDPOINTS, endpoint)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": FOLK_BASE_URL,+ # Auth (Bearer) goes through the framework auth config so its value is redacted from logs.+ "auth": {"type": "bearer", "token": api_key},+ "paginator": FolkPaginator(),+ # Notes, tasks, and contact fields can carry confidential CRM content that the+ # name-based scrubber won't reliably catch (e.g. generic `content`/`description`+ # keys), so this PII-heavy source opts out of HTTP sample capture.+ "capture": False,+ },+ "resources": [+ {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": config.path,+ "params": {"limit": FOLK_PAGE_SIZE},+ "data_selector": "data.items",+ # A response missing `data.items` is a shape change, not a legitimately empty+ # page; fail loud instead of silently replacing the table with zero rows.+ "data_selector_required": True,+ },+ "table_format": "delta",+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_url:+ initial_paginator_state = {"next_url": resume.next_url}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while a next page remains; the checkpoint lands AFTER a page is yielded so a+ # crash re-yields the last page (full refresh rewrites the table, so no duplicates land).+ if state and state.get("next_url"):+ resumable_source_manager.save_state(FolkResumeConfig(next_url=state["next_url"]))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if should_use_incremental_field else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=config.name,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/settings.pynew file mode 100644index 000000000000..b4055ad1dd56--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/settings.py@@ -0,0 +1,59 @@+from dataclasses import dataclass, field+from typing import Optional++# Folk's public API (developer.folk.app). All list endpoints share one shape: bearer auth, a+# `{"data": {"items": [...], "pagination": {"nextLink": ...}}}` envelope, and cursor pagination+# via `limit` + `cursor` params (the next cursor arrives as the full `nextLink` URL).+FOLK_BASE_URL = "https://api.folk.app"+++@dataclass(frozen=True)+class FolkEndpointConfig:+ name: str+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp to partition by; None where the resource carries no timestamp+ # (groups and users).+ partition_key: Optional[str] = None+++# Every endpoint is full refresh: Folk exposes no updatedAt filter on any list endpoint, its+# createdAt filter is day-precision only, and no list endpoint takes a sort param, so an+# incremental watermark could neither catch updates nor checkpoint safely.+FOLK_ENDPOINTS: dict[str, FolkEndpointConfig] = {+ "people": FolkEndpointConfig(+ name="people",+ path="/v1/people",+ partition_key="createdAt",+ ),+ "companies": FolkEndpointConfig(+ name="companies",+ path="/v1/companies",+ partition_key="createdAt",+ ),+ "groups": FolkEndpointConfig(+ name="groups",+ path="/v1/groups",+ ),+ "users": FolkEndpointConfig(+ name="users",+ path="/v1/users",+ ),+ "notes": FolkEndpointConfig(+ name="notes",+ path="/v1/notes",+ partition_key="createdAt",+ ),+ "tasks": FolkEndpointConfig(+ name="tasks",+ path="/v1/tasks",+ partition_key="createdAt",+ ),+ "reminders": FolkEndpointConfig(+ name="reminders",+ path="/v1/reminders",+ partition_key="createdAt",+ ),+}++ENDPOINTS = tuple(FOLK_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/source.pyindex eacea487af38..ce03f19e4694 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/source.py@@ -1,14 +1,41 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.folk import (+ FolkResumeConfig,+ folk_source,+ probe_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.folk import FolkSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FolkSource(SimpleSource[FolkSourceConfig]):+class FolkSource(ResumableSource[FolkSourceConfig, FolkResumeConfig]):+ api_docs_url = "https://developer.folk.app/api-reference/overview"+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FOLK@@ -19,8 +46,90 @@ class FolkSource(SimpleSource[FolkSourceConfig]):name=ExternalDataSourceType.FOLK,category=DataWarehouseSourceCategory.CRM,label="Folk",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Folk API key to pull your CRM contacts, companies, groups, notes, tasks, and reminders into the PostHog Data warehouse.++You can create an API key in your [Folk workspace settings](https://app.folk.app/apps/contacts/network/settings/api-keys) under the "API" section. The key syncs the data its creating user can access, so create it as a user who can see the groups you want to sync.""",iconPath="/static/services/folk.png",+ docsUrl="https://posthog.com/docs/cdp/sources/folk",keywords=["crm", "contacts"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError from the transport's raise_for_status. No+ # retry can satisfy a credential problem. Match the stable status text + host, not the+ # per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.folk.app": "Your Folk API key is invalid or has been revoked. Create a new API key in your Folk workspace settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.folk.app": "Your Folk API key does not have permission to read this resource. Check the key in your Folk workspace settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: FolkSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh — see the rationale in settings.py.+ return build_endpoint_schemas(ENDPOINTS, {}, names)++ def validate_credentials(+ self,+ config: FolkSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ status = probe_credentials(config.api_key, schema_name)++ if status == 200:+ return True, None+ # At source-create (schema_name is None) a 403 means the key is genuine but scoped away+ # from the probe resource — accept it; per-endpoint access is checked when configuring a schema.+ if status == 403 and schema_name is None:+ return True, None+ if status == 401:+ return False, "Your Folk API key is invalid or has been revoked."+ if status == 403:+ return False, "Your Folk API key does not have access to this resource."+ return False, "Could not validate your Folk API key. Please check the key and try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FolkResumeConfig]:+ return ResumableSourceManager[FolkResumeConfig](inputs, FolkResumeConfig)++ def source_for_pipeline(+ self,+ config: FolkSourceConfig,+ resumable_source_manager: ResumableSourceManager[FolkResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return folk_source(+ 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,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/tests/test_folk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/tests/test_folk.pynew file mode 100644index 000000000000..f4010fe80ed8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/tests/test_folk.py@@ -0,0 +1,236 @@+import json+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.folk import (+ FolkResumeConfig,+ FolkUntrustedURLError,+ _validate_pagination_url,+ folk_source,+ probe_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.settings import FOLK_BASE_URL++# folk_source lets the RESTClient build its own tracked session, so the transport is mocked at the+# framework seam; the credential probe builds its session inside the folk module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+PROBE_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.folk.folk.make_tracked_session"+++def _response(items: list[dict[str, Any]] | None, next_url: str | None = None) -> Response:+ pagination: dict[str, Any] = {"nextLink": next_url} if next_url else {}+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps({"data": {"items": items or [], "pagination": pagination}}).encode()+ return resp+++def _make_manager(resume_state: FolkResumeConfig | 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 _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ # The paginator mutates request.url/params in place across pages, so snapshot each request at+ # prepare time instead of inspecting it after the run.+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(+ endpoint: str = "people",+ manager: mock.MagicMock | None = None,+ **kwargs: Any,+):+ return folk_source(+ api_key="folk_test",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestValidatePaginationUrl:+ def test_api_origin_url_is_returned_unchanged(self) -> None:+ url = "https://api.folk.app/v1/people?limit=100&cursor=eyJvZmZzZXQiOjEwMH0%3D"+ assert _validate_pagination_url(url) == url++ @parameterized.expand(+ [+ ("other_host", "https://evil.example.com/v1/people?cursor=x"),+ ("http_downgrade", "http://api.folk.app/v1/people?cursor=x"),+ ("userinfo_confusion", "https://[email protected]/v1/people"),+ ("wrong_path", "https://api.folk.app/steal-token"),+ ]+ )+ def test_off_origin_urls_are_refused(self, _name: str, url: str) -> None:+ # A poisoned resume state or hostile response must not retarget the bearer-token request.+ with pytest.raises(FolkUntrustedURLError):+ _validate_pagination_url(url)+++class TestPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_next_link_and_reads_the_items_envelope(self, MockSession) -> None:+ session = MockSession.return_value+ second = "https://api.folk.app/v1/people?limit=100&cursor=abc"+ snapshots = _wire(+ session,+ [+ _response([{"id": "per_1", "fullName": "Alice"}], next_url=second),+ _response([{"id": "per_2", "fullName": "Bob"}]),+ ],+ )++ rows = _rows(_source())++ assert rows == [{"id": "per_1", "fullName": "Alice"}, {"id": "per_2", "fullName": "Bob"}]+ assert snapshots[0]["url"] == f"{FOLK_BASE_URL}/v1/people"+ assert snapshots[0]["params"] == {"limit": 100}+ # The next-page URL is self-contained; the original params must not be re-appended.+ assert snapshots[1]["url"] == second+ assert snapshots[1]["params"] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_state_after_each_page_except_the_last(self, MockSession) -> None:+ session = MockSession.return_value+ second = "https://api.folk.app/v1/people?limit=100&cursor=abc"+ _wire(session, [_response([{"id": "per_1"}], next_url=second), _response([{"id": "per_2"}])])++ manager = _make_manager()+ _rows(_source(manager=manager))++ # State saved once (pointing at the second page) so a crash re-yields that page; nothing+ # is saved after the final page (no nextLink).+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == FolkResumeConfig(next_url=second)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_next_url(self, MockSession) -> None:+ session = MockSession.return_value+ resume_url = "https://api.folk.app/v1/people?limit=100&cursor=page3"+ snapshots = _wire(session, [_response([{"id": "per_9"}])])++ manager = _make_manager(FolkResumeConfig(next_url=resume_url))+ rows = _rows(_source(manager=manager))++ # Starts at the resumed URL, not the freshly-built first page.+ assert rows == [{"id": "per_9"}]+ assert snapshots[0]["url"] == resume_url+ assert snapshots[0]["params"] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_collection_yields_nothing(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([])])++ manager = _make_manager()+ assert _rows(_source(manager=manager)) == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_off_origin_next_link_is_refused(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": "per_1"}], next_url="https://evil.example.com/v1/people?cursor=x")])++ with pytest.raises(FolkUntrustedURLError):+ _rows(_source())++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_poisoned_resume_url_is_refused(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [])++ manager = _make_manager(FolkResumeConfig(next_url="https://evil.example.com/v1/people"))+ with pytest.raises(FolkUntrustedURLError):+ _rows(_source(manager=manager))+ # Refused before any request carries the bearer token off-origin.+ assert session.send.call_count == 0+++class TestUnknownEndpoint:+ def test_unknown_endpoint_raises_a_retryable_unknown_resource_error(self) -> None:+ # A web pod can offer a table this worker's catalog doesn't know yet; the named error is+ # classified retryable so the sync recovers once the rollout finishes.+ with pytest.raises(UnknownResourceError):+ _source(endpoint="deals")+++class TestBearerAuth:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_request_auth_is_framework_bearer(self, MockSession) -> None:+ session = MockSession.return_value+ session.headers = {}+ auths: list[Any] = []++ def _prepare(request: Any) -> mock.MagicMock:+ auths.append(request.auth)+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = [_response([{"id": "per_1"}])]++ _rows(_source())++ # The key flows through the framework auth (so it's redacted from logs), not a hand-built+ # Authorization header.+ prepared = mock.MagicMock()+ prepared.headers = {}+ auths[0](prepared)+ assert prepared.headers["Authorization"] == "Bearer folk_test"+++class TestProbeCredentials:+ @parameterized.expand([("ok", 200), ("unauthorized", 401), ("forbidden", 403)])+ @mock.patch(PROBE_SESSION_PATCH)+ def test_returns_status_code(self, _name: str, status_code: int, MockSession) -> None:+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert probe_credentials("folk_test") == status_code++ @mock.patch(PROBE_SESSION_PATCH)+ def test_connection_failure_returns_none(self, MockSession) -> None:+ MockSession.return_value.get.side_effect = Exception("boom")+ assert probe_credentials("folk_test") is None++ @mock.patch(PROBE_SESSION_PATCH)+ def test_default_probe_is_the_current_user_with_bearer_token(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = mock.MagicMock(status_code=200)++ probe_credentials("folk_test")++ assert session.get.call_args.args[0] == f"{FOLK_BASE_URL}/v1/users/me"+ assert session.get.call_args.kwargs["headers"]["Authorization"] == "Bearer folk_test"++ @mock.patch(PROBE_SESSION_PATCH)+ def test_schema_probe_hits_the_endpoint_path(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = mock.MagicMock(status_code=200)++ probe_credentials("folk_test", "companies")++ # Probing the endpoint's own path checks access to that resource, one row only.+ assert session.get.call_args.args[0] == f"{FOLK_BASE_URL}/v1/companies?limit=1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/folk/tests/test_folk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/tests/test_folk_source.pynew file mode 100644index 000000000000..29b55173ebbd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/folk/tests/test_folk_source.py@@ -0,0 +1,123 @@+from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, ReleaseStatus+from products.warehouse_sources.backend.temporal.data_imports.sources.folk import source as folk_source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.folk.source import FolkSource+++class TestFolkSourceConfig:+ def test_config_basics(self) -> None:+ config = FolkSource().get_source_config+ assert config.label == "Folk"+ assert config.category == DataWarehouseSourceCategory.CRM+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source ships visible — the scaffold's unreleasedSource flag must stay gone.+ assert not config.unreleasedSource+++class TestFolkGetSchemas:+ def test_every_endpoint_is_full_refresh_only(self) -> None:+ # Folk has no updatedAt filter and no sort param, so offering incremental or append would+ # sync wrong data (missed updates, corrupt watermark) — see settings.py.+ schemas = FolkSource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []+++class TestFolkValidateCredentials:+ @parameterized.expand(+ [+ # (probe status, schema_name, expected_ok)+ ("ok", 200, None, True),+ ("ok_for_schema", 200, "people", True),+ # A 403 at source-create is a genuine key scoped away from the probe resource — accept it.+ ("forbidden_at_create_accepted", 403, None, True),+ # A 403 while configuring a specific schema means no access to that resource — reject.+ ("forbidden_for_schema_rejected", 403, "people", False),+ ("unauthorized_rejected", 401, None, False),+ ("connection_failure_rejected", None, None, False),+ ("unexpected_status_rejected", 500, None, False),+ ]+ )+ def test_status_mapping(+ self, _name: str, probe_status: int | None, schema_name: str | None, expected_ok: bool+ ) -> None:+ with mock.patch.object(folk_source_module, "probe_credentials", return_value=probe_status):+ ok, error = FolkSource().validate_credentials(+ MagicMock(api_key="folk_test"), team_id=1, schema_name=schema_name+ )+ assert ok is expected_ok+ assert (error is None) is expected_ok+++class TestFolkNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.folk.app/v1/people?limit=100"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.folk.app/v1/groups?limit=100"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = FolkSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.folk.app/v1/people"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.folk.app/v1/companies"),+ ("read_timeout", "HTTPSConnectionPool(host='api.folk.app', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = FolkSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestFolkResumableAndPipeline:+ @parameterized.expand(+ [+ # (endpoint, partition keys, partition mode)+ ("people", ["createdAt"], "datetime"),+ ("companies", ["createdAt"], "datetime"),+ ("notes", ["createdAt"], "datetime"),+ ("tasks", ["createdAt"], "datetime"),+ ("reminders", ["createdAt"], "datetime"),+ # Groups and users carry no timestamp to partition by.+ ("groups", None, None),+ ("users", None, None),+ ]+ )+ def test_source_for_pipeline_per_endpoint(+ self,+ endpoint: str,+ expected_keys: list[str] | None,+ expected_mode: str | None,+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.should_use_incremental_field = False+ manager = MagicMock()+ manager.can_resume.return_value = False+ response = FolkSource().source_for_pipeline(+ MagicMock(api_key="folk_test"), resumable_source_manager=manager, inputs=inputs+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_keys == expected_keys+ assert response.partition_mode == expected_mode+++class TestFolkCanonicalDescriptions:+ def test_descriptions_keyed_by_endpoint_name(self) -> None:+ descriptions = FolkSource().get_canonical_descriptions()+ # Every documented key must be a real endpoint so enrichment binds to the right table.+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "people" in descriptions+ assert descriptions["people"]["columns"]["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/folk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/folk.pyindex 8d1c5d7375a9..f71053317d5a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/folk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/folk.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass FolkSourceConfig(config.Config):- pass+ api_key: str