: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 flagsmith import source (#71168)
Tom Owersa7c66e90dcb0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 14b5ce087abe..f4d9f73ac9d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -219,6 +219,7 @@ the row lists both.| fireworks_ai | HTTP | requests | ✅ || fleetio | HTTP | requests | ✅ || firehydrant | HTTP | requests | ✅ |+| flagsmith | HTTP | requests | ✅ || flexmail | HTTP | requests | ✅ || float_app | HTTP | requests | ✅ || flowlu | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.pynew file mode 100644index 000000000000..7e602bb76d3d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.py@@ -0,0 +1,123 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organisations": {+ "description": "The Flagsmith organisation(s) the connected API key can administer, including subscription and seat details.",+ "docs_url": "https://docs.flagsmith.com/clients/rest",+ "columns": {+ "id": "Unique identifier for the organisation.",+ "uuid": "Stable UUID for the organisation.",+ "name": "Display name of the organisation.",+ "created_date": "When the organisation was created.",+ "num_seats": "Number of member seats in use.",+ "subscription": "Subscription plan details for the organisation.",+ "persist_trait_data": "Whether identity trait data is persisted for this organisation.",+ },+ },+ "projects": {+ "description": "Projects in the organisation. A project groups feature flags and segments shared across its environments.",+ "docs_url": "https://docs.flagsmith.com/basic-features",+ "columns": {+ "id": "Unique identifier for the project.",+ "uuid": "Stable UUID for the project.",+ "name": "Display name of the project.",+ "organisation": "ID of the organisation the project belongs to.",+ "hide_disabled_flags": "Whether disabled flags are hidden from SDK responses.",+ "use_edge_identities": "Whether the project stores identities in the Flagsmith Edge platform.",+ "stale_flags_limit_days": "Days without changes before a flag is considered stale.",+ },+ },+ "environments": {+ "description": "Environments within each project (for example development, staging, production). Feature values are set per environment.",+ "docs_url": "https://docs.flagsmith.com/basic-features",+ "columns": {+ "id": "Unique identifier for the environment.",+ "uuid": "Stable UUID for the environment.",+ "name": "Display name of the environment.",+ "api_key": "Client-side SDK key that identifies the environment.",+ "project": "ID of the project the environment belongs to.",+ "use_v2_feature_versioning": "Whether the environment uses versioned feature states.",+ "_project_id": "ID of the parent project this row was fetched for (added by PostHog).",+ },+ },+ "features": {+ "description": "Feature flags and remote config entries defined per project, including default values, owners, tags, and multivariate options.",+ "docs_url": "https://docs.flagsmith.com/basic-features/managing-features",+ "columns": {+ "id": "Unique identifier for the feature.",+ "uuid": "Stable UUID for the feature.",+ "name": "Feature name used by SDKs to evaluate the flag.",+ "type": "Feature type (STANDARD or MULTIVARIATE).",+ "default_enabled": "Whether the feature defaults to enabled in new environments.",+ "initial_value": "Default remote-config value for the feature.",+ "created_date": "When the feature was created.",+ "is_archived": "Whether the feature has been archived.",+ "multivariate_options": "Weighted value options for multivariate features.",+ "project": "ID of the project the feature belongs to.",+ "_project_id": "ID of the parent project this row was fetched for (added by PostHog).",+ },+ },+ "feature_states": {+ "description": "The current state of every feature per environment: enabled/disabled plus the effective value, including segment overrides.",+ "docs_url": "https://docs.flagsmith.com/basic-features/managing-features",+ "columns": {+ "id": "Unique identifier for the feature state.",+ "uuid": "Stable UUID for the feature state.",+ "enabled": "Whether the feature is enabled in this environment.",+ "feature_state_value": "The effective value served for the feature in this environment.",+ "feature": "ID of the feature this state belongs to.",+ "environment": "ID of the environment this state applies to.",+ "feature_segment": "Segment override this state belongs to, if any.",+ "created_at": "When the feature state was created.",+ "updated_at": "When the feature state was last changed.",+ "live_from": "When this feature state went (or goes) live.",+ "_environment_api_key": "API key of the parent environment this row was fetched for (added by PostHog).",+ },+ },+ "segments": {+ "description": "User segments per project — rule-based groups of identities used to target feature overrides.",+ "docs_url": "https://docs.flagsmith.com/basic-features/segments",+ "columns": {+ "id": "Unique identifier for the segment.",+ "uuid": "Stable UUID for the segment.",+ "name": "Display name of the segment.",+ "description": "Human-readable description of the segment.",+ "rules": "Nested trait-matching rules that define segment membership.",+ "project": "ID of the project the segment belongs to.",+ "feature": "For feature-specific segments, the feature the segment targets.",+ "created_at": "When the segment was created.",+ "_project_id": "ID of the parent project this row was fetched for (added by PostHog).",+ },+ },+ "audit_logs": {+ "description": "Append-only audit history of changes across the organisation: who changed what, when. Retention on Flagsmith SaaS depends on your plan.",+ "docs_url": "https://docs.flagsmith.com/system-administration/audit-logs",+ "columns": {+ "id": "Unique identifier for the audit log record.",+ "created_date": "When the change happened.",+ "log": "Human-readable description of the change.",+ "author": "The user who made the change.",+ "environment": "Environment the change applies to, if any.",+ "project": "Project the change applies to, if any.",+ "related_object_id": "ID of the object the change relates to.",+ "related_object_type": "Type of the object the change relates to (for example FEATURE or SEGMENT).",+ "is_system_event": "Whether the change was made by the system rather than a user.",+ "_organisation_id": "ID of the parent organisation this row was fetched for (added by PostHog).",+ },+ },+ "users": {+ "description": "Members of the organisation and their basic profile details.",+ "docs_url": "https://docs.flagsmith.com/system-administration/rbac",+ "columns": {+ "id": "Unique identifier for the user.",+ "uuid": "Stable UUID for the user.",+ "email": "Email address of the user.",+ "first_name": "First name of the user.",+ "last_name": "Last name of the user.",+ "last_login": "When the user last logged in.",+ "_organisation_id": "ID of the parent organisation this row was fetched for (added by PostHog).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.pynew file mode 100644index 000000000000..294f76f24cae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py@@ -0,0 +1,520 @@+import json+import threading+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt+from urllib3.util.retry import Retry++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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.settings import (+ FLAGSMITH_ENDPOINTS,+ FlagsmithEndpointConfig,+ ParentResource,+)++DEFAULT_BASE_URL = "https://api.flagsmith.com"++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+MAX_RETRY_WAIT_SECONDS = 60++# Cap on the total pages walked in one sync invocation, shared across parent enumeration and+# every fan-out child listing. `next` links come from a user-supplied (self-hosted) host, so a+# hostile or misconfigured server can return a non-empty cyclic `next` forever — and in a fan-out+# multiply that across thousands of parents. A single shared budget makes the whole sync+# self-terminate instead of issuing credentialed requests until the activity is cancelled.+# Generous enough not to truncate real data.+MAX_PAGES_PER_SYNC = 10_000++# Cap on how many fan-out parents (organisation ids, project ids, or environment api_keys) a single+# sync enumerates and holds in memory before child processing begins. Even within the page budget a+# hostile host could return enough parents to balloon this list and exhaust a warehouse worker.+# Generous enough to cover any real org.+MAX_FANOUT_PARENTS = 50_000++# Cap on the length of a single fan-out parent key. Real ids and api_keys are short identifiers, so+# the count cap alone doesn't bound retained bytes — a hostile host could return an arbitrarily long+# id/api_key (up to the response byte cap) that balloons the retained list and gets interpolated into+# child request URLs. Keys longer than this are skipped rather than trusted.+MAX_FANOUT_KEY_LENGTH = 256+++class _PageBudget:+ """Mutable page allowance drawn down across a whole sync (all parents and child listings)."""++ def __init__(self, limit: int) -> None:+ self.remaining = limit++ def take(self) -> bool:+ """Consume one page; return False once the shared budget is exhausted."""+ if self.remaining <= 0:+ return False+ self.remaining -= 1+ return True+++# base_url can be a customer-controlled self-hosted host, so response bodies are streamed and+# read under a byte cap and a total-transfer deadline: an arbitrarily large (or endlessly+# dripped) 200 body must fail the sync instead of exhausting worker memory or holding a worker.+# The cap counts decoded bytes, so a gzip bomb can't slip past it.+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+_READ_CHUNK_BYTES = 1024 * 1024+# The per-read socket timeout only bounds the gap between bytes, so a host that trickles one byte+# just before each read timeout could keep a worker busy until the activity's timeout. This+# absolute wall-clock deadline (enforced in `_read_bounded`) caps how long a single body read may+# take end to end, even while a read is blocked mid-chunk.+MAX_RESPONSE_SECONDS = 600+# Bytes pulled from an error body for a diagnostic message — error bodies are never needed in full.+_ERROR_SNIPPET_BYTES = 2048+++class FlagsmithRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None):+ super().__init__(message)+ self.retry_after = retry_after+++class FlagsmithResponseTooLargeError(Exception):+ pass+++class FlagsmithResponseTimeoutError(Exception):+ pass+++def _read_bounded(+ response: requests.Response, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS+) -> bytes:+ """Read a streamed response body under both a byte cap and a total-transfer deadline.++ The read runs on a worker thread bounded by ``join(timeout=max_seconds)``, so the deadline is+ enforced as absolute wall-clock time even while a read is blocked: ``iter_content`` fills a+ whole chunk before it yields, so a host that trickles bytes just under the per-read socket+ timeout could otherwise never let an in-loop deadline check run. On timeout we close the+ response to unblock the pending socket read and let the daemon thread unwind.+ """+ box: dict[str, Any] = {}++ def _reader() -> None:+ try:+ total = 0+ chunks: list[bytes] = []+ for chunk in response.iter_content(chunk_size=_READ_CHUNK_BYTES):+ total += len(chunk)+ if total > max_bytes:+ box["error"] = FlagsmithResponseTooLargeError(+ f"Flagsmith API response exceeded the size limit ({max_bytes} bytes)"+ )+ return+ chunks.append(chunk)+ box["data"] = b"".join(chunks)+ except Exception as exc: # surfaced on the calling thread below+ box["error"] = exc++ thread = threading.Thread(target=_reader, name="flagsmith-read-bounded", daemon=True)+ thread.start()+ thread.join(timeout=max_seconds)+ if thread.is_alive():+ # Close the socket so the blocked read raises and the daemon thread can exit.+ response.close()+ raise FlagsmithResponseTimeoutError(+ f"Flagsmith API response exceeded the download time limit ({max_seconds:g}s)"+ )+ if "error" in box:+ raise box["error"]+ return box.get("data", b"")+++def _error_snippet(response: requests.Response) -> str:+ try:+ chunk = next(response.iter_content(chunk_size=_ERROR_SNIPPET_BYTES), b"")+ return chunk[:_ERROR_SNIPPET_BYTES].decode("utf-8", errors="replace")+ except Exception:+ return ""+++class FlagsmithResumeConfig:+ # Full URL of the next page to fetch ("" once a resource is exhausted).+ next_url: str = ""+ # For fan-out endpoints, the parent (organisation id, project id, or environment+ # api_key) currently being paginated ("" for top-level endpoints or before the first+ # parent starts).+ parent_key: str = ""+++def normalize_base_url(base_url: str | None) -> str:+ """Normalize the (optional) instance URL and reject anything that isn't plain http(s).++ Defaults to Flagsmith SaaS; self-hosted deployments pass their own API URL.++ Rejects URLs where the host ``urlparse`` reports could diverge from the host the HTTP+ client actually dials, which would let a caller slip past the downstream SSRF allowlist+ (which validates the parsed hostname): backslashes (treated as path separators by some+ clients but not by ``urlparse``), userinfo (``user@host`` hides the real host after an+ ``@``), and query/fragment noise that has no place in a base URL.+ """+ host = (base_url or "").strip() or DEFAULT_BASE_URL+ if "://" not in host:+ host = f"https://{host}"+ # Catch raw and percent-encoded backslashes before urlparse silently keeps them.+ if "\\" in host or "%5c" in host.lower():+ raise ValueError(f"Invalid Flagsmith base URL: {base_url}")+ host = host.rstrip("/")+ parsed = urlparse(host)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(f"Invalid Flagsmith base URL: {base_url}")+ if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:+ raise ValueError(f"Invalid Flagsmith base URL: {base_url}")+ if parsed.query or parsed.fragment or parsed.params:+ raise ValueError(f"Invalid Flagsmith base URL: {base_url}")+ return host+++def hostname_of(base_url: str | None) -> str:+ return urlparse(normalize_base_url(base_url)).hostname or ""+++def scheme_of(base_url: str | None) -> str:+ return urlparse(normalize_base_url(base_url)).scheme+++def _api_base(base: str) -> str:+ return f"{base}/api/v1"+++def _headers(api_key: str) -> dict[str, str]:+ # Organisation API keys authenticate with an "Api-Key" prefix+ # (see https://docs.flagsmith.com/clients/rest#private-admin-api-endpoints).+ return {+ "Authorization": f"Api-Key {api_key}",+ "Accept": "application/json",+ }+++def _initial_url(base: str, path: str, params: dict[str, Any]) -> str:+ url = f"{_api_base(base)}{path}"+ if params:+ sep = "&" if "?" in path else "?"+ url = f"{url}{sep}{urlencode(params)}"+ return url+++def _pinned_next_url(base: str, next_link: Any) -> str | None:+ """Rebuild a DRF ``next`` link onto the configured base URL.++ The API returns absolute URLs derived from the request host, which a misconfigured+ self-hosted proxy (or a hostile server) could point elsewhere. Keeping only the+ path + query pins pagination to the host that credential validation approved.+ """+ if not next_link or not isinstance(next_link, str):+ return None+ parsed = urlparse(next_link)+ query = f"?{parsed.query}" if parsed.query else ""+ return f"{base}{parsed.path}{query}"+++def _extract_rows(base: str, data: Any) -> tuple[list[dict[str, Any]], str | None]:+ """Rows + next-page URL from a response body: either a DRF pagination envelope+ (``{count, next, previous, results}``) or a plain JSON array (projects, users)."""+ if isinstance(data, list):+ return [row for row in data if isinstance(row, dict)], None+ if isinstance(data, dict):+ rows = [row for row in data.get("results") or [] if isinstance(row, dict)]+ return rows, _pinned_next_url(base, data.get("next"))+ return [], None+++def _wait_strategy(retry_state: Any) -> float:+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, FlagsmithRetryableError) and exc.retry_after is not None:+ return min(exc.retry_after, MAX_RETRY_WAIT_SECONDS)+ return min(2.0**retry_state.attempt_number, MAX_RETRY_WAIT_SECONDS)+++@retry(+ retry=retry_if_exception_type((FlagsmithRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=_wait_strategy,+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ # stream=True keeps the body off the wire until it's read through `_read_bounded` under a byte+ # cap and a transfer deadline — a customer-controlled host must not exhaust worker memory or+ # hold a worker with an endless body.+ with session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, stream=True) as response:+ if response.status_code == 429:+ retry_after_header = response.headers.get("Retry-After")+ try:+ retry_after = float(retry_after_header) if retry_after_header else None+ except ValueError:+ # A non-numeric value (e.g. an HTTP-date) falls back to exponential backoff.+ retry_after = None+ logger.warning(f"Flagsmith rate limited (429), retrying. retry_after={retry_after_header}, url={url}")+ raise FlagsmithRetryableError(f"Flagsmith rate limited: url={url}", retry_after=retry_after)++ if response.status_code >= 500:+ raise FlagsmithRetryableError(f"Flagsmith server error: status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(+ f"Flagsmith API error: status={response.status_code}, body={_error_snippet(response)}, url={url}"+ )+ response.raise_for_status()++ return json.loads(_read_bounded(response))+++def validate_credentials(api_key: str, base_url: str | None, path: str = "/organisations/") -> int | None:+ """Probe an endpoint and return the HTTP status code (or None on transport failure)."""+ try:+ # base_url is user-supplied (self-hosted), so pin redirects off: validation and the+ # outbound request must stay on the same target (SSRF defense-in-depth). capture=False+ # keeps the probe's customer-content response body out of HTTP sample storage.+ # retry=Retry(total=0): the probe runs inline on an API worker, so it takes a single+ # attempt — a hostile base_url must not be able to hold the worker via adapter retries+ # that honour an unbounded server-controlled Retry-After.+ session = make_tracked_session(+ redact_values=(api_key,), allow_redirects=False, capture=False, retry=Retry(total=0)+ )+ # stream=True and a context manager so we read only the status line/headers and never+ # download the body: a hostile base_url could otherwise trickle an endless body and hold+ # this inline API worker open well past the read timeout (which only bounds byte gaps).+ with session.get(+ f"{_api_base(normalize_base_url(base_url))}{path}", headers=_headers(api_key), timeout=10, stream=True+ ) as response:+ return response.status_code+ except Exception:+ return None+++def _iter_pages(+ session: requests.Session,+ base: str,+ start_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ budget: _PageBudget,+) -> Iterator[list[dict[str, Any]]]:+ """Walk a listing (paginated or plain-array) without touching resume state — used to+ enumerate fan-out parents, which must be re-listed from scratch on every run."""+ url: str | None = start_url+ while url:+ if not budget.take():+ logger.warning(f"Flagsmith: sync page budget ({MAX_PAGES_PER_SYNC}) exhausted at {start_url}, truncating")+ return+ data = _fetch_page(session, url, headers, logger)+ rows, url = _extract_rows(base, data)+ if rows:+ yield rows+++def _extend_capped(+ keys: list[str], listing: Iterator[list[dict[str, Any]]], field: str, logger: FilteringBoundLogger+) -> bool:+ """Append ``row[field]`` from each row of a parent listing into ``keys``, stopping once the+ retained list hits MAX_FANOUT_PARENTS so a hostile host can't balloon it and exhaust worker+ memory. Keys longer than MAX_FANOUT_KEY_LENGTH are skipped so an oversized id/api_key can't+ balloon retained bytes or poison a child request URL. Returns True if the count cap was reached+ (the caller should stop enumerating)."""+ for rows in listing:+ for row in rows:+ key = str(row[field])+ if len(key) > MAX_FANOUT_KEY_LENGTH:+ logger.warning(f"Flagsmith: skipping fan-out parent with oversized {field} ({len(key)} chars)")+ continue+ keys.append(key)+ if len(keys) >= MAX_FANOUT_PARENTS:+ logger.warning(f"Flagsmith: fan-out parent cap ({MAX_FANOUT_PARENTS}) reached, truncating enumeration")+ return True+ return False+++def _fetch_parent_keys(+ session: requests.Session,+ base: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ parent: ParentResource,+ budget: _PageBudget,+) -> list[str]:+ if parent == "organisation":+ listing = _iter_pages(session, base, _initial_url(base, "/organisations/", {}), headers, logger, budget)+ org_ids: list[str] = []+ _extend_capped(org_ids, listing, "id", logger)+ return org_ids++ project_listing = _iter_pages(session, base, _initial_url(base, "/projects/", {}), headers, logger, budget)+ project_ids: list[str] = []+ _extend_capped(project_ids, project_listing, "id", logger)+ if parent == "project":+ return project_ids++ # Environments are addressed by their (non-secret, client-side) api_key and listed+ # per project; keep API order so the resume bookmark resolves deterministically.+ keys: list[str] = []+ for project_id in project_ids:+ env_listing = _iter_pages(+ session, base, _initial_url(base, f"/environments/?project={project_id}", {}), headers, logger, budget+ )+ if _extend_capped(keys, env_listing, "api_key", logger):+ break+ return keys+++def _paginate_resource(+ session: requests.Session,+ base: str,+ start_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlagsmithResumeConfig],+ parent_key: str,+ parent_field: str | None,+ budget: _PageBudget,+) -> Iterator[list[dict[str, Any]]]:+ url: str | None = start_url+ while url:+ if not budget.take():+ logger.warning(f"Flagsmith: sync page budget ({MAX_PAGES_PER_SYNC}) exhausted at {start_url}, truncating")+ # Terminal resume state so a resume advances past this parent instead of re-entering+ # the same (possibly cyclic) chain and re-spending the budget on it.+ resumable_source_manager.save_state(FlagsmithResumeConfig(next_url="", parent_key=parent_key))+ return+ data = _fetch_page(session, url, headers, logger)+ rows, next_url = _extract_rows(base, data)++ if parent_field:+ for row in rows:+ row[parent_field] = parent_key++ if rows:+ yield rows++ # Save state AFTER yielding so a heartbeat-timeout crash re-fetches from the next+ # page rather than re-emitting the page we just yielded (merge dedupes regardless).+ resumable_source_manager.save_state(FlagsmithResumeConfig(next_url=next_url or "", parent_key=parent_key))+ url = next_url+++def _get_fan_out_rows(+ session: requests.Session,+ base: str,+ config: FlagsmithEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlagsmithResumeConfig],+ resume: FlagsmithResumeConfig | None,+ budget: _PageBudget,+) -> Iterator[list[dict[str, Any]]]:+ assert config.parent is not None+ parent_keys = _fetch_parent_keys(session, base, headers, logger, config.parent, budget)+ if not parent_keys:+ logger.warning(f"Flagsmith: no {config.parent}s found, nothing to sync for endpoint={config.name}")+ return++ start_idx = 0+ resume_url: str | None = None+ if resume is not None and resume.parent_key and resume.parent_key in parent_keys:+ idx = parent_keys.index(resume.parent_key)+ if resume.next_url:+ # Mid-parent: pick up at the saved page within that parent. Re-pin onto the current base+ # so a stale URL from a since-retargeted source can't send the current API key to the+ # previously configured host.+ start_idx = idx+ resume_url = _pinned_next_url(base, resume.next_url)+ else:+ # The saved parent finished (empty next_url marker); start at the next one.+ start_idx = idx + 1++ for i in range(start_idx, len(parent_keys)):+ parent_key = parent_keys[i]+ if i == start_idx and resume_url:+ start_url = resume_url+ else:+ start_url = _initial_url(base, config.path.format(parent=parent_key), config.params)+ yield from _paginate_resource(+ session, base, start_url, headers, logger, resumable_source_manager, parent_key, config.parent_field, budget+ )+++def get_rows(+ api_key: str,+ base_url: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlagsmithResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = FLAGSMITH_ENDPOINTS[endpoint]+ base = normalize_base_url(base_url)+ headers = _headers(api_key)+ # capture=False: Flagsmith bodies carry customer-authored content the name-based scrubbers+ # can't recognise — feature values, segment rules, audit records, and member PII (names/emails).+ # retry=Retry(total=0): _fetch_page owns the retry budget via tenacity with a bounded wait+ # (_wait_strategy caps at MAX_RETRY_WAIT_SECONDS); leaving the adapter's DEFAULT_RETRY on would+ # let a hostile base_url stall a sync worker with an unbounded, server-controlled Retry-After.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False, retry=Retry(total=0))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ # One budget for the whole invocation so a fan-out can't multiply the per-listing cap across+ # parents into unbounded credentialed requests.+ budget = _PageBudget(MAX_PAGES_PER_SYNC)++ if config.parent is not None:+ yield from _get_fan_out_rows(session, base, config, headers, logger, resumable_source_manager, resume, budget)+ return++ if resume is not None and resume.next_url:+ logger.debug(f"Flagsmith: resuming endpoint={endpoint} from saved page")+ # Re-pin onto the current base: a stale resume URL from a since-retargeted source must not+ # send the current API key to the previously configured host.+ start_url = _pinned_next_url(base, resume.next_url) or _initial_url(base, config.path, config.params)+ else:+ start_url = _initial_url(base, config.path, config.params)++ yield from _paginate_resource(+ session,+ base,+ start_url,+ headers,+ logger,+ resumable_source_manager,+ parent_key="",+ parent_field=None,+ budget=budget,+ )+++def flagsmith_source(+ api_key: str,+ base_url: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlagsmithResumeConfig],+) -> SourceResponse:+ config = FLAGSMITH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ base_url=base_url,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=list(config.primary_keys),+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.pynew file mode 100644index 000000000000..57e454f77bbc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py@@ -0,0 +1,109 @@+from dataclasses import dataclass, field+from typing import Any, Literal++from products.warehouse_sources.backend.types import IncrementalField++# Which root listing a fan-out endpoint enumerates its parents from. Environments are+# discovered project-by-project, so their prerequisite is the projects listing.+ParentResource = Literal["organisation", "project", "environment"]+++@dataclass+class FlagsmithEndpointConfig:+ name: str+ # Path under ``/api/v1``. A ``{parent}`` placeholder marks a fan-out endpoint queried+ # once per parent resource (organisation id, project id, or environment api_key). The+ # path may carry its own query string (e.g. the environments listing filter).+ path: str+ primary_keys: list[str]+ parent: ParentResource | None = None+ # Row field the parent identifier is injected into, so a single table stays meaningful+ # (and uniquely keyed) across parents whose rows don't carry the parent id themselves.+ parent_field: str | None = None+ # Static query params for the initial request. Only endpoints whose OpenAPI spec+ # documents ``page_size`` get one — DRF silently ignores it elsewhere, so don't imply it.+ params: dict[str, Any] = field(default_factory=dict)+ # A STABLE datetime field to partition by — never one that mutates on update.+ partition_key: str | None = None+ # Flagsmith's Admin API exposes no server-side updated-since/created-after filter on any+ # of these resources (verified against the live OpenAPI spec), so every endpoint is+ # full-refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {+ # The organisation(s) the API key can administer. Organisation API keys are org-scoped,+ # so this is normally a single row.+ "organisations": FlagsmithEndpointConfig(+ name="organisations",+ path="/organisations/",+ primary_keys=["id"],+ ),+ # All projects visible to the key. Returns a plain JSON array (no pagination envelope).+ "projects": FlagsmithEndpointConfig(+ name="projects",+ path="/projects/",+ primary_keys=["id"],+ ),+ "environments": FlagsmithEndpointConfig(+ name="environments",+ path="/environments/?project={parent}",+ primary_keys=["id"],+ parent="project",+ parent_field="_project_id",+ ),+ "features": FlagsmithEndpointConfig(+ name="features",+ path="/projects/{parent}/features/",+ primary_keys=["id"],+ parent="project",+ parent_field="_project_id",+ # An explicit stable sort prevents page-boundary skips/duplicates while paginating.+ params={"page_size": 100, "sort_field": "created_date", "sort_direction": "ASC"},+ partition_key="created_date",+ ),+ # Current flag values per environment (environment defaults and segment overrides).+ "feature_states": FlagsmithEndpointConfig(+ name="feature_states",+ path="/environments/{parent}/featurestates/",+ primary_keys=["id"],+ parent="environment",+ parent_field="_environment_api_key",+ partition_key="created_at",+ ),+ "segments": FlagsmithEndpointConfig(+ name="segments",+ path="/projects/{parent}/segments/",+ primary_keys=["id"],+ parent="project",+ parent_field="_project_id",+ params={"page_size": 100},+ partition_key="created_at",+ ),+ # Append-only change history for the organisation. Retention on Flagsmith SaaS is+ # plan-gated, so the table reflects the currently retained window.+ "audit_logs": FlagsmithEndpointConfig(+ name="audit_logs",+ path="/organisations/{parent}/audit/",+ primary_keys=["id"],+ parent="organisation",+ parent_field="_organisation_id",+ params={"page_size": 100},+ partition_key="created_date",+ ),+ # Organisation members. Returns a plain JSON array. A user can belong to more than one+ # organisation, so the composite key includes the injected ``_organisation_id``.+ "users": FlagsmithEndpointConfig(+ name="users",+ path="/organisations/{parent}/users/",+ primary_keys=["id", "_organisation_id"],+ parent="organisation",+ parent_field="_organisation_id",+ ),+}++ENDPOINTS = tuple(FLAGSMITH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FLAGSMITH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.pyindex fc7e9409443e..e842bb6eae02 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py@@ -1,30 +1,201 @@-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 posthog.cloud_utils import is_cloud++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.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith import (+ FlagsmithResumeConfig,+ flagsmith_source,+ hostname_of,+ scheme_of,+ validate_credentials as validate_flagsmith_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.settings import (+ ENDPOINTS,+ FLAGSMITH_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlagsmithSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+# Fan-out endpoints can't be probed without a parent id, so scope checks probe the root+# listing their parent enumeration starts from.+_PARENT_PROBE_PATHS = {+ "organisation": "/organisations/",+ "project": "/projects/",+ "environment": "/projects/",+}+@SourceRegistry.register-class FlagsmithSource(SimpleSource[FlagsmithSourceConfig]):+class FlagsmithSource(ResumableSource[FlagsmithSourceConfig, FlagsmithResumeConfig], ValidateDatabaseHostMixin):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FLAGSMITH+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API key is sent, so retargeting it must re-require the key.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FLAGSMITH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,+ keywords=["feature flags", "remote config"],label="Flagsmith",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Flagsmith organisation API key to pull your projects, environments, feature flags, flag states, segments, and audit log into the PostHog Data warehouse.++Create an organisation API key under **Organisation Settings > API Keys** in your Flagsmith dashboard. Note that organisation API keys grant admin access to every project in the organisation, so store them carefully.++Leave the API URL blank for Flagsmith SaaS, or set it to your API host (for example `https://flagsmith.example.com`) for a self-hosted deployment.""",iconPath="/static/services/flagsmith.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/flagsmith",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Organisation API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API URL (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://api.flagsmith.com",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Flagsmith API key is invalid or has been revoked. Create a new organisation API key and reconnect.",+ "403 Client Error": "Your Flagsmith API key does not have permission for this resource. Please check the key and try again.",+ }++ def get_schemas(+ self,+ config: FlagsmithSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Flagsmith's Admin API exposes no server-side timestamp filter on these resources,+ # so every endpoint is full-refresh only (no incremental/append support).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=FLAGSMITH_ENDPOINTS[endpoint].primary_keys,+ )+ 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_base_url(self, base_url: str | None, team_id: int) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(base_url), team_id)+ scheme = scheme_of(base_url)+ except ValueError:+ return False, "Invalid Flagsmith API URL"+ if not host_valid:+ return False, host_error+ # On Cloud the required API key would otherwise be sent in cleartext to a customer-supplied+ # http:// host. Self-hosted deployments (not is_cloud) may still use http on their own network.+ if is_cloud() and scheme != "https":+ return False, "Flagsmith API URL must use https"+ return True, None++ def validate_credentials(+ self, config: FlagsmithSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ base_url_valid, base_url_error = self._validate_base_url(config.base_url, team_id)+ if not base_url_valid:+ return False, base_url_error++ probe_path = "/organisations/"+ if schema_name is not None:+ endpoint = FLAGSMITH_ENDPOINTS.get(schema_name)+ if endpoint is not None:+ probe_path = _PARENT_PROBE_PATHS[endpoint.parent] if endpoint.parent else endpoint.path++ status = validate_flagsmith_credentials(config.api_key, config.base_url, probe_path)++ if status is None:+ return False, "Could not reach Flagsmith. Please check the API URL and try again."+ if status == 401:+ return False, "Invalid Flagsmith API key"+ # A valid key may legitimately lack scope for a specific endpoint. Accept 403 at+ # source-create (schema_name is None); only reject it for a specific schema check.+ if status == 403:+ if schema_name is None:+ return True, None+ return False, f"Your API key does not have permission to read '{schema_name}'"+ if status >= 400:+ return False, f"Flagsmith returned an unexpected status ({status})"+ return True, None++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FlagsmithResumeConfig]:+ return ResumableSourceManager[FlagsmithResumeConfig](inputs, FlagsmithResumeConfig)++ def source_for_pipeline(+ self,+ config: FlagsmithSourceConfig,+ resumable_source_manager: ResumableSourceManager[FlagsmithResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ base_url_valid, base_url_error = self._validate_base_url(config.base_url, inputs.team_id)+ if not base_url_valid:+ raise ValueError(base_url_error or "Invalid Flagsmith API URL")++ return flagsmith_source(+ api_key=config.api_key,+ base_url=config.base_url,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.pynew file mode 100644index 000000000000..f00716e5c0e6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.py@@ -0,0 +1,469 @@+import json+import threading+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith import (+ DEFAULT_BASE_URL,+ FlagsmithResponseTimeoutError,+ FlagsmithResponseTooLargeError,+ FlagsmithResumeConfig,+ _initial_url,+ _pinned_next_url,+ _read_bounded,+ flagsmith_source,+ get_rows,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.settings import (+ ENDPOINTS,+ FLAGSMITH_ENDPOINTS,+)++API_BASE = f"{DEFAULT_BASE_URL}/api/v1"+SESSION_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith.make_tracked_session"+)+BUDGET_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith.MAX_PAGES_PER_SYNC"+PARENTS_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith.MAX_FANOUT_PARENTS"+KEY_LENGTH_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith.MAX_FANOUT_KEY_LENGTH"+)+++def _make_manager(resume_state: FlagsmithResumeConfig | 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 _page(results: list[dict[str, Any]], next_url: str | None = None) -> dict[str, Any]:+ return {"count": len(results), "next": next_url, "previous": None, "results": results}+++def _resp(data: Any, status_code: int = 200) -> mock.MagicMock:+ # `_fetch_page` streams the body (`with session.get(..., stream=True) as response`) and reads+ # it via `_read_bounded`/`iter_content`, so the mock must act as its own context manager and+ # expose the JSON-encoded body through `iter_content`.+ resp = mock.MagicMock()+ body = json.dumps(data).encode()+ resp.iter_content.side_effect = lambda *args, **kwargs: iter([body])+ resp.json.return_value = data+ resp.status_code = status_code+ resp.ok = 200 <= status_code < 300+ resp.__enter__.return_value = resp+ resp.__exit__.return_value = False+ return resp+++def _probe_resp(status_code: int = 200) -> mock.MagicMock:+ # validate_credentials reads the status via `with session.get(..., stream=True) as response`.+ resp = mock.MagicMock(status_code=status_code)+ resp.__enter__.return_value = resp+ resp.__exit__.return_value = False+ return resp+++class TestUrlHelpers:+ @pytest.mark.parametrize(+ "base_url, expected",+ [+ (None, DEFAULT_BASE_URL),+ ("", DEFAULT_BASE_URL),+ (" ", DEFAULT_BASE_URL),+ ("https://flagsmith.example.com", "https://flagsmith.example.com"),+ ("https://flagsmith.example.com/", "https://flagsmith.example.com"),+ ("flagsmith.example.com", "https://flagsmith.example.com"),+ ("http://flagsmith.internal:8000", "http://flagsmith.internal:8000"),+ ],+ )+ def test_normalize_base_url_valid(self, base_url, expected):+ assert normalize_base_url(base_url) == expected++ @pytest.mark.parametrize(+ "base_url",+ [+ "ftp://flagsmith.example.com",+ "https://[email protected]",+ "https://user:[email protected]",+ "https://169.254.169.254\\@flagsmith.example.com",+ "https://flagsmith.example.com%[email protected]",+ "https://flagsmith.example.com?next=x",+ "https://flagsmith.example.com#frag",+ ],+ )+ def test_normalize_base_url_rejects_unsafe(self, base_url):+ with pytest.raises(ValueError):+ normalize_base_url(base_url)++ @pytest.mark.parametrize(+ "next_link, expected",+ [+ (f"{API_BASE}/organisations/?page=2", f"{API_BASE}/organisations/?page=2"),+ # A next link pointing at another host is rebuilt onto the configured base.+ ("https://evil.example.com/api/v1/organisations/?page=2", f"{API_BASE}/organisations/?page=2"),+ ("http://proxy.internal/api/v1/audit/?page=3&page_size=100", f"{API_BASE}/audit/?page=3&page_size=100"),+ (None, None),+ ("", None),+ ],+ )+ def test_pinned_next_url(self, next_link, expected):+ assert _pinned_next_url(DEFAULT_BASE_URL, next_link) == expected++ def test_initial_url_appends_params_to_path_with_query(self):+ url = _initial_url(DEFAULT_BASE_URL, "/environments/?project=1", {"page_size": 100})+ assert url == f"{API_BASE}/environments/?project=1&page_size=100"+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])+ @mock.patch(SESSION_PATH)+ def test_returns_status_code(self, mock_session, status_code):+ mock_session.return_value.get.return_value = _probe_resp(status_code)+ assert validate_credentials("key", None) == status_code++ @mock.patch(SESSION_PATH)+ def test_uses_api_key_prefix(self, mock_session):+ mock_session.return_value.get.return_value = _probe_resp(200)+ validate_credentials("org-key", None)+ call = mock_session.return_value.get.call_args+ assert call.kwargs["headers"]["Authorization"] == "Api-Key org-key"+ assert call.args[0] == f"{API_BASE}/organisations/"++ @mock.patch(SESSION_PATH)+ def test_uses_custom_base_url(self, mock_session):+ mock_session.return_value.get.return_value = _probe_resp(200)+ validate_credentials("org-key", "https://flagsmith.example.com", "/projects/")+ assert mock_session.return_value.get.call_args.args[0] == "https://flagsmith.example.com/api/v1/projects/"++ @mock.patch(SESSION_PATH)+ def test_streams_probe_without_downloading_body(self, mock_session):+ # A hostile base_url must not be able to occupy the API worker with an endless body: the+ # probe streams and returns the status without consuming the body.+ resp = _probe_resp(200)+ mock_session.return_value.get.return_value = resp+ validate_credentials("key", None)+ assert mock_session.return_value.get.call_args.kwargs["stream"] is True+ resp.iter_content.assert_not_called()++ @mock.patch(SESSION_PATH)+ def test_returns_none_on_exception(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", None) is None+++class TestGetRowsTopLevel:+ @mock.patch(SESSION_PATH)+ def test_paginates_via_drf_next(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp(_page([{"id": 1}, {"id": 2}], f"{API_BASE}/organisations/?page=2")),+ _resp(_page([{"id": 3}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", None, "organisations", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == [1, 2, 3]+ # State saved after every page (final save records the empty next_url marker).+ saved_urls = [call.args[0].next_url for call in manager.save_state.call_args_list]+ assert saved_urls == [f"{API_BASE}/organisations/?page=2", ""]++ @mock.patch(SESSION_PATH)+ def test_projects_plain_array_yields_rows(self, mock_session):+ mock_session.return_value.get.return_value = _resp([{"id": 10}, {"id": 11}])++ batches = list(get_rows("key", None, "projects", mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == [10, 11]+ assert mock_session.return_value.get.call_args.args[0] == f"{API_BASE}/projects/"++ @mock.patch(SESSION_PATH)+ def test_resumes_from_saved_state(self, mock_session):+ mock_session.return_value.get.return_value = _resp(_page([{"id": 9}], None))++ resume_url = f"{API_BASE}/organisations/?page=5"+ manager = _make_manager(FlagsmithResumeConfig(next_url=resume_url))++ list(get_rows("key", None, "organisations", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url++ @mock.patch(SESSION_PATH)+ def test_resume_url_repinned_to_configured_base(self, mock_session):+ # A resume URL persisted before the source was retargeted must be re-pinned onto the current+ # base, or the current API key would be replayed to the previously configured (attacker) host.+ mock_session.return_value.get.return_value = _resp(_page([{"id": 9}], None))+ stale = "https://old-host.example.com/api/v1/organisations/?page=5"+ manager = _make_manager(FlagsmithResumeConfig(next_url=stale))++ list(get_rows("key", None, "organisations", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_args_list[0].args[0] == f"{API_BASE}/organisations/?page=5"++ @mock.patch(SESSION_PATH)+ def test_empty_response_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _resp(_page([], None))++ assert list(get_rows("key", None, "organisations", mock.MagicMock(), _make_manager())) == []++ @mock.patch(BUDGET_PATH, 5)+ @mock.patch(SESSION_PATH)+ def test_cyclic_next_link_is_capped(self, mock_session):+ # A hostile self-hosted host can return a non-empty `next` forever; pagination must+ # self-terminate at the page budget instead of looping on credentialed requests.+ mock_session.return_value.get.return_value = _resp(_page([{"id": 1}], f"{API_BASE}/organisations/?page=next"))++ manager = _make_manager()+ batches = list(get_rows("key", None, "organisations", mock.MagicMock(), manager))++ assert len(batches) == 5+ # Terminal resume state so a resume advances past the cyclic resource, not back into it.+ assert manager.save_state.call_args_list[-1].args[0].next_url == ""+++class TestGetRowsFanout:+ @mock.patch(SESSION_PATH)+ def test_features_fan_out_per_project(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 1}, {"id": 2}]), # projects (plain array)+ _resp(_page([{"id": 100, "name": "flag-a"}], None)),+ _resp(_page([{"id": 200, "name": "flag-b"}], None)),+ ]++ batches = list(get_rows("key", None, "features", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert rows == [+ {"id": 100, "name": "flag-a", "_project_id": "1"},+ {"id": 200, "name": "flag-b", "_project_id": "2"},+ ]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[0] == f"{API_BASE}/projects/"+ assert urls[1] == f"{API_BASE}/projects/1/features/?page_size=100&sort_field=created_date&sort_direction=ASC"+ assert urls[2] == f"{API_BASE}/projects/2/features/?page_size=100&sort_field=created_date&sort_direction=ASC"++ @mock.patch(SESSION_PATH)+ def test_environments_fan_out_uses_project_query_param(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 7}]),+ _resp(_page([{"id": 70, "api_key": "env-key"}], None)),+ ]++ batches = list(get_rows("key", None, "environments", mock.MagicMock(), _make_manager()))++ assert [row for batch in batches for row in batch] == [{"id": 70, "api_key": "env-key", "_project_id": "7"}]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[1] == f"{API_BASE}/environments/?project=7"++ @mock.patch(SESSION_PATH)+ def test_feature_states_enumerate_environments_via_projects(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 1}]), # projects+ _resp(_page([{"id": 10, "api_key": "env-a"}, {"id": 11, "api_key": "env-b"}], None)), # environments+ _resp(_page([{"id": 1000, "enabled": True}], None)), # featurestates env-a+ _resp(_page([{"id": 2000, "enabled": False}], None)), # featurestates env-b+ ]++ batches = list(get_rows("key", None, "feature_states", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert rows == [+ {"id": 1000, "enabled": True, "_environment_api_key": "env-a"},+ {"id": 2000, "enabled": False, "_environment_api_key": "env-b"},+ ]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[2] == f"{API_BASE}/environments/env-a/featurestates/"+ assert urls[3] == f"{API_BASE}/environments/env-b/featurestates/"++ @mock.patch(SESSION_PATH)+ def test_users_fan_out_injects_organisation_id(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp(_page([{"id": 5}], None)), # organisations+ _resp([{"id": 500, "email": "[email protected]"}]), # users (plain array)+ ]++ batches = list(get_rows("key", None, "users", mock.MagicMock(), _make_manager()))++ assert [row for batch in batches for row in batch] == [+ {"id": 500, "email": "[email protected]", "_organisation_id": "5"}+ ]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[1] == f"{API_BASE}/organisations/5/users/"++ @mock.patch(SESSION_PATH)+ def test_resume_skips_completed_parent(self, mock_session):+ # Project 1 finished last run (empty next_url marker); resume must start at project 2.+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 1}, {"id": 2}]),+ _resp(_page([{"id": 200}], None)),+ ]+ manager = _make_manager(FlagsmithResumeConfig(next_url="", parent_key="1"))++ batches = list(get_rows("key", None, "segments", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == [200]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls == [f"{API_BASE}/projects/", f"{API_BASE}/projects/2/segments/?page_size=100"]++ @mock.patch(SESSION_PATH)+ def test_resume_midparent_uses_saved_url(self, mock_session):+ resume_url = f"{API_BASE}/projects/1/segments/?page=3&page_size=100"+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 1}, {"id": 2}]),+ _resp(_page([{"id": 150}], None)),+ _resp(_page([{"id": 250}], None)),+ ]+ manager = _make_manager(FlagsmithResumeConfig(next_url=resume_url, parent_key="1"))++ list(get_rows("key", None, "segments", mock.MagicMock(), manager))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls == [+ f"{API_BASE}/projects/",+ resume_url,+ f"{API_BASE}/projects/2/segments/?page_size=100",+ ]++ @mock.patch(SESSION_PATH)+ def test_fan_out_resume_url_repinned_to_configured_base(self, mock_session):+ # Same host-pinning guarantee on the fan-out resume path: a stale mid-parent URL must be+ # re-pinned to the current base rather than replayed to a since-changed host.+ stale = "https://old-host.example.com/api/v1/projects/1/segments/?page=3&page_size=100"+ mock_session.return_value.get.side_effect = [+ _resp([{"id": 1}, {"id": 2}]),+ _resp(_page([{"id": 150}], None)),+ _resp(_page([{"id": 250}], None)),+ ]+ manager = _make_manager(FlagsmithResumeConfig(next_url=stale, parent_key="1"))++ list(get_rows("key", None, "segments", mock.MagicMock(), manager))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[1] == f"{API_BASE}/projects/1/segments/?page=3&page_size=100"++ @mock.patch(SESSION_PATH)+ def test_no_parents_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _resp([])++ assert list(get_rows("key", None, "features", mock.MagicMock(), _make_manager())) == []++ @mock.patch(BUDGET_PATH, 5)+ @mock.patch(SESSION_PATH)+ def test_budget_is_shared_across_fan_out_parents(self, mock_session):+ # Many parents, each with a cyclic child `next`. A per-parent cap would multiply into+ # budget-per-parent requests; the shared budget bounds the whole invocation instead.+ def _get(url, **kwargs):+ if "/features/" in url:+ return _resp(_page([{"id": 1}], f"{API_BASE}/projects/1/features/?page=next"))+ return _resp([{"id": 1}, {"id": 2}, {"id": 3}]) # projects (plain array, one fetch)++ mock_session.return_value.get.side_effect = _get++ list(get_rows("key", None, "features", mock.MagicMock(), _make_manager()))++ # 1 projects fetch + 4 feature fetches = the whole 5-page budget, not 5 per parent.+ assert mock_session.return_value.get.call_count == 5++ @mock.patch(PARENTS_PATH, 2)+ @mock.patch(SESSION_PATH)+ def test_fan_out_parent_count_is_capped(self, mock_session):+ # A hostile host can return a huge parent list in one page; enumeration must stop at the+ # cap so the retained parent list can't exhaust worker memory (only capped parents fan out).+ def _get(url, **kwargs):+ if url.endswith("/projects/"):+ return _resp([{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}])+ return _resp(_page([{"id": 100}], None))++ mock_session.return_value.get.side_effect = _get++ list(get_rows("key", None, "features", mock.MagicMock(), _make_manager()))++ child_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/features/" in c.args[0]]+ assert len(child_urls) == 2 # only the first 2 of 4 projects enumerated++ @mock.patch(KEY_LENGTH_PATH, 5)+ @mock.patch(SESSION_PATH)+ def test_oversized_parent_key_is_skipped(self, mock_session):+ # A hostile host can return an arbitrarily long id/api_key; over-length keys must be dropped+ # so they can't balloon the retained list or be interpolated into a child request URL.+ def _get(url, **kwargs):+ if url.endswith("/projects/"):+ return _resp([{"id": "x" * 50}, {"id": 2}])+ return _resp(_page([{"id": 100}], None))++ mock_session.return_value.get.side_effect = _get++ list(get_rows("key", None, "features", mock.MagicMock(), _make_manager()))++ child_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/features/" in c.args[0]]+ assert child_urls == [+ f"{API_BASE}/projects/2/features/?page_size=100&sort_field=created_date&sort_direction=ASC"+ ]+++class TestErrors:+ @mock.patch(SESSION_PATH)+ def test_4xx_raises(self, mock_session):+ resp = _resp({}, status_code=403)+ resp.raise_for_status.side_effect = Exception("403 Client Error")+ mock_session.return_value.get.return_value = resp++ with pytest.raises(Exception, match="403 Client Error"):+ list(get_rows("key", None, "organisations", mock.MagicMock(), _make_manager()))+++class TestReadBounded:+ # A customer-controlled self-hosted host could return an arbitrarily large or slow-dripped+ # body; these guard that the byte cap and transfer deadline both fail the read.+ def test_raises_when_body_exceeds_byte_cap(self):+ resp = mock.MagicMock()+ resp.iter_content.return_value = iter([b"x" * 10, b"y" * 10])+ with pytest.raises(FlagsmithResponseTooLargeError):+ _read_bounded(resp, max_bytes=15)++ def test_aborts_when_read_blocks_past_deadline(self):+ # A trickle host makes `iter_content` block mid-chunk so no in-loop deadline check runs;+ # the wall-clock deadline must still abort the read and close the response to unblock it.+ blocker = threading.Event()++ def _stalled_iter(*args, **kwargs):+ blocker.wait(timeout=10)+ yield b"late"++ resp = mock.MagicMock()+ resp.iter_content.side_effect = _stalled_iter+ try:+ with pytest.raises(FlagsmithResponseTimeoutError):+ _read_bounded(resp, max_bytes=100, max_seconds=0.1)+ resp.close.assert_called_once()+ finally:+ blocker.set()+++class TestFlagsmithSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = FLAGSMITH_ENDPOINTS[endpoint]+ response = flagsmith_source("key", None, endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_users_use_composite_primary_key(self):+ # A user can belong to more than one organisation, so `id` alone would collide.+ assert FLAGSMITH_ENDPOINTS["users"].primary_keys == ["id", "_organisation_id"]++ @pytest.mark.parametrize("endpoint", [e for e, c in FLAGSMITH_ENDPOINTS.items() if c.partition_key])+ def test_partition_keys_are_stable_creation_timestamps(self, endpoint):+ # Partitioning on a mutable field rewrites partitions every sync.+ assert FLAGSMITH_ENDPOINTS[endpoint].partition_key in ("created_date", "created_at")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.pynew file mode 100644index 000000000000..02837966b86a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.py@@ -0,0 +1,150 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.flagsmith import FlagsmithResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.source import FlagsmithSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlagsmithSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.source.validate_flagsmith_credentials"+)+++class TestFlagsmithSource:+ def setup_method(self):+ self.source = FlagsmithSource()+ self.team_id = 123+ self.config = FlagsmithSourceConfig(api_key="org-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.FLAGSMITH++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Flagsmith"+ assert config.label == "Flagsmith"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/flagsmith.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/flagsmith"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "base_url"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_base_url_is_a_connection_host_field(self):+ # Retargeting the API URL must force re-entry of the API key (credential exfiltration guard).+ assert self.source.connection_host_fields == ["base_url"]++ def test_get_schemas_lists_all_endpoints_full_refresh(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # Flagsmith has no server-side timestamp filter, so nothing is incremental.+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["features"])+ assert len(schemas) == 1+ assert schemas[0].name == "features"++ @pytest.mark.parametrize(+ "status, schema_name, expected_valid",+ [+ (200, None, True),+ (401, None, False),+ # A valid key may lack scope for an unselected endpoint — accept 403 at source-create.+ (403, None, True),+ # But reject 403 when validating a specific schema.+ (403, "features", False),+ (500, None, False),+ (None, None, False),+ ],+ )+ @mock.patch(VALIDATE_PATH)+ def test_validate_credentials_status_mapping(self, mock_validate, status, schema_name, expected_valid):+ mock_validate.return_value = status++ is_valid, _error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)++ assert is_valid is expected_valid++ @pytest.mark.parametrize(+ "schema_name, expected_path",+ [+ ("organisations", "/organisations/"),+ ("projects", "/projects/"),+ ("features", "/projects/"),+ ("feature_states", "/projects/"),+ ("audit_logs", "/organisations/"),+ ],+ )+ @mock.patch(VALIDATE_PATH)+ def test_validate_credentials_probe_paths(self, mock_validate, schema_name, expected_path):+ mock_validate.return_value = 200+ self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)+ assert mock_validate.call_args.args[2] == expected_path++ @mock.patch(VALIDATE_PATH)+ def test_validate_credentials_rejects_invalid_base_url(self, mock_validate):+ config = FlagsmithSourceConfig(api_key="org-key", base_url="https://[email protected]")++ is_valid, error = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error == "Invalid Flagsmith API URL"+ mock_validate.assert_not_called()++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.source.is_cloud")+ @mock.patch(VALIDATE_PATH)+ def test_validate_credentials_rejects_http_on_cloud(self, mock_validate, mock_is_cloud):+ mock_is_cloud.return_value = True+ config = FlagsmithSourceConfig(api_key="org-key", base_url="http://flagsmith.example.com")++ is_valid, error = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error == "Flagsmith API URL must use https"+ mock_validate.assert_not_called()++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FlagsmithResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.source.flagsmith_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_flagsmith_source):+ 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)++ kwargs = mock_flagsmith_source.call_args.kwargs+ assert kwargs["api_key"] == "org-key"+ assert kwargs["base_url"] is None+ assert kwargs["endpoint"] == "features"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_invalid_base_url(self):+ config = FlagsmithSourceConfig(api_key="org-key", base_url="https://[email protected]")+ inputs = mock.MagicMock()+ inputs.schema_name = "features"+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Invalid Flagsmith API URL"):+ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex cf94b1766add..17a00a638aa9 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@@ -1612,7 +1612,8 @@ class FireworksAISourceConfig(config.Config):@config.configclass FlagsmithSourceConfig(config.Config):- pass+ api_key: str+ base_url: str | None = None@config.config