: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): add FusionAuth source (#73194)
Tom Owers80f56d6339e1
diff --git a/frontend/public/services/fusionauth.png b/frontend/public/services/fusionauth.pngindex d756fddb6ec8..3e47ec233d1e 100644Binary files a/frontend/public/services/fusionauth.png and b/frontend/public/services/fusionauth.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex eaa6f29f1642..b86b60767b25 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -237,6 +237,7 @@ the row lists both.| front | HTTP | requests | ✅ || fulcrum | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ |+| fusionauth | HTTP | requests + `rest_source.RESTClient` | ✅ || gainsight_px | HTTP | requests | ✅ || gerrit | HTTP | requests | ✅ || gitbook | HTTP | requests | ✅ |@@ -930,7 +931,6 @@ doesn't conflict with concurrent PRs.- freshservice- frontegg- fulcrum-- fusionauth- g2- gcore- gcp_apigeediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/canonical_descriptions.pynew file mode 100644index 000000000000..6558a6be2930--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/canonical_descriptions.py@@ -0,0 +1,56 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Users": {+ "description": "FusionAuth user accounts, including their registrations, contact info, and account timestamps.",+ "docs_url": "https://fusionauth.io/docs/apis/users",+ "columns": {+ "id": "Unique identifier for the user.",+ "email": "The user's email address.",+ "username": "The user's username.",+ "active": "Whether the user's account is active (not soft-deleted).",+ "insertInstant": "The instant (epoch milliseconds) the user was created.",+ "lastUpdateInstant": "The instant (epoch milliseconds) the user was last updated.",+ "lastLoginInstant": "The instant (epoch milliseconds) of the user's last successful login.",+ "verified": "Whether the user's email address has been verified.",+ "tenantId": "The unique identifier of the tenant the user belongs to.",+ "registrations": "The applications this user is registered for.",+ },+ },+ "AuditLogs": {+ "description": "Administrative actions taken in the FusionAuth admin UI or API, such as user or configuration changes.",+ "docs_url": "https://fusionauth.io/docs/apis/audit-logs",+ "columns": {+ "id": "Unique identifier for the audit log entry.",+ "insertInstant": "The instant (epoch milliseconds) the audit log entry was created.",+ "insertUser": "The email address (or identifier) of the user who performed the action.",+ "message": "A description of the action that was performed.",+ "tenantId": "The unique identifier of the tenant the action was performed in, if applicable.",+ "data": "Additional structured data about the change, such as reason and old/new values.",+ },+ },+ "EventLogs": {+ "description": "Internal FusionAuth system events, such as errors and informational/debug messages.",+ "docs_url": "https://fusionauth.io/docs/apis/event-logs",+ "columns": {+ "id": "Unique identifier for the event log entry.",+ "insertInstant": "The instant (epoch milliseconds) the event log entry was created.",+ "message": "The event log message.",+ "type": "The severity of the event log entry (Information, Debug, or Error).",+ },+ },+ "LoginRecords": {+ "description": "A record of every successful and failed login attempt against a FusionAuth application.",+ "docs_url": "https://fusionauth.io/docs/apis/login",+ "columns": {+ "applicationId": "The unique identifier of the application the login attempt was made against.",+ "applicationName": "The name of the application the login attempt was made against.",+ "userId": "The unique identifier of the user who attempted to log in.",+ "loginId": "The identifier (email or username) the user logged in with.",+ "instant": "The instant (epoch milliseconds) the login attempt occurred.",+ "ipAddress": "The IP address the login attempt was made from.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/fusionauth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/fusionauth.pynew file mode 100644index 000000000000..b63ccb902dfa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/fusionauth.py@@ -0,0 +1,443 @@+import threading+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlparse++import requests+from requests import PreparedRequest, Request, Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapter+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.settings import (+ FUSIONAUTH_ENDPOINTS,+ FusionAuthEndpointConfig,+)++HOST_NOT_ALLOWED_ERROR = "FusionAuth base URL is not allowed"+HTTP_NOT_ALLOWED_ERROR = "FusionAuth base URL must use HTTPS"++# The base URL can be a customer-controlled self-hosted host, so the sync path can't trust it to+# behave. `RESTClient` calls `session.send()` without a timeout and buffers the whole body via+# `.json()`, so a host that hangs, trickles bytes, or ships a huge (or gzip-bombed) 200 could pin an+# import worker or exhaust its memory. `_BoundedFusionAuthSession` pins a connect/read timeout and+# reads every body incrementally under a decoded-byte cap and a wall-clock deadline before handing+# it back.+DEFAULT_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0) # (connect, read)+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+_READ_CHUNK_BYTES = 1024 * 1024+# The per-read socket timeout only bounds the gap between bytes, so a host trickling one byte just+# under it could keep a worker busy indefinitely. This absolute wall-clock deadline caps how long a+# single body read may take end to end, even while a read is blocked mid-chunk.+MAX_RESPONSE_SECONDS = 600.0++# The credential probe runs inline in the source-create API request (a Django worker), not a sync+# worker, so it gets much tighter bounds: its only job is to read a status code and a small JSON+# error body, so a controlled host must not be able to hold or fatten the worker even briefly.+VALIDATION_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 10.0) # (connect, read)+VALIDATION_MAX_RESPONSE_BYTES = 5 * 1024 * 1024+VALIDATION_MAX_RESPONSE_SECONDS = 30.0+++class FusionAuthHostNotAllowedError(Exception):+ pass+++class FusionAuthResponseTooLargeError(Exception):+ pass+++class FusionAuthResponseTimeoutError(Exception):+ pass+++def _read_bounded(+ response: Response, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS+) -> bytes:+ """Read a streamed response body under both a decoded-byte cap and a total-transfer deadline.++ The read runs on a worker thread bounded by ``join(timeout=max_seconds)``, so the deadline is+ enforced as absolute wall-clock time even while a read is blocked: ``iter_content`` fills a whole+ chunk before it yields, so a host that trickles bytes just under the per-read socket timeout+ could otherwise never let an in-loop deadline check run. ``iter_content`` decodes content+ encoding as it streams, so the cap counts decoded bytes and a gzip bomb can't slip past it. On+ timeout we close the response to unblock the pending socket read and let the daemon thread unwind.+ """+ box: dict[str, Any] = {}++ def _reader() -> None:+ try:+ total = 0+ chunks: list[bytes] = []+ for chunk in response.iter_content(chunk_size=_READ_CHUNK_BYTES):+ total += len(chunk)+ if total > max_bytes:+ box["error"] = FusionAuthResponseTooLargeError(+ f"FusionAuth 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="fusionauth-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 FusionAuthResponseTimeoutError(f"FusionAuth response exceeded the download time limit ({max_seconds:g}s)")+ if "error" in box:+ raise box["error"]+ return box.get("data", b"")+++class _BoundedFusionAuthSession(requests.Session):+ """Tracked, no-redirect session that streams every response under a size + time bound.++ `RESTClient` invokes `send()` without a timeout and later reads the full body via `.json()`, so+ on its own it offers no defense against a customer-controlled host that hangs or returns an+ unbounded body. This pins a default connect/read timeout, streams the body through+ `_read_bounded` under a decoded-byte cap and a wall-clock deadline, then re-buffers it so the+ rest of the REST client (`.json()`, `.content`) sees an ordinary buffered response. The probe in+ `validate_credentials` reuses it with tighter caps.+ """++ def __init__(self, *, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS) -> None:+ super().__init__()+ self._max_bytes = max_bytes+ self._max_seconds = max_seconds++ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:+ # Never follow redirects: a validated host could 3xx to an internal address (SSRF). Pin the+ # timeout only when the caller didn't set one, and stream so the body is read incrementally.+ kwargs["allow_redirects"] = False+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT_SECONDS)+ kwargs["stream"] = True+ response = super().send(request, **kwargs)+ if response.is_redirect or response.is_permanent_redirect:+ # The caller rejects the 3xx itself; don't touch the (unconsumed) body.+ return response+ response._content = _read_bounded(response, self._max_bytes, self._max_seconds)+ response._content_consumed = True # type: ignore[attr-defined]+ return response+++def _make_bounded_session(+ api_key: str, *, max_bytes: int = MAX_RESPONSE_BYTES, max_seconds: float = MAX_RESPONSE_SECONDS+) -> requests.Session:+ session = _BoundedFusionAuthSession(max_bytes=max_bytes, max_seconds=max_seconds)+ adapter = make_tracked_adapter(redact_values=(api_key,))+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session+++def _is_https(base_url: str) -> bool:+ # The API key rides in the Authorization header, so refuse plaintext HTTP to keep an on-path+ # attacker from capturing it.+ return urlparse(base_url).scheme == "https"+++class FusionAuthResumeConfig:+ offset: int+++def normalize_base_url(base_url: str) -> str:+ """Turn whatever the user typed into a bare origin (scheme + host[:port]).++ Accepts values like ``auth.example.com``, ``https://auth.example.com/``, or+ ``https://auth.example.com/api``, and returns ``https://auth.example.com``. Defaults to+ https since FusionAuth Cloud and any customer-facing self-hosted instance should be+ reachable over TLS.+ """+ stripped = base_url.strip().rstrip("/")+ if not stripped.lower().startswith(("http://", "https://")):+ stripped = f"https://{stripped}"+ parsed = urlparse(stripped)+ return f"{parsed.scheme}://{parsed.netloc}"+++def _hostname(base_url: str) -> str:+ return (urlparse(base_url).hostname or "").lower()+++def _is_same_host(url: str, base_url: str) -> bool:+ try:+ return (urlparse(url).hostname or "").lower() == _hostname(base_url)+ except Exception:+ return False+++class FusionAuthOffsetPaginator(BasePaginator):+ """FusionAuth search endpoints take their pagination fields (``startRow``,+ ``numberOfResults``) nested inside the POST body's ``search`` object rather than as+ query params or root-level JSON keys, so the generic ``OffsetPaginator`` doesn't fit.++ Termination relies on ``len(page) < limit`` rather than the response's ``total`` field:+ ``total`` is either absent unless explicitly requested (login records) or an extra+ computation the API doesn't need to do just to page (audit/event logs, users), so an+ undersized page is a simpler, universally available stopping signal.+ """++ def __init__(self, limit: int, offset: int = 0, maximum_offset: Optional[int] = None) -> None:+ super().__init__()+ self.limit = limit+ self.offset = offset+ self.maximum_offset = maximum_offset++ def _set_paging(self, request: Request) -> None:+ if request.json is None:+ request.json = {}+ search = request.json.setdefault("search", {})+ search["startRow"] = self.offset+ search["numberOfResults"] = self.limit++ def init_request(self, request: Request) -> None:+ self._set_paging(request)++ def update_request(self, request: Request) -> None:+ self._set_paging(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if not data:+ self._has_next_page = False+ return+ self.offset += self.limit+ if len(data) < self.limit:+ self._has_next_page = False+ return+ if self.maximum_offset is not None and self.offset >= self.maximum_offset:+ self._has_next_page = False++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"offset": self.offset} if self._has_next_page else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ offset = state.get("offset")+ if offset is not None:+ self.offset = int(offset)+ self._has_next_page = True++ def __str__(self) -> str:+ return f"FusionAuthOffsetPaginator(offset={self.offset}, limit={self.limit})"+++def _build_search_body(config: FusionAuthEndpointConfig, search_extra: dict[str, Any]) -> dict[str, Any]:+ search: dict[str, Any] = {}+ if config.name == "Users":+ # `queryString: "*"` matches every user; sortFields keeps ordering stable across pages.+ search["queryString"] = "*"+ search["sortFields"] = [{"name": "insertInstant", "order": "asc"}]+ elif config.sort_mode == "asc":+ # AuditLogs/EventLogs document an explicit `orderBy` field (unlike LoginRecords),+ # so we can request ascending order and use a simple advancing watermark.+ search["orderBy"] = "insertInstant ASC"+ search.update(search_extra)+ return {"search": search}+++def _get_headers() -> dict[str, str]:+ return {"Accept": "application/json", "Content-Type": "application/json"}+++def validate_credentials(base_url: str, api_key: str, team_id: Optional[int] = None) -> tuple[bool, str | None]:+ """Probe a cheap, non-search endpoint to confirm the API key is genuine.++ Applications aren't Elasticsearch-backed (unlike the search endpoints this source syncs),+ so this doesn't require the instance to have search configured just to validate a key.+ """+ try:+ normalized = normalize_base_url(base_url)+ except Exception:+ return False, "Invalid FusionAuth base URL"++ hostname = _hostname(normalized)+ if not hostname:+ return False, "Invalid FusionAuth base URL"++ 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++ # Refuse plaintext HTTP before the key-bearing request goes out, so a self-hosted URL can't+ # expose the API key on the network.+ if not _is_https(normalized):+ return False, HTTP_NOT_ALLOWED_ERROR++ try:+ # A bounded session (like the sync path, but with tight validation caps) streams the probe+ # body under a decoded-byte cap and an absolute deadline, so a controlled host can't hold or+ # fatten this inline API worker. `redact_values` masks the key from captured samples; the+ # session refuses redirects so the validated host can't 3xx to an internal address (SSRF).+ session = _make_bounded_session(+ api_key, max_bytes=VALIDATION_MAX_RESPONSE_BYTES, max_seconds=VALIDATION_MAX_RESPONSE_SECONDS+ )+ response = session.get(+ f"{normalized}/api/application",+ headers={**_get_headers(), "Authorization": api_key},+ timeout=VALIDATION_TIMEOUT_SECONDS,+ allow_redirects=False,+ )+ except (requests.exceptions.RequestException, FusionAuthResponseTooLargeError, FusionAuthResponseTimeoutError) as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid FusionAuth API key"++ try:+ body = response.json()+ return False, body.get("generalErrors", [{}])[0].get("message", response.text) if body else response.text+ except Exception:+ return False, response.text+++def fusionauth_source(+ base_url: str,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FusionAuthResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ db_incremental_field_earliest_value: Optional[Any] = None,+) -> SourceResponse:+ config = FUSIONAUTH_ENDPOINTS[endpoint]+ normalized_url = normalize_base_url(base_url)++ def make_rest_config(search_extra: dict[str, Any], maximum_offset: Optional[int]) -> RESTAPIConfig:+ return {+ "client": {+ "base_url": normalized_url,+ "headers": _get_headers(),+ # Auth rides on the framework auth config so it's redacted from logs/errors;+ # FusionAuth expects the raw key value, no "Bearer"/scheme prefix.+ "auth": {"type": "api_key", "api_key": api_key, "name": "Authorization", "location": "header"},+ "paginator": FusionAuthOffsetPaginator(limit=config.page_size, maximum_offset=maximum_offset),+ # A validated host could still 3xx to an internal address; refuse to follow+ # redirects so the Authorization header never replays to an unexpected host (SSRF).+ "allow_redirects": False,+ # Bound the customer-controlled host: pin a connect/read timeout and read every body+ # under a decoded-byte cap and wall-clock deadline so it can't hang a worker or OOM it.+ "session": _make_bounded_session(api_key),+ },+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "method": "POST",+ "path": config.path,+ "json": _build_search_body(config, search_extra),+ "data_selector": config.data_selector,+ },+ }+ ],+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a crash+ # re-fetches the next page (merge dedupes on the primary key) rather than skipping it.+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(FusionAuthResumeConfig(offset=int(state["offset"])))++ def items() -> Iterator[list[Any]]:+ # Re-check at run time (not just at source-create) in case the base URL was edited to+ # now resolve to an internal address (SSRF / DNS rebinding). Only enforced on cloud. Refuse+ # plaintext HTTP before the key is used. Both raise before any request leaves the process.+ host_ok, host_err = _is_host_safe(_hostname(normalized_url), team_id)+ if not host_ok:+ raise FusionAuthHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ if not _is_https(normalized_url):+ raise FusionAuthHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ if config.sort_mode == "desc":+ # LoginRecords has no documented `orderBy`, so we can't assert ascending order.+ # Mirror the Stripe source's descending-endpoint pattern: scroll strictly-earlier+ # rows (below the lowest instant already synced) and strictly-newer rows (above the+ # highest instant already synced) as two separate bounded passes. Each pass fully+ # drains its own small window every attempt rather than persisting resumable state,+ # since a bounded incremental delta is cheap to redo from scratch on a crash.+ if (+ not should_use_incremental_field+ or db_incremental_field_last_value is None+ and db_incremental_field_earliest_value is None+ ):+ initial_state = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_state = {"offset": resume.offset}+ resource = rest_api_resource(+ make_rest_config({}, config.maximum_offset),+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ )+ yield from resource+ return++ if db_incremental_field_earliest_value is not None:+ resource = rest_api_resource(+ make_rest_config({"end": db_incremental_field_earliest_value}, None), team_id, job_id, None+ )+ yield from resource++ if db_incremental_field_last_value is not None:+ resource = rest_api_resource(+ make_rest_config({"start": db_incremental_field_last_value}, None), team_id, job_id, None+ )+ yield from resource+ return++ # Ascending (or non-incremental full-refresh) endpoints: a single pass, resumable+ # across the whole run since a first full-history sync can be large.+ search_extra: dict[str, Any] = {}+ if should_use_incremental_field and db_incremental_field_last_value is not None and config.incremental_fields:+ search_extra["start"] = db_incremental_field_last_value++ initial_state = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_state = {"offset": resume.offset}++ resource = rest_api_resource(+ make_rest_config(search_extra, config.maximum_offset),+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ )+ yield from resource++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" 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/fusionauth/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/settings.pynew file mode 100644index 000000000000..dad29d23e2d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/settings.py@@ -0,0 +1,96 @@+from dataclasses import dataclass+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.Integer, # FusionAuth instants are epoch millis+ }+++@dataclass+class FusionAuthEndpointConfig:+ name: str+ path: str+ # Key in the JSON response holding the list of rows (e.g. "users", "auditLogs").+ data_selector: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField]+ # Stable, immutable field to partition by. Never a field that mutates in place.+ partition_key: Optional[str] = None+ page_size: int = 100+ # "orderBy" -> the endpoint accepts an explicit `search.orderBy` string ("<field> ASC/DESC"),+ # so we can request ascending order and use a simple advancing watermark.+ # None -> the endpoint has no documented sort control; FusionAuth's default (and only+ # observed) behavior is newest-first, so incremental sync must scroll both directions+ # (see fusionauth.py's earliest/last value handling, mirroring the Stripe source).+ sort_mode: Literal["asc", "desc"] = "asc"+ # Elasticsearch-backed search endpoints (currently just user search) cap the standard+ # result window; None means no such cap is documented.+ maximum_offset: Optional[int] = None+++# Search endpoints only: FusionAuth also has non-search read APIs (e.g. GET /api/user/{id})+# that aren't useful for a bulk warehouse sync, so they're intentionally excluded.+FUSIONAUTH_ENDPOINTS: dict[str, FusionAuthEndpointConfig] = {+ "Users": FusionAuthEndpointConfig(+ name="Users",+ path="/api/user/search",+ data_selector="users",+ primary_keys=["id"],+ # The Elasticsearch-backed queryString filter has no documented server-side timestamp+ # operator we can verify against a live instance, so this stays full refresh.+ incremental_fields=[],+ partition_key="insertInstant",+ page_size=100,+ sort_mode="asc",+ # Standard search window caps around 10k results (search_after/nextResults token+ # pagination for deeper scans is not implemented here).+ maximum_offset=9_900,+ ),+ "AuditLogs": FusionAuthEndpointConfig(+ name="AuditLogs",+ path="/api/system/audit-log/search",+ data_selector="auditLogs",+ primary_keys=["id"],+ incremental_fields=[_datetime_incremental_field("insertInstant")],+ partition_key="insertInstant",+ page_size=100,+ sort_mode="asc",+ ),+ "EventLogs": FusionAuthEndpointConfig(+ name="EventLogs",+ path="/api/system/event-log/search",+ data_selector="eventLogs",+ primary_keys=["id"],+ incremental_fields=[_datetime_incremental_field("insertInstant")],+ partition_key="insertInstant",+ page_size=100,+ sort_mode="asc",+ ),+ "LoginRecords": FusionAuthEndpointConfig(+ name="LoginRecords",+ path="/api/system/login-record/search",+ data_selector="logins",+ # Login records have no unique id field — identified by the combination of user,+ # application and instant (https://fusionauth.io/docs/apis/login/search).+ primary_keys=["userId", "applicationId", "instant"],+ incremental_fields=[_datetime_incremental_field("instant")],+ partition_key="instant",+ page_size=100,+ # No documented `orderBy`/sort control on this endpoint, so we can't assert ascending+ # order — assume FusionAuth's usual newest-first default like the other log endpoints.+ sort_mode="desc",+ ),+}++ENDPOINTS = tuple(FUSIONAUTH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FUSIONAUTH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/source.pyindex 09dc6c1b2fcc..b2551d9f4982 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/source.py@@ -1,13 +1,36 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.fusionauth import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ FusionAuthResumeConfig,+ fusionauth_source,+ validate_credentials as validate_fusionauth_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.settings import (+ ENDPOINTS,+ FUSIONAUTH_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fusionauth import (FusionAuthSourceConfig,)@@ -15,18 +38,134 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FusionAuthSource(SimpleSource[FusionAuthSourceConfig]):+class FusionAuthSource(ResumableSource[FusionAuthSourceConfig, FusionAuthResumeConfig]):+ api_docs_url = "https://fusionauth.io/docs/apis/"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FUSIONAUTH+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API key is sent; retargeting it must re-require the key.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FUSION_AUTH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="FusionAuth",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your FusionAuth instance's base URL and an API key to pull your FusionAuth data into the PostHog Data warehouse.++You can create an API key in the FusionAuth admin UI under **Settings > API Keys**.++The key needs read access to the resources you want to sync, for example:+- `/api/user/search`+- `/api/system/audit-log/search`+- `/api/system/event-log/search`+- `/api/system/login-record/search`++Audit logs, event logs, and login records require the Elasticsearch search engine to be configured on your FusionAuth instance.+""",iconPath="/static/services/fusionauth.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/fusionauth",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="base_url",+ label="FusionAuth base URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://your-instance.fusionauth.io",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid FusionAuth API key. Please generate a new key and reconnect.",+ HOST_NOT_ALLOWED_ERROR: "The FusionAuth base URL is not allowed. Please use your organization's FusionAuth instance URL.",+ HTTP_NOT_ALLOWED_ERROR: "The FusionAuth base URL must use HTTPS. Update the source to an https:// URL and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: FusionAuthSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(FUSIONAUTH_ENDPOINTS[endpoint].incremental_fields),+ supports_append=bool(FUSIONAUTH_ENDPOINTS[endpoint].incremental_fields),+ incremental_fields=FUSIONAUTH_ENDPOINTS[endpoint].incremental_fields,+ description="Full sync only; the search API's result window is capped at ~10,000 rows."+ if endpoint == "Users"+ else None,+ )+ 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: FusionAuthSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_fusionauth_credentials(config.base_url, config.api_key, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FusionAuthResumeConfig]:+ return ResumableSourceManager[FusionAuthResumeConfig](inputs, FusionAuthResumeConfig)++ def source_for_pipeline(+ self,+ config: FusionAuthSourceConfig,+ resumable_source_manager: ResumableSourceManager[FusionAuthResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return fusionauth_source(+ base_url=config.base_url,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ db_incremental_field_earliest_value=inputs.db_incremental_field_earliest_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/tests/test_fusionauth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/tests/test_fusionauth.pynew file mode 100644index 000000000000..6ffe8aa2e925--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/tests/test_fusionauth.py@@ -0,0 +1,526 @@+import json+import threading+from typing import Any, Optional, cast++import pytest+from unittest import mock++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth import fusionauth as fusionauth_module+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.fusionauth import (+ HTTP_NOT_ALLOWED_ERROR,+ FusionAuthOffsetPaginator,+ FusionAuthResponseTimeoutError,+ FusionAuthResponseTooLargeError,+ FusionAuthResumeConfig,+ _build_search_body,+ _read_bounded,+ fusionauth_source,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.settings import FUSIONAUTH_ENDPOINTS++# The sync path runs through a bounded session built by `_make_bounded_session`; patch that so the+# pagination tests can drive `session.send` directly (RESTClient uses the session it's handed).+CLIENT_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.fusionauth._make_bounded_session"+)+++def _response(body: dict[str, Any], *, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _redirect_response(status_code: int = 302, location: str = "https://internal.example/") -> Response:+ resp = Response()+ resp.status_code = status_code+ resp.headers["Location"] = location+ resp._content = b""+ return resp+++def _make_manager(resume_state: Optional[FusionAuthResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's url + json body AT PREPARE TIME.++ ``request.json`` is a single dict mutated in place across pages, so snapshot a deep copy+ when each request is prepared rather than inspecting the shared dict after the run.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "json": json.loads(json.dumps(request.json or {}))})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("auth.example.com", "https://auth.example.com"),+ ("https://auth.example.com", "https://auth.example.com"),+ ("https://auth.example.com/", "https://auth.example.com"),+ ("http://auth.example.com/", "http://auth.example.com"),+ (" auth.example.com ", "https://auth.example.com"),+ ("https://auth.example.com/api", "https://auth.example.com"),+ ],+ )+ def test_normalize(self, raw, expected):+ assert normalize_base_url(raw) == expected+++class TestBuildSearchBody:+ def test_users_has_query_string_and_sort_fields(self):+ body = _build_search_body(FUSIONAUTH_ENDPOINTS["Users"], {})+ assert body["search"]["queryString"] == "*"+ assert body["search"]["sortFields"] == [{"name": "insertInstant", "order": "asc"}]++ @pytest.mark.parametrize("endpoint", ["AuditLogs", "EventLogs"])+ def test_ascending_endpoints_request_explicit_order(self, endpoint):+ body = _build_search_body(FUSIONAUTH_ENDPOINTS[endpoint], {})+ assert body["search"]["orderBy"] == "insertInstant ASC"++ def test_login_records_has_no_order_by(self):+ # LoginRecords documents no orderBy field, so it must never be sent.+ body = _build_search_body(FUSIONAUTH_ENDPOINTS["LoginRecords"], {})+ assert "orderBy" not in body["search"]++ def test_search_extra_merges_in(self):+ body = _build_search_body(FUSIONAUTH_ENDPOINTS["AuditLogs"], {"start": 123})+ assert body["search"]["start"] == 123+++class TestFusionAuthOffsetPaginator:+ def _request(self):+ return mock.MagicMock(json=None)++ def test_init_sets_first_page(self):+ paginator = FusionAuthOffsetPaginator(limit=100)+ request = self._request()+ paginator.init_request(request)+ assert request.json == {"search": {"startRow": 0, "numberOfResults": 100}}++ def test_full_page_advances_offset(self):+ paginator = FusionAuthOffsetPaginator(limit=2)+ response = _response({"total": 10})+ paginator.update_state(response, data=[{"id": 1}, {"id": 2}])+ assert paginator.has_next_page is True+ assert paginator.offset == 2++ def test_undersized_page_terminates(self):+ paginator = FusionAuthOffsetPaginator(limit=100)+ response = _response({})+ paginator.update_state(response, data=[{"id": 1}])+ assert paginator.has_next_page is False++ def test_empty_page_terminates(self):+ paginator = FusionAuthOffsetPaginator(limit=100)+ response = _response({})+ paginator.update_state(response, data=[])+ assert paginator.has_next_page is False++ def test_maximum_offset_terminates(self):+ paginator = FusionAuthOffsetPaginator(limit=100, offset=9800, maximum_offset=9900)+ response = _response({})+ paginator.update_state(response, data=[{"id": i} for i in range(100)])+ assert paginator.has_next_page is False++ def test_resume_state_roundtrip(self):+ paginator = FusionAuthOffsetPaginator(limit=100)+ paginator.offset = 300+ state = paginator.get_resume_state()+ assert state == {"offset": 300}++ resumed = FusionAuthOffsetPaginator(limit=100)+ resumed.set_resume_state(state)+ assert resumed.offset == 300+ assert resumed.has_next_page is True++ def test_no_resume_state_when_exhausted(self):+ paginator = FusionAuthOffsetPaginator(limit=100)+ paginator._has_next_page = False+ assert paginator.get_resume_state() is None+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(fusionauth_module, "_make_bounded_session", return_value=session)++ def _resp(self, *, status_code=200, json_data=None, text=""):+ response = mock.MagicMock()+ response.status_code = status_code+ response.is_redirect = status_code in (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.json.return_value = json_data+ return response++ def test_success(self):+ with self._patch_session(self._resp(status_code=200)):+ assert validate_credentials("https://auth.example.com", "tok") == (True, None)++ def test_invalid_key(self):+ with self._patch_session(self._resp(status_code=401)):+ valid, msg = validate_credentials("https://auth.example.com", "tok")+ assert valid is False+ assert msg == "Invalid FusionAuth API key"++ def test_error_body_surfaces_message(self):+ with self._patch_session(+ self._resp(status_code=500, json_data={"generalErrors": [{"message": "internal error"}]})+ ):+ valid, msg = validate_credentials("https://auth.example.com", "tok")+ assert valid is False+ assert msg == "internal error"++ def test_request_exception_returns_failure(self):+ import requests++ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials("https://auth.example.com", "tok")+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ # A validated host that 3xx-redirects (potentially to an internal address) must be+ # rejected, not followed (SSRF).+ with self._patch_session(self._resp(status_code=302)) as patched:+ valid, msg = validate_credentials("https://auth.example.com", "tok")+ assert valid is False+ assert msg == fusionauth_module.HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host(self):+ # When a team_id is supplied, a host that resolves to an internal address is rejected+ # before any HTTP request is made (SSRF guard).+ with (+ mock.patch.object(fusionauth_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(self._resp(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("https://10.0.0.1", "tok", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()++ @pytest.mark.parametrize("bad_url", ["", " "])+ def test_invalid_url_short_circuits(self, bad_url):+ valid, msg = validate_credentials(bad_url, "tok")+ assert valid is False+ assert msg == "Invalid FusionAuth base URL"++ def test_rejects_plaintext_http_before_sending_key(self):+ # An explicit http:// URL would send the API key in plaintext; reject it before any request.+ with self._patch_session(self._resp(status_code=200)) as patched:+ valid, msg = validate_credentials("http://auth.example.com", "tok")+ assert valid is False+ assert msg == HTTP_NOT_ALLOWED_ERROR+ patched.return_value.get.assert_not_called()++ def test_oversized_or_stalled_body_surfaces_as_failure(self):+ # A controlled host that ships an unbounded/stalled body must fail validation, not hang.+ with self._patch_session(raises=FusionAuthResponseTooLargeError("too big")):+ valid, msg = validate_credentials("https://auth.example.com", "tok")+ assert valid is False+ assert "too big" in (msg or "")+++class TestFusionAuthSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, sort_mode, partition_key",+ [+ ("Users", ["id"], "asc", "insertInstant"),+ ("AuditLogs", ["id"], "asc", "insertInstant"),+ ("EventLogs", ["id"], "asc", "insertInstant"),+ ("LoginRecords", ["userId", "applicationId", "instant"], "desc", "instant"),+ ],+ )+ def test_response_shape(self, endpoint, primary_keys, sort_mode, partition_key):+ response = fusionauth_source(+ base_url="https://auth.example.com",+ api_key="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "week"+++class TestFusionAuthAscendingPagination:+ def _source(self, endpoint="AuditLogs", manager=None, base_url="https://auth.example.com", **kwargs):+ return fusionauth_source(+ base_url=base_url,+ api_key="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ **kwargs,+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_undersized_page(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"auditLogs": [{"id": i} for i in range(100)]}),+ _response({"auditLogs": [{"id": 100}]}),+ ],+ )+ rows = _rows(self._source())+ assert [r["id"] for r in rows] == list(range(101))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_state_after_yielding(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"auditLogs": [{"id": i} for i in range(100)]}),+ _response({"auditLogs": [{"id": 100}]}),+ ],+ )+ manager = _make_manager()+ _rows(self._source(manager=manager))++ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, FusionAuthResumeConfig)+ assert saved.offset == 100++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_state(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response({"auditLogs": [{"id": 9}]})])+ manager = _make_manager(FusionAuthResumeConfig(offset=500))+ rows = _rows(self._source(manager=manager))++ assert snaps[0]["json"]["search"]["startRow"] == 500+ assert [r["id"] for r in rows] == [9]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_start_filter_reaches_request(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response({"auditLogs": [{"id": 1}]})])+ _rows(+ self._source(+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000000,+ )+ )+ assert snaps[0]["json"]["search"]["start"] == 1700000000000+ assert snaps[0]["json"]["search"]["orderBy"] == "insertInstant ASC"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_ignores_stray_watermark(self, MockSession):+ # Users has no incremental_fields declared, so a watermark must never reach the request.+ session = MockSession.return_value+ snaps = _wire(session, [_response({"users": [{"id": 1}]})])+ _rows(+ self._source(+ endpoint="Users",+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000000,+ )+ )+ assert "start" not in snaps[0]["json"]["search"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_users_body_shape(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response({"users": [{"id": 1}]})])+ _rows(self._source(endpoint="Users"))+ assert snaps[0]["json"]["search"]["queryString"] == "*"+ assert snaps[0]["json"]["search"]["numberOfResults"] == 100++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_does_not_follow_redirects(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_redirect_response(302)])+ with pytest.raises(ValueError):+ _rows(self._source())++ @mock.patch("tenacity.nap.time.sleep")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_retries_on_429(self, MockSession, _mock_sleep):+ session = MockSession.return_value+ _wire(session, [_response({}, status_code=429), _response({"auditLogs": [{"id": 1}]})])+ rows = _rows(self._source())++ assert [r["id"] for r in rows] == [1]+ assert session.send.call_count == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_runtime_host_check_blocks_unsafe_domain(self, MockSession):+ # The configured base URL is re-checked at run time (DNS rebinding) before any request.+ session = MockSession.return_value+ _wire(session, [_response({"auditLogs": [{"id": 1}]})])+ with mock.patch.object(fusionauth_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(fusionauth_module.FusionAuthHostNotAllowedError):+ _rows(self._source())+ session.send.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_runtime_rejects_plaintext_http_before_sending_key(self, MockSession):+ # A base URL edited to http:// must be refused at run time before the key leaves the process.+ session = MockSession.return_value+ _wire(session, [_response({"auditLogs": [{"id": 1}]})])+ with pytest.raises(fusionauth_module.FusionAuthHostNotAllowedError):+ _rows(self._source(base_url="http://auth.example.com"))+ session.send.assert_not_called()+++class TestFusionAuthDescendingPagination:+ def _source(self, manager=None, **kwargs):+ return fusionauth_source(+ base_url="https://auth.example.com",+ api_key="tok",+ endpoint="LoginRecords",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ **kwargs,+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_scan_when_no_watermarks(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response({"logins": [{"userId": "1"}]})])+ rows = _rows(self._source(should_use_incremental_field=True))+ assert rows == [{"userId": "1"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_scan_is_resumable(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"logins": [{"userId": str(i)} for i in range(100)]}),+ _response({"logins": [{"userId": "100"}]}),+ ],+ )+ manager = _make_manager()+ _rows(self._source(manager=manager))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].offset == 100++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_earliest_and_last_value_both_queried(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(+ session,+ [+ _response({"logins": [{"userId": "earlier"}]}),+ _response({"logins": [{"userId": "newer"}]}),+ ],+ )+ rows = _rows(+ self._source(+ should_use_incremental_field=True,+ db_incremental_field_earliest_value=1600000000000,+ db_incremental_field_last_value=1700000000000,+ )+ )++ assert [r["userId"] for r in rows] == ["earlier", "newer"]+ assert snaps[0]["json"]["search"]["end"] == 1600000000000+ assert snaps[1]["json"]["search"]["start"] == 1700000000000+ assert "orderBy" not in snaps[0]["json"]["search"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_only_last_value_set(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response({"logins": [{"userId": "newer"}]})])+ _rows(+ self._source(+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000000,+ db_incremental_field_earliest_value=None,+ )+ )+ assert snaps[0]["json"]["search"]["start"] == 1700000000000++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_not_incremental_falls_back_to_full_scan(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response({"logins": [{"userId": "1"}]})])+ _rows(+ self._source(+ should_use_incremental_field=False,+ db_incremental_field_last_value=1700000000000,+ )+ )+ assert "start" not in snaps[0]["json"]["search"]+++class _FakeStreamResponse:+ """Minimal streamed `requests.Response` stand-in: yields fixed chunks and records close()."""++ def __init__(self, chunks: list[bytes], *, block: bool = False) -> None:+ self._chunks = chunks+ self._block = block+ self._released = threading.Event()+ self.closed = False++ def iter_content(self, chunk_size: int = 1) -> Any:+ yield from self._chunks+ if self._block:+ # Never completes on its own; only close() releases it. Models a host that stops mid-body.+ self._released.wait()++ def close(self) -> None:+ self.closed = True+ self._released.set()+++class TestReadBounded:+ def test_reads_full_body_under_cap(self):+ response = _FakeStreamResponse([b"hel", b"lo"])+ assert _read_bounded(cast(requests.Response, response), max_bytes=100) == b"hello"++ def test_raises_when_body_exceeds_byte_cap(self):+ # The cap is what stops a huge (or gzip-bombed) body from exhausting a worker's memory.+ response = _FakeStreamResponse([b"a" * 8, b"b" * 8])+ with pytest.raises(FusionAuthResponseTooLargeError):+ _read_bounded(cast(requests.Response, response), max_bytes=10)++ def test_times_out_and_closes_a_stalled_body(self):+ # A host that stalls mid-body must not pin the worker: the deadline fires and the socket is+ # closed. max_seconds=0 makes the join return immediately while the reader is still blocked.+ response = _FakeStreamResponse([b"partial"], block=True)+ with pytest.raises(FusionAuthResponseTimeoutError):+ _read_bounded(cast(requests.Response, response), max_bytes=100, max_seconds=0)+ assert response.closed is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/tests/test_fusionauth_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/tests/test_fusionauth_source.pynew file mode 100644index 000000000000..bc77fd75e46f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fusionauth/tests/test_fusionauth_source.py@@ -0,0 +1,149 @@+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.fusionauth.fusionauth import (+ FusionAuthResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.source import FusionAuthSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fusionauth import (+ FusionAuthSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestFusionAuthSource:+ def setup_method(self):+ self.source = FusionAuthSource()+ self.team_id = 123+ self.config = FusionAuthSourceConfig(base_url="https://auth.example.com", api_key="00token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.FUSIONAUTH++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "FusionAuth"+ assert config.label == "FusionAuth"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/fusionauth.png"+ assert config.category is not None++ field_names = [f.name for f in config.fields]+ assert field_names == ["base_url", "api_key"]++ url_field, key_field = config.fields+ assert isinstance(url_field, SourceFieldInputConfig)+ assert url_field.type == SourceFieldInputConfigType.TEXT+ assert url_field.secret is False+ assert url_field.required is True++ assert isinstance(key_field, SourceFieldInputConfig)+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_connection_host_fields(self):+ assert self.source.connection_host_fields == ["base_url"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "endpoint, incremental",+ [+ ("Users", False),+ ("AuditLogs", True),+ ("EventLogs", True),+ ("LoginRecords", True),+ ],+ )+ def test_schema_incremental_support(self, endpoint, incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].supports_incremental is incremental+ assert schemas[endpoint].supports_append is incremental++ def test_users_schema_has_window_cap_description(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert "10,000" in (schemas["Users"].description or "")++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Users"])+ assert len(schemas) == 1+ assert schemas[0].name == "Users"++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected",+ [+ ((True, None), (True, None)),+ ((False, "Invalid FusionAuth API key"), (False, "Invalid FusionAuth API key")),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.source.validate_fusionauth_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id)++ assert result == expected+ mock_validate.assert_called_once_with(self.config.base_url, self.config.api_key, self.team_id)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FusionAuthResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.source.fusionauth_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_fusionauth_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "AuditLogs"+ inputs.team_id = 42+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000000+ inputs.db_incremental_field_earliest_value = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_fusionauth_source.assert_called_once()+ kwargs = mock_fusionauth_source.call_args.kwargs+ assert kwargs["base_url"] == "https://auth.example.com"+ assert kwargs["api_key"] == "00token"+ assert kwargs["endpoint"] == "AuditLogs"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["job_id"] == "job-1"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000000+ assert kwargs["db_incremental_field_earliest_value"] is None++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.fusionauth.source.fusionauth_source")+ def test_source_for_pipeline_omits_incremental_values_when_not_incremental(self, mock_fusionauth_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ inputs.db_incremental_field_earliest_value = "ignored"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_fusionauth_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["db_incremental_field_earliest_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fusionauth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fusionauth.pyindex bd6a1d00109c..78ccd288461b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fusionauth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fusionauth.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass FusionAuthSourceConfig(config.Config):- pass+ base_url: str+ api_key: str