: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 unleash import source (#69378)
Tom Owersee10e5515fa5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7f91d73f1606..685c52fbef88 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -363,6 +363,7 @@ the row lists both.| twilio | HTTP | requests | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || ubidots | HTTP | requests | ✅ |+| unleash | HTTP | requests | ✅ || vercel | HTTP | requests | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ |@@ -736,7 +737,6 @@ doesn't conflict with concurrent PRs.- twitter_ads- tyntec_sms-- unleash- uppromote- uptick- us_censusdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 76a2e6e60174..f20ea961798a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3553,7 +3553,8 @@ class UbidotsSourceConfig(config.Config):@config.configclass UnleashSourceConfig(config.Config):- pass+ instance_url: str+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/canonical_descriptions.pynew file mode 100644index 000000000000..2652e4be4581--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/canonical_descriptions.py@@ -0,0 +1,151 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "features": {+ "description": "A feature flag with its type, project, lifecycle state, and per-environment strategy/rollout status.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/search-features",+ "columns": {+ "name": "Unique name of the feature flag across the whole Unleash instance.",+ "type": "Type of the flag: release, experiment, operational, kill-switch, or permission.",+ "description": "Detailed description of the feature flag.",+ "project": "Id of the project the flag belongs to.",+ "stale": "Whether the flag has outlived its expected lifetime and is marked stale.",+ "impressionData": "Whether the flag emits impression events to analytics when evaluated.",+ "createdAt": "When the feature flag was created.",+ "archivedAt": "When the feature flag was archived, or null if it is active.",+ "environments": "Per-environment state: enabled status, strategy presence, and last seen timestamps.",+ "segments": "Names of the segments referenced by the flag's strategies.",+ "tags": "Tags applied to the feature flag, as (type, value) pairs.",+ "dependencyType": "Whether the flag is a parent or child in a flag dependency, or null.",+ "lastSeenAt": "The last time metrics were reported for the flag (mutates; not a sync cursor).",+ },+ },+ "projects": {+ "description": "A project, Unleash's top-level grouping of feature flags with its own members and health metrics.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-projects",+ "columns": {+ "id": "Unique id of the project.",+ "name": "Display name of the project.",+ "description": "Detailed description of the project.",+ "health": "Project health score based on the proportion of healthy (non-stale) flags.",+ "featureCount": "Number of feature flags in the project.",+ "memberCount": "Number of users who are members of the project.",+ "mode": "Collaboration mode of the project: open, protected, or private.",+ "createdAt": "When the project was created.",+ "archivedAt": "When the project was archived, or null if it is active.",+ },+ },+ "environments": {+ "description": "A deployment environment (e.g. development, production) that flags can be enabled in.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-all-environments",+ "columns": {+ "name": "Unique name of the environment.",+ "type": "Type of the environment: development, test, preproduction, or production.",+ "enabled": "Whether the environment is enabled for use across the instance.",+ "protected": "Whether the environment is protected from deletion (true for the built-in default).",+ "sortOrder": "Priority used to sort environments in the Unleash UI.",+ "projectCount": "Number of projects the environment is visible in.",+ "apiTokenCount": "Number of API tokens scoped to the environment.",+ "enabledToggleCount": "Number of feature flags enabled in the environment.",+ },+ },+ "strategies": {+ "description": "An activation strategy definition (built-in or custom) with its parameter schema.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-all-strategies",+ "columns": {+ "name": "Unique name of the activation strategy.",+ "displayName": "Human-friendly name shown in the Unleash UI.",+ "description": "Detailed description of what the strategy does.",+ "editable": "Whether the strategy can be edited (false for built-in strategies).",+ "deprecated": "Whether the strategy is deprecated and hidden from new flag configuration.",+ "parameters": "Schema of the parameters the strategy accepts (name, type, required).",+ },+ },+ "segments": {+ "description": "A reusable set of strategy constraints that can be referenced by multiple feature flags.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-segments",+ "columns": {+ "id": "Unique id of the segment.",+ "name": "Name of the segment.",+ "description": "Detailed description of the segment.",+ "project": "Id of the project the segment is scoped to, or null for a global segment.",+ "constraints": "Constraint expressions (context field, operator, values) that make up the segment.",+ "createdBy": "User who created the segment.",+ "createdAt": "When the segment was created.",+ "usedInProjects": "Number of projects with flags referencing the segment.",+ "usedInFeatures": "Number of feature flags referencing the segment.",+ },+ },+ "context_fields": {+ "description": "A context field available for strategy constraints, such as userId or sessionId.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-context-fields",+ "columns": {+ "name": "Unique name of the context field.",+ "description": "Detailed description of the context field.",+ "stickiness": "Whether the field can be used as a stickiness basis for gradual rollouts.",+ "sortOrder": "Priority used to sort context fields in the Unleash UI.",+ "legalValues": "Allowed values for the field, each with an optional description.",+ "createdAt": "When the context field was created.",+ "usedInProjects": "Number of projects with constraints using the field.",+ "usedInFeatures": "Number of feature flags with constraints using the field.",+ },+ },+ "tags": {+ "description": "A tag applied to feature flags, identified by its tag type and value.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-tags",+ "columns": {+ "type": "Tag type the tag belongs to (e.g. simple, jira).",+ "value": "Value of the tag within its type.",+ },+ },+ "tag_types": {+ "description": "A tag type, the namespace that groups related tags (e.g. simple, jira).",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-tag-types",+ "columns": {+ "name": "Unique name of the tag type.",+ "description": "Detailed description of the tag type.",+ "icon": "Icon shown for the tag type in the Unleash UI.",+ "color": "Hex color used for the tag type in the Unleash UI.",+ },+ },+ "feature_types": {+ "description": "A feature flag type (release, experiment, operational, kill-switch, permission) with its expected lifetime.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-all-feature-types",+ "columns": {+ "id": "Unique id of the feature flag type.",+ "name": "Display name of the feature flag type.",+ "description": "What the flag type is intended for.",+ "lifetimeDays": "Expected number of days before a flag of this type is considered potentially stale, or null for permanent.",+ },+ },+ "addons": {+ "description": "A configured integration (addon) such as a webhook, Slack, or Datadog notifier. Sensitive parameters are masked by the API.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-addons",+ "columns": {+ "id": "Unique id of the addon configuration.",+ "provider": "Integration provider the addon uses (e.g. webhook, slack, datadog).",+ "description": "Detailed description of the addon configuration.",+ "enabled": "Whether the addon is currently active.",+ "events": "Event types that trigger the addon (e.g. feature-created, feature-archived).",+ "parameters": "Provider-specific configuration; sensitive values are masked by the API.",+ "projects": "Projects the addon listens to, or empty for all projects.",+ "environments": "Environments the addon listens to, or empty for all environments.",+ },+ },+ "users": {+ "description": "A user account on the Unleash instance. Requires a token with the Admin root role.",+ "docs_url": "https://docs.getunleash.io/reference/api/unleash/get-users",+ "columns": {+ "id": "Unique id of the user.",+ "name": "Display name of the user.",+ "email": "Email address of the user.",+ "username": "Username of the user, when set instead of an email.",+ "rootRole": "Id of the user's root role (e.g. Admin, Editor, Viewer).",+ "createdAt": "When the user account was created.",+ "seenAt": "The last time the user logged in (mutates; not a sync cursor).",+ "isService": "Whether the account is a service account rather than a person.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/settings.pynew file mode 100644index 000000000000..e202162d12a4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/settings.py@@ -0,0 +1,99 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class UnleashEndpointConfig:+ name: str+ # Path under the instance base URL (Unleash Admin API lives at /api/admin).+ path: str+ # Top-level key the list of records lives under in the response body, or None when the+ # endpoint returns a bare JSON array (context fields).+ data_selector: Optional[str]+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Only the feature search endpoint supports offset/limit pagination; every other Admin API+ # list endpoint returns the full collection in one response.+ paginated: bool = False+ # Endpoints gated on the ADMIN root permission (verified against a live instance: a+ # non-admin personal access token gets a 403 PermissionError here).+ requires_admin: bool = False+++# Unleash Admin API list endpoints. All are full refresh only: the Admin API exposes no+# server-side updated_after/created_after filter on these resources, so there is no reliable+# timestamp cursor to advance an incremental sync. Collections are configuration-sized, so a+# full pull per sync is cheap.+UNLEASH_ENDPOINTS: dict[str, UnleashEndpointConfig] = {+ # Feature flag search (Unleash 5.12+). Flag names are unique across the whole instance, so+ # `name` is a safe primary key. Fetched sorted by createdAt ascending for stable page+ # boundaries while paginating.+ "features": UnleashEndpointConfig(+ name="features",+ path="/api/admin/search/features",+ data_selector="features",+ primary_keys=["name"],+ paginated=True,+ ),+ "projects": UnleashEndpointConfig(+ name="projects",+ path="/api/admin/projects",+ data_selector="projects",+ ),+ "environments": UnleashEndpointConfig(+ name="environments",+ path="/api/admin/environments",+ data_selector="environments",+ primary_keys=["name"],+ ),+ "strategies": UnleashEndpointConfig(+ name="strategies",+ path="/api/admin/strategies",+ data_selector="strategies",+ primary_keys=["name"],+ ),+ "segments": UnleashEndpointConfig(+ name="segments",+ path="/api/admin/segments",+ data_selector="segments",+ ),+ # Returns a bare JSON array (no wrapper object).+ "context_fields": UnleashEndpointConfig(+ name="context_fields",+ path="/api/admin/context",+ data_selector=None,+ primary_keys=["name"],+ ),+ # A tag is identified by its (type, value) pair — there is no id column.+ "tags": UnleashEndpointConfig(+ name="tags",+ path="/api/admin/tags",+ data_selector="tags",+ primary_keys=["type", "value"],+ ),+ "tag_types": UnleashEndpointConfig(+ name="tag_types",+ path="/api/admin/tag-types",+ data_selector="tagTypes",+ primary_keys=["name"],+ ),+ "feature_types": UnleashEndpointConfig(+ name="feature_types",+ path="/api/admin/feature-types",+ data_selector="types",+ ),+ "addons": UnleashEndpointConfig(+ name="addons",+ path="/api/admin/addons",+ data_selector="addons",+ ),+ "users": UnleashEndpointConfig(+ name="users",+ path="/api/admin/user-admin",+ data_selector="users",+ requires_admin=True,+ ),+}++ENDPOINTS = tuple(UNLEASH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/source.pyindex 0f52f1397e6c..d399d240655e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/source.py@@ -1,30 +1,158 @@-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UnleashSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.settings import (+ ENDPOINTS,+ UNLEASH_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.unleash import (+ UnleashResumeConfig,+ check_endpoint_permissions,+ unleash_source,+ validate_credentials as validate_unleash_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class UnleashSource(SimpleSource[UnleashSourceConfig]):+class UnleashSource(ResumableSource[UnleashSourceConfig, UnleashResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.UNLEASH+ @property+ def connection_host_fields(self) -> list[str]:+ # `instance_url` is where the stored API token is sent; retargeting it must re-require the token.+ return ["instance_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.UNLEASH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Unleash",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["feature flags", "feature toggles", "getunleash"],+ caption="""Enter your Unleash instance URL and an Admin API token to sync your feature flags, projects, environments, strategies, segments, and other configuration data into the PostHog Data warehouse.++The instance URL is where you open the Unleash UI — for Unleash cloud it includes your instance name (e.g. `https://us.app.unleash-hosted.com/your-instance`); for self-hosted it's your server's URL. The token is a [personal access token](https://docs.getunleash.io/how-to/how-to-create-personal-access-tokens) or, on Enterprise, a [service account token](https://docs.getunleash.io/reference/service-accounts); it inherits the owner's permissions, and the `users` table additionally requires the Admin root role. The `features` table uses the flag search API, which requires Unleash 5.12 or newer.+""",iconPath="/static/services/unleash.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/unleash",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="instance_url",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://us.app.unleash-hosted.com/your-instance",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Unleash API token is invalid or has expired. Generate a new personal access token or service account token and reconnect.",+ "Unauthorized for url": "Your Unleash API token is invalid or has expired. Generate a new personal access token or service account token and reconnect.",+ "403 Client Error": "Your Unleash API token does not have permission to read this data. Check the token owner's role (the users table requires the Admin root role), then reconnect.",+ }++ def get_schemas(+ self,+ config: UnleashSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — the Admin API exposes no server-side+ # updated_after/created_after filter, so there is no timestamp cursor to advance an+ # incremental sync (see settings.py).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: UnleashSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_unleash_credentials(config.instance_url, config.api_token, schema_name, team_id)++ def get_endpoint_permissions(+ self, config: UnleashSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ # Tokens inherit their owner's role, so per-table access varies (users needs the Admin+ # root role). Probe each endpoint so the schema picker can flag unreadable tables.+ return check_endpoint_permissions(config.instance_url, config.api_token, endpoints, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UnleashResumeConfig]:+ return ResumableSourceManager[UnleashResumeConfig](inputs, UnleashResumeConfig)++ def source_for_pipeline(+ self,+ config: UnleashSourceConfig,+ resumable_source_manager: ResumableSourceManager[UnleashResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in UNLEASH_ENDPOINTS:+ raise ValueError(f"Unknown Unleash schema '{inputs.schema_name}'")++ return unleash_source(+ instance_url=config.instance_url,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/tests/test_unleash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/tests/test_unleash.pynew file mode 100644index 000000000000..3d5e0a0e8f28--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/tests/test_unleash.py@@ -0,0 +1,436 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.unleash import unleash+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.settings import UNLEASH_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.unleash import (+ PAGE_SIZE,+ UnleashHostNotAllowedError,+ UnleashResumeConfig,+ UnleashRetryableError,+ _extract_rows,+ _headers,+ check_endpoint_permissions,+ get_rows,+ normalize_instance_url,+ unleash_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_unwrapped = unleash._fetch.__wrapped__ # type: ignore[attr-defined]++BASE_URL = "https://unleash.example.com"+TOKEN = "user:secret-token"+++def _mock_response(+ status_code: int = 200,+ json_data: Any = None,+ is_redirect: bool = False,+) -> MagicMock:+ response = MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.ok = status_code < 400+ response.is_redirect = is_redirect+ response.is_permanent_redirect = False+ response.json.return_value = json_data+ response.text = str(json_data)+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} Client Error", response=response) if status_code >= 400 else None+ )+ return response+++class _FakeResumableManager:+ def __init__(self, state: UnleashResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[UnleashResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> UnleashResumeConfig | None:+ return self._state++ def save_state(self, data: UnleashResumeConfig) -> None:+ self.saved.append(data)+++class TestUnleash:+ # --- URL normalization ---++ @parameterized.expand(+ [+ ("plain", "https://unleash.example.com", "https://unleash.example.com"),+ ("trailing_slash", "https://unleash.example.com/", "https://unleash.example.com"),+ ("api_suffix", "https://unleash.example.com/api", "https://unleash.example.com"),+ ("api_admin_suffix", "https://unleash.example.com/api/admin/", "https://unleash.example.com"),+ ("no_scheme", "unleash.example.com", "https://unleash.example.com"),+ ("whitespace", " https://unleash.example.com ", "https://unleash.example.com"),+ (+ # Unleash cloud URLs carry the instance name as a path prefix — it must be preserved.+ "cloud_path_prefix",+ "https://us.app.unleash-hosted.com/my-instance/",+ "https://us.app.unleash-hosted.com/my-instance",+ ),+ (+ "cloud_path_prefix_with_api_suffix",+ "https://us.app.unleash-hosted.com/my-instance/api/admin",+ "https://us.app.unleash-hosted.com/my-instance",+ ),+ ]+ )+ def test_normalize_instance_url(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_instance_url(raw) == expected++ def test_headers_send_raw_token_without_bearer_prefix(self) -> None:+ # Unleash rejects Bearer-prefixed tokens — the raw token is the whole header value.+ assert _headers(TOKEN)["Authorization"] == TOKEN++ # --- row extraction ---++ @parameterized.expand(+ [+ ("wrapped", "projects", {"version": 1, "projects": [{"id": "a"}]}, [{"id": "a"}]),+ ("bare_array", "context_fields", [{"name": "userId"}], [{"name": "userId"}]),+ ]+ )+ def test_extract_rows(self, _name: str, endpoint: str, payload: Any, expected: list[dict]) -> None:+ assert _extract_rows(payload, UNLEASH_ENDPOINTS[endpoint], "http://url") == expected++ @parameterized.expand(+ [+ ("wrapped_missing_key", "projects", {"version": 1}),+ ("wrapped_got_array", "projects", [{"id": "a"}]),+ ("bare_got_object", "context_fields", {"fields": []}),+ ]+ )+ def test_extract_rows_rejects_unexpected_payloads(self, _name: str, endpoint: str, payload: Any) -> None:+ with pytest.raises(UnleashRetryableError):+ _extract_rows(payload, UNLEASH_ENDPOINTS[endpoint], "http://url")++ # --- fetch ---++ @parameterized.expand([(429,), (500,), (503,)])+ def test_fetch_raises_retryable_on_transient_statuses(self, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(status_code=status_code)+ with pytest.raises(UnleashRetryableError):+ _fetch_unwrapped(session, "http://url", None, MagicMock())++ @parameterized.expand([(401,), (403,), (404,)])+ def test_fetch_raises_http_error_on_permanent_statuses(self, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(status_code=status_code)+ with pytest.raises(requests.HTTPError):+ _fetch_unwrapped(session, "http://url", None, MagicMock())++ @parameterized.expand([(301,), (302,), (307,)])+ def test_fetch_refuses_redirects(self, status_code: int) -> None:+ # The session never follows redirects — a 3xx would move the sync off the validated+ # host (SSRF), so it must fail rather than be treated as an empty page.+ session = MagicMock()+ session.get.return_value = _mock_response(status_code=status_code)+ with pytest.raises(UnleashHostNotAllowedError):+ _fetch_unwrapped(session, "http://url", None, MagicMock())++ # --- get_rows ---++ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[Any, Any],+ endpoint: str,+ ) -> tuple[list[dict], list[dict[str, Any]]]:+ """Run get_rows with a fake _fetch keyed by the `offset` param (None = unpaginated)."""+ calls: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, params: Optional[dict], logger: Any) -> Any:+ calls.append({"url": url, "params": params})+ return pages[params["offset"] if params else None]++ monkeypatch.setattr(unleash, "_fetch", fake_fetch)+ monkeypatch.setattr(unleash, "make_tracked_session", lambda **kwargs: MagicMock())+ monkeypatch.setattr(unleash, "_check_host", lambda instance_url, team_id: None)++ rows: list[dict] = []+ for batch in get_rows(+ instance_url=BASE_URL,+ api_token=TOKEN,+ endpoint=endpoint,+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows, calls++ def test_unpaginated_endpoint_fetches_once_without_resume_state(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, calls = self._collect(+ manager, monkeypatch, {None: {"version": 1, "projects": [{"id": "a"}, {"id": "b"}]}}, "projects"+ )+ assert rows == [{"id": "a"}, {"id": "b"}]+ assert len(calls) == 1+ assert calls[0]["url"] == f"{BASE_URL}/api/admin/projects"+ assert calls[0]["params"] is None+ # The whole collection arrives in one response, so there is nothing to resume.+ assert manager.saved == []++ def test_unpaginated_endpoint_with_no_rows_yields_no_batches(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()++ def fake_fetch(session: Any, url: str, params: Any, logger: Any) -> Any:+ return {"version": 1, "projects": []}++ monkeypatch.setattr(unleash, "_fetch", fake_fetch)+ monkeypatch.setattr(unleash, "make_tracked_session", lambda **kwargs: MagicMock())+ monkeypatch.setattr(unleash, "_check_host", lambda instance_url, team_id: None)++ batches = list(+ get_rows(+ instance_url=BASE_URL,+ api_token=TOKEN,+ endpoint="projects",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )+ # An empty collection must not push an empty batch into the pipeline.+ assert batches == []++ def test_paginated_endpoint_walks_offsets_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ full_page = [{"name": f"flag-{i}"} for i in range(PAGE_SIZE)]+ pages = {+ 0: {"features": full_page, "total": PAGE_SIZE + 2},+ PAGE_SIZE: {"features": [{"name": "x"}, {"name": "y"}], "total": PAGE_SIZE + 2},+ }+ rows, calls = self._collect(manager, monkeypatch, pages, "features")++ assert len(rows) == PAGE_SIZE + 2+ assert [c["params"]["offset"] for c in calls] == [0, PAGE_SIZE]+ # Stable ascending sort keeps page boundaries fixed while walking offsets.+ assert all(+ c["params"]["sortBy"] == "createdAt"+ and c["params"]["sortOrder"] == "asc"+ and c["params"]["limit"] == PAGE_SIZE+ for c in calls+ )+ # State is saved once — after the first (full) page, pointing at the next offset.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_paginated_endpoint_stops_on_short_page_without_total(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, calls = self._collect(manager, monkeypatch, {0: {"features": [{"name": "only"}]}}, "features")+ assert rows == [{"name": "only"}]+ assert len(calls) == 1+ assert manager.saved == []++ def test_paginated_endpoint_stops_when_total_reached_on_full_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ full_page = [{"name": f"flag-{i}"} for i in range(PAGE_SIZE)]+ rows, calls = self._collect(manager, monkeypatch, {0: {"features": full_page, "total": PAGE_SIZE}}, "features")+ assert len(rows) == PAGE_SIZE+ # total == offset means the collection is exhausted — no extra empty-page request.+ assert len(calls) == 1+ assert manager.saved == []++ def test_paginated_endpoint_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(UnleashResumeConfig(offset=PAGE_SIZE))+ pages = {PAGE_SIZE: {"features": [{"name": "x"}], "total": PAGE_SIZE + 1}}+ rows, calls = self._collect(manager, monkeypatch, pages, "features")+ assert rows == [{"name": "x"}]+ assert [c["params"]["offset"] for c in calls] == [PAGE_SIZE]++ def test_get_rows_blocks_unsafe_hosts(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (False, "blocked"))+ with pytest.raises(UnleashHostNotAllowedError):+ list(+ get_rows(+ instance_url="https://10.0.0.1",+ api_token=TOKEN,+ endpoint="projects",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ # --- SourceResponse assembly ---++ @parameterized.expand(+ [+ ("features", ["name"]),+ # A tag has no id — its identity is the (type, value) pair; a single-column key here+ # would seed duplicate rows and multi-match on every merge.+ ("tags", ["type", "value"]),+ ]+ )+ def test_unleash_source_returns_declared_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ response = unleash_source(+ instance_url=BASE_URL,+ api_token=TOKEN,+ endpoint=endpoint,+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys++ # --- credential validation ---++ def _validate(self, monkeypatch: Any, response: MagicMock, schema_name: Optional[str] = None) -> tuple:+ session = MagicMock()+ session.get.return_value = response+ monkeypatch.setattr(unleash, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (True, None))+ return validate_credentials(BASE_URL, TOKEN, schema_name=schema_name, team_id=1)++ def test_validate_credentials_success(self, monkeypatch: Any) -> None:+ assert self._validate(monkeypatch, _mock_response(200, {"projects": []})) == (True, None)++ def test_validate_credentials_invalid_token(self, monkeypatch: Any) -> None:+ valid, message = self._validate(monkeypatch, _mock_response(401, {"message": "nope"}))+ assert valid is False+ assert message == "Invalid Unleash API token"++ def test_validate_credentials_accepts_403_at_source_create(self, monkeypatch: Any) -> None:+ # A valid token may lack the permission for the probe endpoint; source creation must+ # still go through, and per-schema syncs surface their own permission errors.+ assert self._validate(monkeypatch, _mock_response(403, {"message": "denied"})) == (True, None)++ def test_validate_credentials_rejects_403_for_scoped_probe(self, monkeypatch: Any) -> None:+ valid, message = self._validate(monkeypatch, _mock_response(403, {"message": "denied"}), schema_name="users")+ assert valid is False+ assert message == "denied"++ def test_validate_credentials_rejects_redirects(self, monkeypatch: Any) -> None:+ # A redirect could bounce the probe to an internal address, defeating the host check.+ valid, _ = self._validate(monkeypatch, _mock_response(200, {}, is_redirect=True))+ assert valid is False++ def test_validate_credentials_rejects_unsafe_host(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (False, "blocked"))+ valid, message = validate_credentials("https://10.0.0.1", TOKEN, team_id=1)+ assert valid is False+ assert message == "blocked"++ @parameterized.expand(+ [+ ("blank", " "),+ ("bad_scheme", "ftp://unleash.example.com"),+ # Parser-differential SSRF guards: urlparse and urllib3 disagree on where the+ # authority ends for backslash/userinfo URLs, so validation could approve one host+ # while requests connects to another.+ ("userinfo", "https://[email protected]"),+ ("backslash", "https://169.254.169.254\\@unleash.example.com"),+ ("encoded_backslash", "https://169.254.169.254%[email protected]"),+ ]+ )+ def test_validate_credentials_rejects_malformed_or_ambiguous_urls(self, _name: str, raw_url: str) -> None:+ valid, message = validate_credentials(raw_url, TOKEN, team_id=1)+ assert valid is False+ assert message == "Invalid Unleash instance URL"++ @parameterized.expand(+ [+ # The token rides in the Authorization header, so plaintext http is rejected on cloud+ # (public egress) but allowed off cloud (self-hosted controls its own network path).+ ("http_on_cloud", True, "http://unleash.example.com", None),+ ("http_off_cloud", False, "http://unleash.example.com", "unleash.example.com"),+ ("https_on_cloud", True, "https://unleash.example.com", "unleash.example.com"),+ ]+ )+ def test_validated_hostname_requires_https_only_on_cloud(+ self, _name: str, cloud: bool, url: str, expected: Optional[str]+ ) -> None:+ with patch.object(unleash, "is_cloud", return_value=cloud):+ assert unleash._validated_hostname(url) == expected++ def test_check_endpoint_permissions_rejects_ambiguous_url_for_all_endpoints(self) -> None:+ result = check_endpoint_permissions(+ "https://169.254.169.254\\@unleash.example.com", TOKEN, ["projects", "users"], team_id=1+ )+ assert result == {"projects": "Invalid Unleash instance URL", "users": "Invalid Unleash instance URL"}++ def test_get_rows_blocks_ambiguous_url(self) -> None:+ with pytest.raises(UnleashHostNotAllowedError):+ list(+ get_rows(+ instance_url="https://169.254.169.254\\@unleash.example.com",+ api_token=TOKEN,+ endpoint="projects",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ def test_validate_credentials_handles_connection_errors(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(unleash, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (True, None))+ valid, message = validate_credentials(BASE_URL, TOKEN, team_id=1)+ assert valid is False+ assert message is not None and "Could not connect to Unleash" in message++ # --- per-endpoint permissions ---++ def test_check_endpoint_permissions_flags_admin_gated_tables(self, monkeypatch: Any) -> None:+ def get(url: str, params: Any = None, **kwargs: Any) -> MagicMock:+ if url.endswith("/api/admin/user-admin"):+ return _mock_response(403, {"message": "You need the ADMIN permission."})+ return _mock_response(200, {"projects": [], "features": [], "total": 0})++ session = MagicMock()+ session.get.side_effect = get+ monkeypatch.setattr(unleash, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (True, None))++ result = check_endpoint_permissions(BASE_URL, TOKEN, ["projects", "features", "users"], team_id=1)+ assert result["projects"] is None+ assert result["features"] is None+ assert result["users"] is not None and "Admin root role" in result["users"]++ @parameterized.expand(+ [+ # Transient failures are not permission problems — they must not flag the table.+ ("server_error", 500, None),+ ("throttled", 429, None),+ ("invalid_token", 401, "Invalid Unleash API token"),+ ]+ )+ def test_check_endpoint_permissions_status_mapping(+ self, _name: str, status_code: int, expected: Optional[str]+ ) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(status_code, {})+ with (+ patch.object(unleash, "make_tracked_session", lambda **kwargs: session),+ patch.object(unleash, "_is_host_safe", lambda host, team_id: (True, None)),+ ):+ result = check_endpoint_permissions(BASE_URL, TOKEN, ["projects"], team_id=1)+ assert result["projects"] == expected++ def test_check_endpoint_permissions_treats_network_blips_as_reachable(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(unleash, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (True, None))+ assert check_endpoint_permissions(BASE_URL, TOKEN, ["projects"], team_id=1) == {"projects": None}++ def test_check_endpoint_permissions_blocks_unsafe_host_for_all_endpoints(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(unleash, "_is_host_safe", lambda host, team_id: (False, "blocked"))+ result = check_endpoint_permissions("https://10.0.0.1", TOKEN, ["projects", "users"], team_id=1)+ assert result == {"projects": "blocked", "users": "blocked"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/tests/test_unleash_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/tests/test_unleash_source.pynew file mode 100644index 000000000000..2cbac7e500fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/tests/test_unleash_source.py@@ -0,0 +1,145 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UnleashSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.source import UnleashSource+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.unleash import UnleashResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestUnleashSource:+ def setup_method(self) -> None:+ self.source = UnleashSource()+ self.team_id = 123+ self.config = UnleashSourceConfig(instance_url="https://unleash.example.com", api_token="user:secret-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.UNLEASH++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Unleash"+ assert config.label == "Unleash"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/unleash"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["instance_url", "api_token"]++ def test_api_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_connection_host_fields_covers_instance_url(self) -> None:+ # The stored API token is sent to whatever `instance_url` points at, so retargeting the+ # URL must force the editor to re-enter the token.+ assert self.source.connection_host_fields == ["instance_url"]++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ 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)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["features"])+ assert len(schemas) == 1+ assert schemas[0].name == "features"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://unleash.example.com/api/admin/projects",),+ ("403 Client Error: Forbidden for url: https://unleash.example.com/api/admin/user-admin",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://unleash.example.com/api/admin/projects",),+ ("429 Client Error: Too Many Requests for url: https://unleash.example.com/api/admin/segments",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.unleash.source.validate_unleash_credentials"+ )+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Unleash API token")+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="features")+ assert result == (False, "Invalid Unleash API token")+ mock_validate.assert_called_once_with(+ "https://unleash.example.com", "user:secret-token", "features", self.team_id+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.unleash.source.check_endpoint_permissions"+ )+ def test_get_endpoint_permissions_delegates_to_shared_helper(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = {"users": "needs admin", "features": None}+ result = self.source.get_endpoint_permissions(self.config, self.team_id, ["users", "features"])+ assert result == {"users": "needs admin", "features": None}+ mock_check.assert_called_once_with(+ "https://unleash.example.com", "user:secret-token", ["users", "features"], self.team_id+ )++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is UnleashResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.unleash.source.unleash_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "features"+ inputs.team_id = self.team_id+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["instance_url"] == "https://unleash.example.com"+ assert kwargs["api_token"] == "user:secret-token"+ assert kwargs["endpoint"] == "features"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "nope"+ with pytest.raises(ValueError, match="Unknown Unleash schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/unleash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/unleash.pynew file mode 100644index 000000000000..57d9c18c3b5b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/unleash/unleash.py@@ -0,0 +1,334 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.cloud_utils import is_cloud++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.unleash.settings import (+ UNLEASH_ENDPOINTS,+ UnleashEndpointConfig,+)++# The feature search endpoint documents a default limit of 50; 100 verified working against a+# live instance and keeps round trips low.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap list endpoint used to confirm the token is genuine. Every admin-capable token (personal+# access token, service account token) can read projects.+DEFAULT_PROBE_PATH = "/api/admin/projects"++HOST_NOT_ALLOWED_ERROR = "Unleash instance URL is not allowed"+++class UnleashRetryableError(Exception):+ pass+++class UnleashHostNotAllowedError(Exception):+ pass+++class UnleashResumeConfig:+ # Offset of the next feature-search page to fetch. Only the features endpoint paginates;+ # a crashed sync resumes from the page after the last one yielded and merge dedupes the+ # re-pulled page on the primary key. The other endpoints return the whole collection in one+ # request, so there is nothing to resume.+ offset: int = 0+++def normalize_instance_url(instance_url: str) -> str:+ """Turn whatever the user typed into a consistent instance base URL.++ Unleash instances live at a per-customer URL that may include a path prefix (e.g.+ ``https://us.app.unleash-hosted.com/some-instance`` on Unleash cloud), so the path must be+ preserved — we only strip a scheme-less prefix, trailing slashes, and an accidentally-pasted+ ``/api`` or ``/api/admin`` suffix.+ """+ url = instance_url.strip().rstrip("/")+ # Only default the scheme for bare hosts — a non-http(s) scheme must survive normalization+ # so _validated_hostname can reject it.+ if url and "://" not in url:+ url = f"https://{url}"+ for suffix in ("/api/admin", "/api"):+ if url.lower().endswith(suffix):+ url = url[: -len(suffix)]+ break+ return url.rstrip("/")+++def _headers(api_token: str) -> dict[str, str]:+ # Unleash expects the token as the raw Authorization header value — no Bearer prefix+ # (verified against a live instance; a Bearer-prefixed token is rejected).+ return {"Authorization": api_token, "Accept": "application/json"}+++def _get_session(api_token: str) -> requests.Session:+ # The instance URL is user-supplied, so pin redirects off so host validation and the+ # outbound request stay on the same target (SSRF defense-in-depth). Redact the token+ # from logs.+ return make_tracked_session(headers=_headers(api_token), redact_values=(api_token,), allow_redirects=False)+++def _validated_hostname(base_url: str) -> Optional[str]:+ """Hostname of the normalized instance URL, or None when the URL is malformed or ambiguous.++ SSRF guard: urlparse treats a backslash as ordinary userinfo and an "@" as a userinfo+ separator, but urllib3/requests treat the backslash as an authority separator, so+ `https://127.0.0.1\\@example.com` validates as example.com yet connects to 127.0.0.1.+ A legitimate instance URL has no userinfo, so reject either construct outright (same+ guard as the n8n source) and require a plain http(s) URL with a clean hostname.+ """+ if "\\" in base_url or "%5c" in base_url.lower():+ return None+ parsed = urlparse(base_url)+ if parsed.scheme not in ("http", "https") or "@" in parsed.netloc:+ return None+ # The API token rides in the Authorization header on every request, so plaintext http would+ # leak it to any network observer. On PostHog Cloud the request egresses over the public+ # internet, so require https. Self-hosted operators control their own network path (e.g. an+ # internal Unleash reachable only over http), so http stays allowed there — mirroring how host+ # IP safety is only enforced on cloud.+ if parsed.scheme == "http" and is_cloud():+ return None+ hostname = parsed.hostname+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):+ return None+ return hostname+++def _check_host(instance_url: str, team_id: int) -> None:+ hostname = _validated_hostname(normalize_instance_url(instance_url))+ if not hostname:+ raise UnleashHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ raise UnleashHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+++def _extract_rows(data: Any, config: UnleashEndpointConfig, url: str) -> list[dict[str, Any]]:+ if config.data_selector is None:+ if not isinstance(data, list):+ raise UnleashRetryableError(f"Unleash returned an unexpected payload for {url}: {type(data).__name__}")+ return data+ if not isinstance(data, dict) or not isinstance(data.get(config.data_selector), list):+ raise UnleashRetryableError(f"Unleash returned an unexpected payload for {url}: {type(data).__name__}")+ return data[config.data_selector]+++@retry(+ retry=retry_if_exception_type((UnleashRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: Optional[dict[str, Any]],+ logger: FilteringBoundLogger,+) -> Any:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ # The session never follows redirects: a 3xx would move the sync off the validated host+ # (SSRF), so refuse it rather than silently fetching an empty body.+ if 300 <= response.status_code < 400:+ raise UnleashHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)++ if response.status_code == 429 or response.status_code >= 500:+ raise UnleashRetryableError(f"Unleash API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Unleash API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ instance_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UnleashResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = UNLEASH_ENDPOINTS[endpoint]+ # Re-check at run time (not just at source-create) in case the instance URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ _check_host(instance_url, team_id)++ base_url = normalize_instance_url(instance_url)+ url = f"{base_url}{config.path}"+ session = _get_session(api_token)++ if not config.paginated:+ rows = _extract_rows(_fetch(session, url, None, logger), config, url)+ if rows:+ yield rows+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume:+ logger.debug(f"Unleash: resuming {endpoint} from offset {offset}")++ while True:+ # Sort by createdAt ascending so page boundaries stay stable while we walk the offsets —+ # flags created mid-sync land at the end instead of shifting earlier pages.+ params: dict[str, Any] = {+ "limit": PAGE_SIZE,+ "offset": offset,+ "sortBy": "createdAt",+ "sortOrder": "asc",+ }+ data = _fetch(session, url, params, logger)+ rows = _extract_rows(data, config, url)+ if rows:+ yield rows++ offset += len(rows)+ total = data.get("total") if isinstance(data, dict) else None+ # Stop on a short/empty page, or once the reported total is reached.+ if len(rows) < PAGE_SIZE or (isinstance(total, int) and offset >= total):+ break++ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(UnleashResumeConfig(offset=offset))+++def unleash_source(+ instance_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UnleashResumeConfig],+) -> SourceResponse:+ config = UNLEASH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ instance_url=instance_url,+ api_token=api_token,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def _error_message(response: requests.Response) -> Optional[str]:+ # Unleash error bodies carry a human-readable `message` (e.g. PermissionError details).+ try:+ body = response.json()+ if isinstance(body, dict) and isinstance(body.get("message"), str):+ return body["message"]+ except Exception:+ pass+ return None+++def validate_credentials(+ instance_url: str, api_token: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe a cheap list endpoint to confirm the token is genuine.++ At source-create (``schema_name is None``) a 403 is accepted: the token is valid but may lack+ the permission for this particular probe. A scoped probe (``schema_name`` set) treats 403 as a+ hard failure.+ """+ base_url = normalize_instance_url(instance_url)+ hostname = _validated_hostname(base_url)+ if not hostname:+ return False, "Invalid Unleash instance URL"++ # The instance URL is fully customer-controlled, so block hosts that resolve to private/+ # internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ session = _get_session(api_token)+ try:+ # The session never follows redirects: the validated host could 3xx to an internal+ # address, defeating the host check above (SSRF).+ response = session.get(f"{base_url}{DEFAULT_PROBE_PATH}", timeout=15)+ except requests.exceptions.RequestException as e:+ return False, f"Could not connect to Unleash: {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 Unleash API token"++ if response.status_code == 403:+ if schema_name is None:+ # Valid token, missing permission for this probe — let source creation through.+ return True, None+ return False, _error_message(response) or "Your Unleash API token lacks the required permissions"++ return False, _error_message(response) or f"Unleash returned HTTP {response.status_code}"+++def check_endpoint_permissions(+ instance_url: str, api_token: str, endpoints: list[str], team_id: int+) -> dict[str, str | None]:+ """Probe each endpoint and report which ones the token cannot read.++ Returns ``{endpoint: None}`` when reachable and ``{endpoint: reason}`` on a real denial+ (401/403). Transient failures (throttles, 5xx, network blips) are not permission problems, so+ they report as reachable rather than blocking the schema picker.+ """+ base_url = normalize_instance_url(instance_url)+ hostname = _validated_hostname(base_url)+ if not hostname:+ return dict.fromkeys(endpoints, "Invalid Unleash instance URL")+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ return dict.fromkeys(endpoints, host_err or HOST_NOT_ALLOWED_ERROR)++ session = _get_session(api_token)+ results: dict[str, str | None] = {}+ for endpoint in endpoints:+ config = UNLEASH_ENDPOINTS.get(endpoint)+ if config is None:+ results[endpoint] = None+ continue+ params = {"limit": 1} if config.paginated else None+ try:+ response = session.get(f"{base_url}{config.path}", params=params, timeout=15)+ except requests.exceptions.RequestException:+ results[endpoint] = None+ continue+ if response.status_code == 401:+ results[endpoint] = "Invalid Unleash API token"+ elif response.status_code == 403:+ reason = _error_message(response) or "Your Unleash API token lacks the required permissions"+ if config.requires_admin:+ reason = f"{reason} This table requires a token with the Admin root role."+ results[endpoint] = reason+ else:+ results[endpoint] = None+ return results