: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 jumpcloud import source (#71185)
Tom Owersb30b441268d0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7cada1d9ee7f..c0e9daa25aab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -283,6 +283,7 @@ the row lists both.| jobnimbus | HTTP | requests | ✅ || jotform | HTTP | requests | ✅ || judgeme_reviews | HTTP | requests | ✅ |+| jumpcloud | HTTP | requests | ✅ || justcall | HTTP | requests | ✅ || justsift | HTTP | requests | ✅ || k6_cloud | HTTP | requests | ✅ |@@ -752,7 +753,6 @@ doesn't conflict with concurrent PRs.- jfrog_artifactory- jobber- judgeme_reviews-- jumpcloud- justsift- kafka- kajabidiff --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 e89b3234bec5..1724d14b9fff 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@@ -2275,7 +2275,9 @@ class JudgeMeReviewsSourceConfig(config.Config):@config.configclass JumpcloudSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")+ org_id: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/canonical_descriptions.pynew file mode 100644index 000000000000..8d1f9a02cbb4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/canonical_descriptions.py@@ -0,0 +1,99 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "User identities in the JumpCloud directory, including their account state and profile attributes.",+ "docs_url": "https://docs.jumpcloud.com/api/1.0/index.html#tag/Systemusers",+ "columns": {+ "_id": "Unique identifier of the user.",+ "email": "The user's email address.",+ "username": "The user's JumpCloud username.",+ "firstname": "The user's first name.",+ "lastname": "The user's last name.",+ "displayname": "The user's display name.",+ "activated": "Whether the user account has been activated.",+ "suspended": "Whether the user account is suspended.",+ "account_locked": "Whether the account is locked out (e.g. after failed login attempts).",+ "state": "Lifecycle state of the user (STAGED, ACTIVATED, or SUSPENDED).",+ "created": "Timestamp when the user was created in JumpCloud.",+ "department": "The user's department.",+ "employeeIdentifier": "Employee identifier for the user, unique within the organization.",+ "mfa": "The user's multi-factor authentication configuration and status.",+ "sudo": "Whether the user has administrator (sudo) permissions on bound systems.",+ "totp_enabled": "Whether time-based one-time password MFA is enabled for the user.",+ },+ },+ "systems": {+ "description": "Devices (workstations and servers) managed by the JumpCloud agent.",+ "docs_url": "https://docs.jumpcloud.com/api/1.0/index.html#tag/Systems",+ "columns": {+ "_id": "Unique identifier of the system.",+ "hostname": "Hostname reported by the device.",+ "displayName": "Display name of the system in the admin console.",+ "os": "Operating system family (e.g. Mac OS X, Windows, Ubuntu).",+ "version": "Operating system version.",+ "arch": "CPU architecture of the device.",+ "agentVersion": "Version of the JumpCloud agent installed on the device.",+ "active": "Whether the device is currently connected to JumpCloud.",+ "remoteIP": "Public IP address the device last connected from.",+ "lastContact": "Timestamp of the device's last check-in with JumpCloud.",+ "created": "Timestamp when the system was enrolled in JumpCloud.",+ "allowSshPasswordAuthentication": "Whether SSH password authentication is allowed on the device.",+ "allowMultiFactorAuthentication": "Whether multi-factor authentication is enabled on the device.",+ },+ },+ "user_groups": {+ "description": "User groups used to grant collections of users access to resources (apps, systems, networks).",+ "docs_url": "https://docs.jumpcloud.com/api/2.0/index.html#tag/User-Groups",+ "columns": {+ "id": "Unique identifier of the group.",+ "name": "Display name of the group.",+ "type": "Group type discriminator (user_group).",+ "description": "Description of the group.",+ "email": "Email address associated with the group, if any.",+ "memberQuery": "Dynamic membership query for the group, if membership is rule-based.",+ "membershipMethod": "How membership is managed (static or dynamic).",+ },+ },+ "system_groups": {+ "description": "Device groups used to apply policies and access to collections of systems.",+ "docs_url": "https://docs.jumpcloud.com/api/2.0/index.html#tag/System-Groups",+ "columns": {+ "id": "Unique identifier of the group.",+ "name": "Display name of the group.",+ "type": "Group type discriminator (system_group).",+ "description": "Description of the group.",+ },+ },+ "applications": {+ "description": "SSO applications configured in JumpCloud (SAML, OIDC, and bookmark apps).",+ "docs_url": "https://docs.jumpcloud.com/api/1.0/index.html#tag/Applications",+ "columns": {+ "_id": "Unique identifier of the application.",+ "name": "Internal name of the application connector.",+ "displayName": "Name of the application shown in the admin console.",+ "displayLabel": "Label shown to users in the JumpCloud user portal.",+ "ssoUrl": "IdP-initiated SSO URL for the application.",+ "sso": "SSO protocol configuration for the application.",+ "config": "Connector-specific configuration for the application.",+ },+ },+ "events": {+ "description": "Directory Insights activity events across JumpCloud services: admin console actions, directory changes, SSO, RADIUS, LDAP, MDM, and agent-reported system events.",+ "docs_url": "https://docs.jumpcloud.com/api/insights/directory/1.0/index.html",+ "columns": {+ "id": "Unique identifier of the event.",+ "timestamp": "Time the event occurred.",+ "service": "JumpCloud service that emitted the event (e.g. directory, sso, radius, ldap, systems).",+ "event_type": "Type of the event (e.g. login_attempt, user_created, admin_login_attempt).",+ "initiated_by": "Actor that initiated the event (user, admin, or system identity).",+ "client_ip": "IP address the action originated from.",+ "success": "Whether the attempted action succeeded.",+ "geoip": "GeoIP enrichment for the originating IP address.",+ "useragent": "Parsed user agent of the client that performed the action.",+ "organization": "Identifier of the JumpCloud organization the event belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/docs/jumpcloud.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/docs/jumpcloud.mdxnew file mode 100644index 000000000000..3798cd671453--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/docs/jumpcloud.mdx@@ -0,0 +1,79 @@+---+title: Linking JumpCloud as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Jumpcloud+---++<!--+This is the user-facing posthog.com source doc. It lives here only because no posthog.com+checkout was available when the source was implemented. Move it to+`posthog.com/contents/docs/cdp/sources/jumpcloud.mdx` and delete this copy, then run+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.+-->++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++[JumpCloud](https://jumpcloud.com) is a cloud directory platform for identity, access, and device management.+Linking it as a source syncs your users, devices, groups, SSO applications, and Directory Insights activity events+into the PostHog Data warehouse, so you can join identity and security data with your product data — for example,+access analytics, login and authentication monitoring, or compliance reporting.++## Prerequisites++To connect JumpCloud, you need:++- A JumpCloud administrator account with API access.+- Your admin API key, found in the JumpCloud Admin Portal under your account menu (click your initials in the+ top-right corner, then **My API Key**).+- A Directory Insights subscription if you want to sync the `events` table. How far back events are available+ depends on your Directory Insights retention (up to 90 days).++## Adding a data source++<SourceSetupIntro />++1. Open the JumpCloud Admin Portal and click your account initials in the top-right corner.+2. Select **My API Key** and copy the key.+3. Paste the key into the **API key** field in PostHog.+4. Pick the **Region** your JumpCloud organization is hosted in (US or EU).+5. If you're an MSP/MTP admin managing multiple organizations, enter the **Organization ID** the key should act+ on. Leave it blank otherwise.++Note that the API key is tied to your admin account, so it can read whatever your admin role can. Rotating the+key in JumpCloud invalidates the old one — update the source's credentials afterwards.++## Sync modes++<SyncModes />++The `events` table (Directory Insights) supports **incremental** sync: each run only fetches events newer than+the last synced event timestamp. The directory tables (`users`, `systems`, `user_groups`, `system_groups`,+`applications`) have no server-side "updated since" filter in JumpCloud's API, so they sync as a **full+refresh** — schedule them at a cadence that fits how often your directory changes.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **"Invalid JumpCloud API key"** when connecting: the key is wrong or has been rotated. Copy the current key+ from the Admin Portal (account menu → **My API Key**) and re-enter it. Also check the selected region matches+ where your organization is hosted.+- **The `events` table fails with a permissions error**: Directory Insights requires a subscription that+ includes it, and the admin's role must have access to Directory Insights.+- **MSP/MTP admins**: if the source connects but shows no data, make sure the **Organization ID** field is set+ to the sub-organization you want to sync.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.pynew file mode 100644index 000000000000..46733a2ad00e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.py@@ -0,0 +1,443 @@+import json+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++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.jumpcloud.settings import (+ JUMPCLOUD_ENDPOINTS,+ JumpcloudEndpointConfig,+)++# JumpCloud hosts its EU tenants on separate regional bases.+CONSOLE_BASE_URLS: dict[str, str] = {+ "us": "https://console.jumpcloud.com",+ "eu": "https://console.eu.jumpcloud.com",+}+INSIGHTS_BASE_URLS: dict[str, str] = {+ "us": "https://api.jumpcloud.com",+ "eu": "https://api.eu.jumpcloud.com",+}++# Both the v1 and v2 console list endpoints cap `limit` at 100.+REST_PAGE_SIZE = 100+# Directory Insights allows up to 10,000 events per page; keep pages smaller since each+# event is a sizeable JSON document and pages are yielded whole.+EVENTS_PAGE_SIZE = 1000+# Directory Insights retention is plan-gated (up to 90 days), so reaching back further on+# the first sync can never return more data.+DEFAULT_EVENTS_LOOKBACK_DAYS = 90+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60+++class JumpcloudRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class JumpcloudResumeConfig:+ # Offset of the next page for the limit/skip REST entity endpoints.+ skip: int = 0+ # Directory Insights deep-paging cursor (the X-Search_After response header), only valid+ # against an identical query, so the time window it was issued for is persisted with it.+ search_after: list[Any] | None = None+ start_time: str | None = None+ end_time: str | None = None+++def _get_headers(api_key: str, org_id: str | None = None) -> dict[str, str]:+ headers = {+ "x-api-key": api_key,+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+ # MSP/MTP admin keys act on a sub-organization selected via x-org-id.+ if org_id:+ headers["x-org-id"] = org_id+ return headers+++def _make_session(api_key: str, org_id: str | None = None, capture: bool = True) -> requests.Session:+ # `redact_values` masks the API key in logged URLs and captured HTTP samples so a failed+ # or sampled request can never persist the raw JumpCloud credential in HTTP telemetry.+ # `capture=False` is used for secret-bearing endpoints: HTTP sample capture writes the raw+ # response body during `send()`, before row-level `redact_keys` runs, and the generic sampler+ # doesn't recognize JumpCloud's camel-case secret fields (e.g. `config.idpPrivateKey`). Keeping+ # those responses out of sample storage is the only place the SAML signing key can be stopped.+ return make_tracked_session(headers=_get_headers(api_key, org_id), redact_values=(api_key,), capture=capture)+++def _console_base_url(region: str) -> str:+ return CONSOLE_BASE_URLS.get(region, CONSOLE_BASE_URLS["us"])+++def _insights_base_url(region: str) -> str:+ return INSIGHTS_BASE_URLS.get(region, INSIGHTS_BASE_URLS["us"])+++def _format_rfc3339(value: Any) -> str:+ """Directory Insights wants RFC 3339 timestamps with a literal ``Z`` suffix."""+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return _format_rfc3339(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _parse_retry_after(response: requests.Response) -> float | None:+ """JumpCloud sends ``Retry-After`` in whole seconds on 429. Ignore HTTP-date forms."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, JumpcloudRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++@retry(+ retry=retry_if_exception_type((JumpcloudRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)+def _request(+ session: requests.Session,+ method: str,+ url: str,+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+) -> requests.Response:+ # Don't follow redirects: the session carries the API key in the x-api-key header, which+ # requests would replay to a cross-origin redirect target (only the standard Authorization+ # header is stripped), leaking the credential.+ response = session.request(method, url, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise JumpcloudRetryableError(+ f"JumpCloud API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than+ # silently parsing the redirect body as data.+ if response.is_redirect or response.is_permanent_redirect:+ raise ValueError(+ f"JumpCloud API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ # Don't log the response body: JumpCloud error payloads can echo request details.+ logger.error(f"JumpCloud API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ return response+++def _redact_key(row: dict[str, Any], dotted_key: str) -> dict[str, Any]:+ """Return ``row`` with a possibly-nested field removed. ``"config"`` drops a top-level field;+ ``"config.idpPrivateKey"`` walks into ``config`` and drops its ``idpPrivateKey``. Only the nodes+ on the path are copied, so the upstream row is left unmodified; a missing or non-dict node is a+ no-op."""+ head, _, rest = dotted_key.partition(".")+ if head not in row:+ return row+ if not rest:+ return {k: v for k, v in row.items() if k != head}+ nested = row[head]+ if not isinstance(nested, dict):+ return row+ return {**row, head: _redact_key(nested, rest)}+++def _redact_row(row: Any, redact_keys: list[str]) -> Any:+ if not isinstance(row, dict):+ return row+ for key in redact_keys:+ row = _redact_key(row, key)+ return row+++def _parse_search_after(raw: str | None, logger: FilteringBoundLogger) -> list[Any] | None:+ """Decode the ``X-Search_After`` response header (a JSON-encoded array) into the cursor+ to send as ``search_after`` in the next query body."""+ if not raw:+ return None+ try:+ parsed = json.loads(raw)+ except (TypeError, ValueError):+ logger.warning(f"JumpCloud: could not parse X-Search_After header: {raw!r}")+ return None+ if not isinstance(parsed, list) or not parsed:+ return None+ return parsed+++def _get_rest_rows(+ session: requests.Session,+ base_url: str,+ config: JumpcloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JumpcloudResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Page through a v1/v2 console list endpoint with limit/skip pagination."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ skip = resume.skip if resume else 0+ if resume:+ logger.debug(f"JumpCloud: resuming {config.name} from skip={skip}")++ while True:+ params: dict[str, Any] = {"limit": REST_PAGE_SIZE, "skip": skip}+ if config.sort:+ params["sort"] = config.sort+ url = f"{base_url}{config.path}?{urlencode(params)}"++ response = _request(session, "GET", url, logger)+ data = response.json()++ # v1 wraps rows as {"totalCount": n, "results": [...]}; v2 returns a bare array. Any+ # other 200 payload is a permanent API-contract violation, not a transient failure.+ if config.api == "v1":+ rows = data.get("results") if isinstance(data, dict) else None+ else:+ rows = data if isinstance(data, list) else None+ if not isinstance(rows, list):+ raise ValueError(f"JumpCloud API returned an unexpected response shape: url={url}")++ if not rows:+ break++ yield rows++ # A short page means we've reached the end of the resource.+ if len(rows) < REST_PAGE_SIZE:+ break++ skip += len(rows)+ # Save AFTER yielding so a crash re-runs from the last persisted offset rather than+ # skipping ahead; the merge dedupes any re-pulled rows on the primary key.+ resumable_source_manager.save_state(JumpcloudResumeConfig(skip=skip))+++def _get_event_rows(+ session: requests.Session,+ base_url: str,+ config: JumpcloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JumpcloudResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Page through Directory Insights events with the search_after deep-paging cursor.++ The query window is [watermark (or the 90-day retention cap on the first sync), sync+ start]. The window is server-side, so pagination terminates at the window edge without+ any client-side watermark checks.+ """+ url = f"{base_url}{config.path}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.start_time and resume.end_time:+ # A search_after cursor is only valid against an identical query, so a resumed+ # attempt re-uses the exact window the cursor was issued for.+ start_time = resume.start_time+ end_time = resume.end_time+ search_after = resume.search_after+ logger.debug(f"JumpCloud: resuming events from search_after={search_after}")+ else:+ start_value = db_incremental_field_last_value if should_use_incremental_field else None+ if not start_value:+ start_value = datetime.now(UTC) - timedelta(days=DEFAULT_EVENTS_LOOKBACK_DAYS)+ start_time = _format_rfc3339(start_value)+ # Pin the window's end at sync start so every page (and any resumed attempt) queries+ # the same immutable window.+ end_time = _format_rfc3339(datetime.now(UTC))+ search_after = None++ while True:+ body: dict[str, Any] = {+ "service": ["all"],+ "start_time": start_time,+ "end_time": end_time,+ "limit": EVENTS_PAGE_SIZE,+ }+ if search_after:+ body["search_after"] = search_after++ response = _request(session, "POST", url, logger, json_body=body)+ rows = response.json()+ if not isinstance(rows, list):+ raise ValueError(f"JumpCloud Directory Insights returned a non-list response: url={url}")++ if not rows:+ break++ next_search_after = _parse_search_after(response.headers.get("X-Search_After"), logger)++ yield rows++ if len(rows) < EVENTS_PAGE_SIZE or not next_search_after:+ break++ search_after = next_search_after+ # Save AFTER yielding so a crash re-fetches the last page rather than skipping it;+ # the merge dedupes re-pulled events on `id`.+ resumable_source_manager.save_state(+ JumpcloudResumeConfig(search_after=search_after, start_time=start_time, end_time=end_time)+ )+++def validate_credentials(+ api_key: str,+ org_id: str | None = None,+ region: str = "us",+ schema_name: Optional[str] = None,+) -> tuple[bool, str | None]:+ """Probe a cheap endpoint to confirm the API key is genuine.++ At source-create (``schema_name is None``) a 403 is accepted: the key is valid but the+ admin's role may simply lack access to this particular probe. A scoped probe+ (``schema_name`` set) treats 403 as a hard failure.+ """+ endpoint = JUMPCLOUD_ENDPOINTS.get(schema_name) if schema_name else None+ # A scoped probe against a secret-bearing endpoint returns rows too, so keep its response out+ # of HTTP sample capture as well.+ session = _make_session(api_key, org_id, capture=not (endpoint is not None and endpoint.redact_keys))++ try:+ if endpoint is not None and endpoint.api == "insights":+ now = datetime.now(UTC)+ response = session.post(+ f"{_insights_base_url(region)}{endpoint.path}",+ json={+ "service": ["all"],+ "start_time": _format_rfc3339(now - timedelta(days=1)),+ "end_time": _format_rfc3339(now),+ "limit": 1,+ },+ timeout=10,+ allow_redirects=False,+ )+ else:+ path = endpoint.path if endpoint is not None else "/api/systemusers"+ response = session.get(f"{_console_base_url(region)}{path}?limit=1", timeout=10, allow_redirects=False)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ # Never follow a redirect with the credentialed session (see _request).+ if response.is_redirect or response.is_permanent_redirect:+ return False, "JumpCloud API returned an unexpected redirect"++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid JumpCloud API key"++ if response.status_code == 403:+ if schema_name is None:+ # Valid key, missing access for this probe — let source creation through.+ return True, None+ return False, "Your JumpCloud API key does not have permission to read this data"++ try:+ body = response.json()+ return False, body.get("message", response.text)+ except Exception:+ return False, response.text+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JumpcloudResumeConfig],+ org_id: str | None = None,+ region: str = "us",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = JUMPCLOUD_ENDPOINTS[endpoint]+ # One session reused across every page so urllib3 keeps the connection alive. Endpoints that+ # redact secret-bearing fields opt out of HTTP sample capture entirely, since capture records+ # the raw body before those fields can be stripped.+ session = _make_session(api_key, org_id, capture=not config.redact_keys)++ if config.api == "insights":+ pages = _get_event_rows(+ session,+ _insights_base_url(region),+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ pages = _get_rest_rows(session, _console_base_url(region), config, logger, resumable_source_manager)++ # Strip secret-bearing fields (e.g. an SSO app's SAML private key) before any row reaches the+ # warehouse. Redaction happens here, outside the paginators, so state checkpointing still runs+ # on the raw upstream response shape.+ if config.redact_keys:+ for page in pages:+ yield [_redact_row(row, config.redact_keys) for row in page]+ else:+ yield from pages+++def jumpcloud_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JumpcloudResumeConfig],+ org_id: str | None = None,+ region: str = "us",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = JUMPCLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ org_id=org_id,+ region=region,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[endpoint_config.primary_key],+ # Directory Insights doesn't document a guaranteed response ordering for the events+ # query, so "desc" keeps the incremental watermark safe: it's persisted once, as the+ # run's max, only after the whole window has been walked. The REST endpoints are+ # full refresh, where sort_mode has no watermark to corrupt.+ sort_mode="desc" if endpoint_config.api == "insights" else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/settings.pynew file mode 100644index 000000000000..af22451263bc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/settings.py@@ -0,0 +1,95 @@+from dataclasses import dataclass, field+from typing import Literal++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class JumpcloudEndpointConfig:+ name: str+ path: str+ # Which JumpCloud API family serves the endpoint:+ # "v1" -> console API, GET, response wrapped as {"totalCount", "results": [...]}+ # "v2" -> console API v2, GET, response is a bare JSON array+ # "insights" -> Directory Insights API, POST with a JSON query body, bare JSON array response+ api: Literal["v1", "v2", "insights"]+ # v1 resources use Mongo-style `_id`; v2 and Directory Insights use `id`.+ primary_key: str = "_id"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable, immutable field to partition by (creation/event time — never a mutating field).+ partition_key: str | None = None+ # Column to sort by while paginating. Sorting v1 list endpoints on the immutable `_id`+ # keeps limit/skip pagination stable as rows are inserted mid-sync. The v2 group+ # endpoints don't document a sort param, so they rely on the API's default ordering.+ sort: str | None = None+ # Fields to strip from every row before it's emitted, to keep secret-bearing fields out of+ # the warehouse where any table reader could see them. Each entry is a dotted path, so nested+ # fields can be redacted (e.g. `config.idpPrivateKey`); a bare name targets a top-level field.+ redact_keys: list[str] = field(default_factory=list)+++# Core directory resources plus the Directory Insights activity event log. The REST entity+# endpoints (users, systems, groups, applications) expose no server-side "updated since"+# filter, so they sync as full refresh. Directory Insights events accept a server-side+# start_time/end_time window, so that stream syncs incrementally on `timestamp`.+JUMPCLOUD_ENDPOINTS: dict[str, JumpcloudEndpointConfig] = {+ "users": JumpcloudEndpointConfig(+ name="users",+ path="/api/systemusers",+ api="v1",+ partition_key="created",+ sort="_id",+ ),+ "systems": JumpcloudEndpointConfig(+ name="systems",+ path="/api/systems",+ api="v1",+ partition_key="created",+ sort="_id",+ ),+ "user_groups": JumpcloudEndpointConfig(+ name="user_groups",+ path="/api/v2/usergroups",+ api="v2",+ primary_key="id",+ ),+ "system_groups": JumpcloudEndpointConfig(+ name="system_groups",+ path="/api/v2/systemgroups",+ api="v2",+ primary_key="id",+ ),+ "applications": JumpcloudEndpointConfig(+ name="applications",+ path="/api/applications",+ api="v1",+ # The application object documents no creation timestamp, so no datetime partitioning.+ sort="_id",+ # SSO application objects carry the SAML IdP signing key at `config.idpPrivateKey.value`.+ # Landing it in the warehouse would let any table reader forge assertions for apps that+ # trust it, so drop the whole private-key object before the row is emitted.+ redact_keys=["config.idpPrivateKey"],+ ),+ "events": JumpcloudEndpointConfig(+ name="events",+ path="/insights/directory/v1/events",+ api="insights",+ primary_key="id",+ # Events are immutable; their event time is the only sensible cursor and partition key.+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ ),+}++ENDPOINTS = tuple(JUMPCLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in JUMPCLOUD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/source.pyindex 8550a301b650..fea2c7af826e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/source.py@@ -1,30 +1,176 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import JumpcloudSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.jumpcloud import (+ JumpcloudResumeConfig,+ jumpcloud_source,+ validate_credentials as validate_jumpcloud_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ JUMPCLOUD_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class JumpcloudSource(SimpleSource[JumpcloudSourceConfig]):+class JumpcloudSource(ResumableSource[JumpcloudSourceConfig, JumpcloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.JUMPCLOUD+ @property+ def connection_host_fields(self) -> list[str]:+ # Both fields retarget the stored API key, so changing either forces secret re-entry:+ # `org_id` selects which organization the key acts on, and `region` selects which+ # regional JumpCloud host the key is sent to.+ return ["org_id", "region"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.JUMPCLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="JumpCloud",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your JumpCloud admin API key to sync your directory and activity data into the PostHog Data warehouse.++Find your API key in the JumpCloud Admin Portal: click your account initials in the top-right corner and select **My API Key**.++The `events` table requires a Directory Insights subscription. If you're an MSP/MTP admin managing multiple organizations, also enter the organization ID the key should act on.""",iconPath="/static/services/jumpcloud.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/jumpcloud",+ keywords=["iam", "sso", "directory insights"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (console.jumpcloud.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (console.eu.jumpcloud.com)", value="eu"),+ ],+ ),+ SourceFieldInputConfig(+ name="org_id",+ label="Organization ID (optional, MSP/MTP only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # An invalid or revoked API key surfaces as a requests HTTPError when `_request`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Matched on the stable status text only, since the host varies by region+ # and API family (console vs Directory Insights).+ return {+ "401 Client Error": "Your JumpCloud API key is invalid or has been revoked. Generate a new key in the JumpCloud Admin Portal (account menu → My API Key), then reconnect.",+ "403 Client Error": "Your JumpCloud API key does not have permission to read this data. Check the admin's role permissions (and Directory Insights subscription for the events table), then reconnect.",+ }++ def get_schemas(+ self,+ config: JumpcloudSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only Directory Insights events expose a server-side time filter (start_time), so+ # only that stream is incremental. Merge-only: the start_time boundary may re-return+ # the watermark row, and merge dedupes it on `id` where append would duplicate it.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=[JUMPCLOUD_ENDPOINTS[endpoint].primary_key],+ description=(+ "Directory Insights activity events (console, SSO, RADIUS, LDAP, systems, and directory changes). "+ "Only syncs the last 90 days on initial sync, bounded by your Directory Insights retention"+ if endpoint == "events"+ 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: JumpcloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_jumpcloud_credentials(config.api_key, config.org_id, config.region, schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JumpcloudResumeConfig]:+ return ResumableSourceManager[JumpcloudResumeConfig](inputs, JumpcloudResumeConfig)++ def source_for_pipeline(+ self,+ config: JumpcloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[JumpcloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return jumpcloud_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ org_id=config.org_id,+ region=config.region,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.pynew file mode 100644index 000000000000..2e5571efb62b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.py@@ -0,0 +1,433 @@+import json+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud import jumpcloud+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.jumpcloud import (+ EVENTS_PAGE_SIZE,+ REST_PAGE_SIZE,+ JumpcloudResumeConfig,+ JumpcloudRetryableError,+ _parse_search_after,+ get_rows,+ jumpcloud_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.settings import (+ ENDPOINTS,+ JUMPCLOUD_ENDPOINTS,+)+++class _FakeResumableManager:+ def __init__(self, state: JumpcloudResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[JumpcloudResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> JumpcloudResumeConfig | None:+ return self._state++ def save_state(self, data: JumpcloudResumeConfig) -> None:+ self.saved.append(data)+++def _response_with_status(status_code: int, body: bytes = b"", headers: dict[str, str] | None = None):+ response = requests.Response()+ response.status_code = status_code+ response._content = body+ response.headers.update(headers or {})+ return response+++class TestRequest:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_exhaust_retries(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.request.return_value = _response_with_status(status)+ # No-op the backoff sleep so the 5 attempts run instantly.+ with patch.object(jumpcloud._request.retry, "sleep", lambda *a, **k: None): # type: ignore[attr-defined]+ with pytest.raises(JumpcloudRetryableError):+ jumpcloud._request(session, "GET", "https://console.jumpcloud.com/api/systemusers", MagicMock())+ assert session.request.call_count == 5++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_http_error_without_retrying(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.request.return_value = _response_with_status(status)+ with pytest.raises(requests.HTTPError):+ jumpcloud._request(session, "GET", "https://console.jumpcloud.com/api/systemusers", MagicMock())+ assert session.request.call_count == 1++ def test_429_carries_server_retry_after(self) -> None:+ session = MagicMock()+ session.request.return_value = _response_with_status(429, headers={"Retry-After": "7"})+ with patch.object(jumpcloud._request.retry, "sleep", lambda *a, **k: None): # type: ignore[attr-defined]+ with pytest.raises(JumpcloudRetryableError) as exc_info:+ jumpcloud._request(session, "GET", "https://console.jumpcloud.com/api/systemusers", MagicMock())+ assert exc_info.value.retry_after == 7.0++ @parameterized.expand([("moved_permanently", 301), ("temporary_redirect", 307)])+ def test_redirects_are_rejected_not_followed(self, _name: str, status: int) -> None:+ # The session carries the API key in x-api-key; following a redirect would replay it+ # to the redirect target, so the request must refuse redirects entirely.+ session = MagicMock()+ session.request.return_value = _response_with_status(status, headers={"Location": "https://evil.example"})+ with pytest.raises(ValueError):+ jumpcloud._request(session, "GET", "https://console.jumpcloud.com/api/systemusers", MagicMock())+ assert session.request.call_args.kwargs["allow_redirects"] is False+++class TestParseSearchAfter:+ @parameterized.expand(+ [+ ("valid_cursor", json.dumps([1747608000000, "abc"]), [1747608000000, "abc"]),+ ("missing_header", None, None),+ ("empty_string", "", None),+ ("garbage", "not-json", None),+ ("non_array", '{"a": 1}', None),+ ("empty_array", "[]", None),+ ]+ )+ def test_parsing(self, _name: str, raw: str | None, expected: list[Any] | None) -> None:+ assert _parse_search_after(raw, MagicMock()) == expected+++class TestRestRows:+ @staticmethod+ def _collect(+ endpoint: str,+ pages: list[Any],+ manager: _FakeResumableManager,+ monkeypatch: Any,+ region: str = "us",+ ) -> tuple[list[dict], list[str]]:+ fetched_urls: list[str] = []++ def fake_request(session: Any, method: str, url: str, logger: Any, json_body: Any = None) -> Any:+ assert method == "GET"+ fetched_urls.append(url)+ skip = int(url.split("skip=")[1].split("&")[0])+ index = skip // REST_PAGE_SIZE+ page = pages[index] if index < len(pages) else []+ response = MagicMock()+ if JUMPCLOUD_ENDPOINTS[endpoint].api == "v1":+ response.json.return_value = {"totalCount": sum(len(p) for p in pages), "results": page}+ else:+ response.json.return_value = page+ return response++ monkeypatch.setattr(jumpcloud, "_request", fake_request)+ monkeypatch.setattr(jumpcloud, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for page in get_rows(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ region=region,+ ):+ rows.extend(page)+ return rows, fetched_urls++ def test_v1_short_page_stops_without_saving_state(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, urls = self._collect("users", [[{"_id": "a"}, {"_id": "b"}]], manager, monkeypatch)+ assert rows == [{"_id": "a"}, {"_id": "b"}]+ assert len(urls) == 1+ assert "sort=_id" in urls[0]+ assert manager.saved == []++ def test_v1_paginates_until_short_page_and_checkpoints_skip(self, monkeypatch: Any) -> None:+ full_page = [{"_id": str(i)} for i in range(REST_PAGE_SIZE)]+ manager = _FakeResumableManager()+ rows, urls = self._collect("users", [full_page, [{"_id": "last"}]], manager, monkeypatch)+ assert len(rows) == REST_PAGE_SIZE + 1+ assert len(urls) == 2+ # State is saved after the full page (pointing at the next offset), then we stop short.+ assert manager.saved == [JumpcloudResumeConfig(skip=REST_PAGE_SIZE)]++ def test_v1_resumes_from_saved_skip(self, monkeypatch: Any) -> None:+ full_page = [{"_id": str(i)} for i in range(REST_PAGE_SIZE)]+ manager = _FakeResumableManager(JumpcloudResumeConfig(skip=REST_PAGE_SIZE))+ rows, urls = self._collect("users", [full_page, [{"_id": "last"}]], manager, monkeypatch)+ # Resuming at skip=REST_PAGE_SIZE skips the already-synced first page.+ assert rows == [{"_id": "last"}]+ assert len(urls) == 1+ assert f"skip={REST_PAGE_SIZE}" in urls[0]++ def test_v2_bare_array_endpoint(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, urls = self._collect("user_groups", [[{"id": "g1"}]], manager, monkeypatch)+ assert rows == [{"id": "g1"}]+ assert urls[0].startswith("https://console.jumpcloud.com/api/v2/usergroups?")++ def test_eu_region_targets_eu_console(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ _, urls = self._collect("users", [[{"_id": "a"}]], manager, monkeypatch, region="eu")+ assert urls[0].startswith("https://console.eu.jumpcloud.com/")++ def test_applications_strips_saml_private_key_before_emitting(self, monkeypatch: Any) -> None:+ # An SSO application row carries its SAML IdP signing key at `config.idpPrivateKey.value`;+ # it must never reach the warehouse, while the rest of the config is kept.+ row = {+ "_id": "app1",+ "name": "Okta",+ "config": {+ "idpPrivateKey": {"value": "-----BEGIN PRIVATE KEY-----secret"},+ "idpEntityId": {"value": "https://idp.example"},+ },+ }+ manager = _FakeResumableManager()+ rows, _ = self._collect("applications", [[row]], manager, monkeypatch)+ assert rows == [+ {+ "_id": "app1",+ "name": "Okta",+ "config": {"idpEntityId": {"value": "https://idp.example"}},+ }+ ]++ @parameterized.expand([("applications", False), ("users", True)])+ def test_secret_bearing_endpoint_disables_http_sample_capture(self, endpoint: str, expected_capture: bool) -> None:+ # HTTP sample capture writes the raw response body before row-level `redact_keys` runs, so+ # endpoints that redact secrets (applications' SAML key) must opt out of capture entirely.+ capture_kwargs: list[Any] = []++ def fake_make_session(**kwargs: Any) -> Any:+ capture_kwargs.append(kwargs.get("capture"))+ return MagicMock()++ def fake_request(session: Any, method: str, url: str, logger: Any, json_body: Any = None) -> Any:+ response = MagicMock()+ response.json.return_value = {"results": []} if JUMPCLOUD_ENDPOINTS[endpoint].api == "v1" else []+ return response++ with (+ patch.object(jumpcloud, "_request", fake_request),+ patch.object(jumpcloud, "make_tracked_session", fake_make_session),+ ):+ list(+ get_rows(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert capture_kwargs == [expected_capture]++ def test_v1_non_wrapped_payload_raises_value_error(self, monkeypatch: Any) -> None:+ def fake_request(session: Any, method: str, url: str, logger: Any, json_body: Any = None) -> Any:+ response = MagicMock()+ response.json.return_value = [{"_id": "a"}] # bare list where v1 wraps in "results"+ return response++ monkeypatch.setattr(jumpcloud, "_request", fake_request)+ monkeypatch.setattr(jumpcloud, "make_tracked_session", lambda **kwargs: MagicMock())+ with pytest.raises(ValueError):+ list(+ get_rows(+ api_key="key",+ endpoint="users",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+++class TestEventRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: list[tuple[list[dict], str | None]],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict], list[dict]]:+ request_bodies: list[dict] = []+ call_index = 0++ def fake_request(session: Any, method: str, url: str, logger: Any, json_body: Any = None) -> Any:+ nonlocal call_index+ assert method == "POST"+ assert url.endswith("/insights/directory/v1/events")+ request_bodies.append(json_body)+ page, search_after_header = pages[call_index] if call_index < len(pages) else ([], None)+ call_index += 1+ response = MagicMock()+ response.json.return_value = page+ response.headers = {"X-Search_After": search_after_header} if search_after_header else {}+ return response++ monkeypatch.setattr(jumpcloud, "_request", fake_request)+ monkeypatch.setattr(jumpcloud, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for page in get_rows(+ api_key="key",+ endpoint="events",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(page)+ return rows, request_bodies++ @freeze_time("2026-07-15T12:00:00Z")+ def test_first_sync_queries_the_90_day_retention_window(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ _, bodies = self._collect(manager, monkeypatch, [([{"id": "e1"}], None)])+ assert bodies == [+ {+ "service": ["all"],+ "start_time": "2026-04-16T12:00:00Z",+ "end_time": "2026-07-15T12:00:00Z",+ "limit": EVENTS_PAGE_SIZE,+ }+ ]++ @freeze_time("2026-07-15T12:00:00Z")+ def test_incremental_sync_starts_at_the_watermark(self, monkeypatch: Any) -> None:+ from datetime import UTC, datetime++ manager = _FakeResumableManager()+ _, bodies = self._collect(+ manager,+ monkeypatch,+ [([{"id": "e1"}], None)],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 10, 8, 30, tzinfo=UTC),+ )+ assert bodies[0]["start_time"] == "2026-07-10T08:30:00Z"+ assert bodies[0]["end_time"] == "2026-07-15T12:00:00Z"++ def test_follows_search_after_cursor_and_checkpoints_after_yield(self, monkeypatch: Any) -> None:+ full_page = [{"id": str(i)} for i in range(EVENTS_PAGE_SIZE)]+ cursor = [1747608000000, "evt"]+ manager = _FakeResumableManager()+ rows, bodies = self._collect(manager, monkeypatch, [(full_page, json.dumps(cursor)), ([{"id": "last"}], None)])+ assert len(rows) == EVENTS_PAGE_SIZE + 1+ # First request has no cursor; the second carries the header cursor back in the body.+ assert "search_after" not in bodies[0]+ assert bodies[1]["search_after"] == cursor+ # Both pages of one run query the identical pinned window (search_after requires it).+ assert bodies[1]["start_time"] == bodies[0]["start_time"]+ assert bodies[1]["end_time"] == bodies[0]["end_time"]+ assert manager.saved == [+ JumpcloudResumeConfig(+ search_after=cursor, start_time=bodies[0]["start_time"], end_time=bodies[0]["end_time"]+ )+ ]++ def test_full_page_without_search_after_header_terminates(self, monkeypatch: Any) -> None:+ # A full page whose response lacks the cursor header must stop rather than loop on page one.+ full_page = [{"id": str(i)} for i in range(EVENTS_PAGE_SIZE)]+ manager = _FakeResumableManager()+ rows, bodies = self._collect(manager, monkeypatch, [(full_page, None)])+ assert len(rows) == EVENTS_PAGE_SIZE+ assert len(bodies) == 1++ def test_resumes_with_saved_window_and_cursor(self, monkeypatch: Any) -> None:+ cursor = [123, "evt"]+ manager = _FakeResumableManager(+ JumpcloudResumeConfig(+ search_after=cursor, start_time="2026-07-01T00:00:00Z", end_time="2026-07-14T00:00:00Z"+ )+ )+ _, bodies = self._collect(manager, monkeypatch, [([{"id": "e2"}], None)])+ assert bodies[0]["search_after"] == cursor+ assert bodies[0]["start_time"] == "2026-07-01T00:00:00Z"+ assert bodies[0]["end_time"] == "2026-07-14T00:00:00Z"++ def test_non_list_payload_raises_value_error(self, monkeypatch: Any) -> None:+ def fake_request(session: Any, method: str, url: str, logger: Any, json_body: Any = None) -> Any:+ response = MagicMock()+ response.json.return_value = {"error": "unexpected"}+ response.headers = {}+ return response++ monkeypatch.setattr(jumpcloud, "_request", fake_request)+ monkeypatch.setattr(jumpcloud, "make_tracked_session", lambda **kwargs: MagicMock())+ with pytest.raises(ValueError):+ list(+ get_rows(+ api_key="key",+ endpoint="events",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("bad_key", 401, None, False),+ # A 403 at source-create means the key is real but this probe is out of the admin's+ # role — creation must go through.+ ("forbidden_at_create", 403, None, True),+ ("forbidden_for_schema", 403, "users", False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ session = MagicMock()+ session.get.return_value = _response_with_status(status, body=b"{}")+ with patch.object(jumpcloud, "_make_session", return_value=session):+ ok, _error = validate_credentials("key", schema_name=schema_name)+ assert ok is expected_ok++ def test_events_schema_probes_the_insights_endpoint(self) -> None:+ session = MagicMock()+ session.post.return_value = _response_with_status(200)+ with patch.object(jumpcloud, "_make_session", return_value=session):+ ok, _error = validate_credentials("key", schema_name="events")+ assert ok is True+ url = session.post.call_args.args[0]+ assert url == "https://api.jumpcloud.com/insights/directory/v1/events"+ assert session.post.call_args.kwargs["json"]["limit"] == 1++ def test_connection_error_returns_message(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(jumpcloud, "_make_session", return_value=session):+ ok, error = validate_credentials("key")+ assert ok is False+ assert error is not None+++class TestJumpcloudSourceResponse:+ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_source_response_shape(self, name: str) -> None:+ response = jumpcloud_source(+ api_key="key",+ endpoint=name,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ config = JUMPCLOUD_ENDPOINTS[name]+ assert response.name == name+ assert response.primary_keys == [config.primary_key]+ # Directory Insights response ordering is undocumented, so the events stream defers+ # its watermark to job end (desc); everything else is plain ascending full refresh.+ assert response.sort_mode == ("desc" if config.api == "insights" else "asc")+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None++ def test_partition_keys_are_stable_fields(self) -> None:+ # Guards against accidentally partitioning on a churning field like lastContact.+ assert all(cfg.partition_key in (None, "created", "timestamp") for cfg in JUMPCLOUD_ENDPOINTS.values())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud_source.pynew file mode 100644index 000000000000..abd063ccdf22--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud_source.py@@ -0,0 +1,202 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.jumpcloud import JumpcloudResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.source import JumpcloudSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "key", org_id: str | None = None, region: str = "us") -> Any:+ config = MagicMock()+ config.api_key = api_key+ config.org_id = org_id+ config.region = region+ return config+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert JumpcloudSource().source_type == ExternalDataSourceType.JUMPCLOUD++ def test_config_is_visible_and_alpha(self) -> None:+ config = JumpcloudSource().get_source_config+ # A finished source must not be hidden from users.+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/jumpcloud"++ def test_fields(self) -> None:+ fields = {f.name: f for f in JumpcloudSource().get_source_config.fields}+ assert set(fields) == {"api_key", "region", "org_id"}++ api_key = fields["api_key"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.secret is True++ region = fields["region"]+ assert isinstance(region, SourceFieldSelectConfig)+ assert region.defaultValue == "us"+ assert {option.value for option in region.options} == {"us", "eu"}++ org_id = fields["org_id"]+ assert isinstance(org_id, SourceFieldInputConfig)+ assert org_id.required is False+ assert org_id.secret is False++ def test_connection_host_fields_force_secret_reentry_on_retarget(self) -> None:+ # Changing org_id or region retargets the stored API key (different organization's+ # data, or a different regional host), so both must force re-entering the key.+ assert JumpcloudSource().connection_host_fields == ["org_id", "region"]+++class TestGetSchemas:+ def test_only_events_is_incremental(self) -> None:+ schemas = {s.name: s for s in JumpcloudSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ assert schemas["events"].supports_incremental is True+ assert [f["field"] for f in schemas["events"].incremental_fields] == ["timestamp"]+ # The start_time boundary can re-return the watermark row, so append would duplicate it.+ assert all(not s.supports_append for s in schemas.values())+ # The REST entity endpoints have no server-side "updated since" filter.+ assert all(not schema.supports_incremental for name, schema in schemas.items() if name != "events")++ def test_primary_keys_follow_api_family(self) -> None:+ schemas = {s.name: s for s in JumpcloudSource().get_schemas(_config(), team_id=1)}+ # v1 resources use Mongo-style `_id`; v2 groups and Insights events use `id`.+ assert schemas["users"].detected_primary_keys == ["_id"]+ assert schemas["user_groups"].detected_primary_keys == ["id"]+ assert schemas["events"].detected_primary_keys == ["id"]++ def test_names_filter(self) -> None:+ schemas = JumpcloudSource().get_schemas(_config(), team_id=1, names=["users", "events"])+ assert {s.name for s in schemas} == {"users", "events"}++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O) — public docs render the table list.+ assert JumpcloudSource.lists_tables_without_credentials is True+ tables = JumpcloudSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ events = next(t for t in tables if t["name"] == "events")+ assert "Incremental" in events["sync_methods"]+++class TestValidateCredentials:+ def test_plumbs_config_and_schema_name(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.source.validate_jumpcloud_credentials",+ return_value=(True, None),+ ) as mocked:+ ok, error = JumpcloudSource().validate_credentials(+ _config(org_id="org1", region="eu"), team_id=1, schema_name="systems"+ )+ assert ok is True+ assert error is None+ mocked.assert_called_once_with("key", "org1", "eu", "systems")++ def test_failure_is_propagated(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.source.validate_jumpcloud_credentials",+ return_value=(False, "Invalid JumpCloud API key"),+ ):+ ok, error = JumpcloudSource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert error == "Invalid JumpCloud API key"+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = JumpcloudSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is JumpcloudResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "events"+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-07-01T00:00:00Z"+ manager = MagicMock()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.source.jumpcloud_source"+ ) as mocked:+ JumpcloudSource().source_for_pipeline(_config(org_id="org1", region="eu"), manager, inputs)+ mocked.assert_called_once_with(+ api_key="key",+ endpoint="events",+ logger=inputs.logger,+ resumable_source_manager=manager,+ org_id="org1",+ region="eu",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01T00:00:00Z",+ )++ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "users"+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-07-01T00:00:00Z"+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.jumpcloud.source.jumpcloud_source"+ ) as mocked:+ JumpcloudSource().source_for_pipeline(_config(), MagicMock(), inputs)+ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized_console",+ "401 Client Error: Unauthorized for url: https://console.jumpcloud.com/api/systemusers?limit=100",+ ),+ (+ "forbidden_insights",+ "403 Client Error: Forbidden for url: https://api.jumpcloud.com/insights/directory/v1/events",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = JumpcloudSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='console.jumpcloud.com', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://console.jumpcloud.com/api/systems",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://console.jumpcloud.com/api/systemusers",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = JumpcloudSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestCanonicalDescriptions:+ def test_canonical_descriptions_keys_are_known_endpoints(self) -> None:+ # Every documented table must map to a real endpoint, or its descriptions never apply.+ assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))++ def test_source_exposes_canonical_descriptions(self) -> None:+ assert JumpcloudSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS