: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 jamf_pro import source (#71219)
Tom Owers5411eedd1067
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ce8dab58e011..31f324c03c4e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -275,6 +275,7 @@ the row lists both.| invoiceninja | HTTP | requests | ✅ || ip2whois | HTTP | requests | ✅ || iterable | HTTP | requests | ✅ |+| jamf_pro | HTTP | requests | ✅ || jellyfish | HTTP | requests | ✅ || jira | HTTP | requests | ✅ || jobnimbus | HTTP | requests | ✅ |@@ -744,7 +745,6 @@ doesn't conflict with concurrent PRs.- instantly- interzoid-- jamf_pro- jenkins- jfrog_artifactory- jobberdiff --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 bb5629acd3d5..c862e93e9e54 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@@ -93,6 +93,15 @@ class HubspotCustomPropertiesConfig(config.Config):meetings_properties: str | None = None+class JamfProAuthMethodConfig(config.Config):+ selection: Literal["client_credentials", "basic"] = "client_credentials"+ client_id: str | None = None+ client_secret: str | None = None+ username: str | None = None+ password: str | None = None++@config.configclass MetabaseAuthMethodConfig(config.Config):selection: Literal["api_key", "session"] = "api_key"@@ -2210,7 +2219,8 @@ class IterableSourceConfig(config.Config):@config.configclass JamfProSourceConfig(config.Config):- pass+ instance_url: str+ auth_method: JamfProAuthMethodConfig@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/canonical_descriptions.pynew file mode 100644index 000000000000..0f231b6e8407--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/canonical_descriptions.py@@ -0,0 +1,120 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "computers": {+ "description": "Inventory record for each managed computer, including general, hardware, operating system, user and location, security, disk encryption, purchasing, storage, and group membership sections.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-computers-inventory",+ "columns": {+ "id": "Unique identifier of the computer in Jamf Pro.",+ "udid": "Unique device identifier (UDID) of the computer.",+ "report_date": "Timestamp of the most recent inventory submission, copied from general.reportDate.",+ "general": "General inventory section: name, last contact time, report date, enrollment details, management state, and remote management settings.",+ "hardware": "Hardware inventory section: model, model identifier, serial number, processor, memory, and network adapters.",+ "operatingSystem": "Operating system inventory section: name, version, build, and software update status.",+ "userAndLocation": "Assigned user and location details: username, real name, email, position, department, and building.",+ "security": "Security inventory section: SIP status, Gatekeeper status, XProtect version, firewall, and Activation Lock state.",+ "diskEncryption": "FileVault disk encryption state, including boot partition encryption details and recovery key validity.",+ "purchasing": "Purchasing information: PO number, vendor, warranty, lease, and applecare details.",+ "storage": "Storage inventory section: disks, partitions, and available space.",+ "groupMemberships": "Smart and static computer groups the computer is a member of.",+ },+ },+ "mobile_devices": {+ "description": "Managed mobile devices (iPhone, iPad, Apple TV) with their identity fields.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-mobile-devices",+ "columns": {+ "id": "Unique identifier of the mobile device in Jamf Pro.",+ "name": "Display name of the device.",+ "serialNumber": "Hardware serial number of the device.",+ "udid": "Unique device identifier (UDID) of the device.",+ "wifiMacAddress": "Wi-Fi MAC address of the device.",+ "phoneNumber": "Phone number assigned to the device, if any.",+ "model": "Human-readable device model (e.g. iPad Pro).",+ "modelIdentifier": "Apple model identifier (e.g. iPad8,9).",+ "username": "Username of the user assigned to the device.",+ "type": "Device type (e.g. ios, tvos).",+ "managementId": "Management identifier used by the MDM protocol.",+ },+ },+ "buildings": {+ "description": "Buildings defined in Jamf Pro, used to organize devices and users by physical location.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-buildings",+ "columns": {+ "id": "Unique identifier of the building.",+ "name": "Name of the building.",+ "streetAddress1": "First street address line.",+ "streetAddress2": "Second street address line.",+ "city": "City of the building.",+ "stateProvince": "State or province of the building.",+ "zipPostalCode": "ZIP or postal code of the building.",+ "country": "Country of the building.",+ },+ },+ "departments": {+ "description": "Departments defined in Jamf Pro, used to organize devices and users organizationally.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-departments",+ "columns": {+ "id": "Unique identifier of the department.",+ "name": "Name of the department.",+ },+ },+ "categories": {+ "description": "Categories used to organize policies, packages, scripts, and configuration profiles in Jamf Pro.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-categories",+ "columns": {+ "id": "Unique identifier of the category.",+ "name": "Name of the category.",+ "priority": "Display priority of the category in Self Service.",+ },+ },+ "sites": {+ "description": "Sites defined in Jamf Pro, used to segment devices, users, and settings across organizational units.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-sites",+ "columns": {+ "id": "Unique identifier of the site.",+ "name": "Name of the site.",+ },+ },+ "computer_groups": {+ "description": "Smart and static computer groups defined in Jamf Pro.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-computer-groups",+ "columns": {+ "id": "Unique identifier of the computer group.",+ "name": "Name of the computer group.",+ "smartGroup": "Whether the group is a smart group (criteria-based) rather than a static group.",+ },+ },+ "scripts": {+ "description": "Scripts stored in Jamf Pro for use in policies, including their full contents.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-scripts",+ "columns": {+ "id": "Unique identifier of the script.",+ "name": "Name of the script.",+ "info": "Information text shown for the script.",+ "notes": "Notes about the script.",+ "priority": "Execution priority relative to other actions in a policy (BEFORE, AFTER, AT_REBOOT).",+ "categoryId": "Identifier of the category the script belongs to.",+ "categoryName": "Name of the category the script belongs to.",+ "osRequirements": "Operating system requirements for the script to run.",+ "scriptContents": "Full contents of the script.",+ },+ },+ "packages": {+ "description": "Software packages stored in Jamf Pro for distribution to managed devices.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-packages",+ "columns": {+ "id": "Unique identifier of the package.",+ "packageName": "Display name of the package.",+ "fileName": "File name of the package on the distribution point.",+ "categoryId": "Identifier of the category the package belongs to.",+ "info": "Information text shown for the package.",+ "notes": "Notes about the package.",+ "priority": "Installation priority relative to other packages.",+ "size": "Size of the package file in bytes.",+ "md5": "MD5 checksum of the package file.",+ "sha256": "SHA-256 checksum of the package file.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.pynew file mode 100644index 000000000000..0d2b72b7dd0f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.py@@ -0,0 +1,523 @@+import re+import json+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Literal, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import 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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.settings import (+ JAMF_PRO_ENDPOINTS,+ JamfProEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5++# The instance URL is customer-controlled, so a hostile or misconfigured server could return an+# arbitrarily large (or endlessly streaming) body. `requests` buffers a non-streamed response whole+# into a shared worker's memory before `.json()` runs, so every response is read with `stream=True`+# and capped at this many decompressed bytes. Jamf's largest legitimate page — 100 computers-inventory+# rows with every requested section — is a few MiB, so this leaves generous headroom.+MAX_RESPONSE_BYTES = 100 * 1024 * 1024+_RESPONSE_CHUNK_BYTES = 64 * 1024+# Only a bounded prefix of an error body is read for logging, so a hostile server can't exhaust+# memory through the error path either.+_ERROR_BODY_PREVIEW_BYTES = 2 * 1024+# Wall-clock budget for downloading one response body. `requests`' timeout only bounds each+# individual socket read, so a host that dribbles the body one byte at a time under the read timeout+# could hold the connection (and a shared worker) open indefinitely while staying under+# MAX_RESPONSE_BYTES. This caps total transfer time — 100 MiB in 300s is a ~0.34 MiB/s floor, far+# below any real API response and far above a slow-drip stall.+MAX_DOWNLOAD_SECONDS = 300++# A misbehaving or hostile server can return a non-empty `results` page forever while omitting or+# inflating `totalCount`, pinning the (up to week-long) resumable activity in an endless fetch loop.+# Cap the highest page we will ever fetch for one endpoint. At 100-200 rows per page this is far+# more than any real Jamf tenant holds, so it only ever trips on a server that never terminates.+MAX_PAGES = 50_000++# Jamf Pro bearer tokens are short-lived (~20 minutes for basic-auth tokens; OAuth tokens report+# their own expires_in). Re-mint this many seconds before the deadline so a request never rides+# a token that expires mid-flight.+TOKEN_REFRESH_MARGIN_SECONDS = 60+DEFAULT_TOKEN_LIFETIME_SECONDS = 15 * 60++HOST_NOT_ALLOWED_ERROR = "Jamf Pro URL is not allowed"+INCOMPLETE_CREDENTIALS_ERROR = "Jamf Pro credentials are incomplete"+++class JamfProRetryableError(Exception):+ pass+++class JamfProHostNotAllowedError(Exception):+ pass+++class JamfProConfigurationError(Exception):+ pass+++class JamfProResponseTooLargeError(Exception):+ pass+++class JamfProResponseTooSlowError(Exception):+ pass+++class JamfProPaginationLimitError(Exception):+ pass+++def _read_capped_json(response: requests.Response) -> Any:+ """Parse a streamed JSON response, refusing a body past ``MAX_RESPONSE_BYTES`` or ``MAX_DOWNLOAD_SECONDS``.++ The host is customer-controlled, so a body must never be buffered unbounded (size cap) nor be+ allowed to hold the connection open indefinitely by dribbling under the per-read timeout (time+ cap). ``iter_content`` decodes any content-encoding, so the size cap bounds the decompressed+ body and a compressed one can't slip past it. Both caps are non-retryable — re-fetching the same+ page yields the same oversized/slow body. The response is always closed, so an aborted read+ doesn't leak the connection.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise JamfProResponseTooSlowError(+ f"Jamf Pro response exceeded the {MAX_DOWNLOAD_SECONDS}s download budget; aborting"+ )+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise JamfProResponseTooLargeError(+ f"Jamf Pro response exceeded the {MAX_RESPONSE_BYTES}-byte limit; refusing to buffer it"+ )+ chunks.append(chunk)+ finally:+ response.close()+ return json.loads(b"".join(chunks))+++def _read_body_preview(response: requests.Response) -> str:+ """Read a bounded prefix of a streamed body for error logging, never buffering it whole.++ Bounded by both the preview size and the wall-clock budget so a slow-dribbling error body can't+ stall the log path either.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ break+ if not chunk:+ continue+ chunks.append(chunk)+ total += len(chunk)+ if total >= _ERROR_BODY_PREVIEW_BYTES:+ break+ return b"".join(chunks)[:_ERROR_BODY_PREVIEW_BYTES].decode("utf-8", errors="replace")+++class JamfProResumeConfig:+ # Zero-based page index to fetch next. Query params are rebuilt deterministically from the+ # schema inputs on resume, so the page number is the only state we need.+ page: int+++class JamfProCredentials:+ method: Literal["client_credentials", "basic"]+ client_id: str | None = None+ client_secret: str | None = None+ username: str | None = None+ password: str | None = None+++def normalize_host(host: str) -> str:+ """Turn whatever the user typed into a bare Jamf Pro host.++ Accepts values like ``company.jamfcloud.com``, ``https://company.jamfcloud.com/``,+ or ``company.jamfcloud.com/api`` and returns ``company.jamfcloud.com``.+ """+ host = host.strip()+ host = re.sub(r"^https?://", "", host, flags=re.IGNORECASE)+ host = host.split("/")[0]+ return host.strip().rstrip("/")+++def _base_url(host: str) -> str:+ return f"https://{normalize_host(host)}"+++def _format_datetime_z(dt: datetime) -> str:+ """Jamf Pro stores instants as ISO 8601 with millisecond precision and a ``Z`` suffix."""+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _format_incremental_value(value: Any) -> str:+ if isinstance(value, datetime):+ return _format_datetime_z(value)+ if isinstance(value, date):+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++class JamfProTokenManager:+ """Mints and caches the short-lived bearer token, re-minting before it expires.++ Supports the two Jamf Pro auth paths: OAuth2 client credentials (API Roles & Clients,+ ``POST /api/oauth/token``) and a user account over HTTP Basic (``POST /api/v1/auth/token``).+ """++ def __init__(self, session: requests.Session, host: str, credentials: JamfProCredentials) -> None:+ self._session = session+ self._base_url = _base_url(host)+ self._credentials = credentials+ self._token: str | None = None+ self._deadline: float = 0.0++ def get_token(self) -> str:+ if self._token is None or time.monotonic() >= self._deadline - TOKEN_REFRESH_MARGIN_SECONDS:+ self._mint()+ assert self._token is not None+ return self._token++ def _mint(self) -> None:+ response = self._request_token()++ try:+ if response.status_code == 429 or response.status_code >= 500:+ raise JamfProRetryableError(f"Jamf Pro token request failed (retryable): status={response.status_code}")++ # A 3xx isn't an error status, so reject it explicitly rather than following it to a+ # potentially internal Location (SSRF).+ if response.is_redirect or response.is_permanent_redirect:+ raise JamfProHostNotAllowedError(+ f"Jamf Pro API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ response.raise_for_status()+ # The token endpoint is customer-controlled too — cap its body like any other response.+ payload = _read_capped_json(response)+ finally:+ response.close()++ if self._credentials.method == "client_credentials":+ self._token = payload["access_token"]+ lifetime = float(payload.get("expires_in") or DEFAULT_TOKEN_LIFETIME_SECONDS)+ else:+ self._token = payload["token"]+ lifetime = self._lifetime_from_expiry(payload.get("expires"))++ self._deadline = time.monotonic() + lifetime++ def _request_token(self) -> requests.Response:+ if self._credentials.method == "client_credentials":+ if not self._credentials.client_id or not self._credentials.client_secret:+ raise JamfProConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: client ID and client secret required")+ return self._session.post(+ f"{self._base_url}/api/oauth/token",+ data={+ "grant_type": "client_credentials",+ "client_id": self._credentials.client_id,+ "client_secret": self._credentials.client_secret,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )++ if not self._credentials.username or not self._credentials.password:+ raise JamfProConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: username and password required")+ return self._session.post(+ f"{self._base_url}/api/v1/auth/token",+ auth=(self._credentials.username, self._credentials.password),+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )++ @staticmethod+ def _lifetime_from_expiry(expires: str | None) -> float:+ if not expires:+ return DEFAULT_TOKEN_LIFETIME_SECONDS+ try:+ expiry = datetime.fromisoformat(expires.replace("Z", "+00:00"))+ except ValueError:+ return DEFAULT_TOKEN_LIFETIME_SECONDS+ return max((expiry - datetime.now(UTC)).total_seconds(), 0.0)+++def _build_params(+ config: JamfProEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"page-size": config.page_size}++ sort = config.sort+ if should_use_incremental_field and config.rsql_incremental_field:+ if config.incremental_sort:+ sort = config.incremental_sort+ if db_incremental_field_last_value:+ formatted = _format_incremental_value(db_incremental_field_last_value)+ # RSQL >= re-pulls the boundary row; merge dedupes it on the primary key. The value is+ # double-quoted because RSQL treats bare colons in timestamps as reserved characters.+ params["filter"] = f'{config.rsql_incremental_field}>="{formatted}"'++ if sort:+ params["sort"] = sort+ if config.sections:+ params["section"] = config.sections++ return params+++def _build_url(host: str, config: JamfProEndpointConfig, params: dict[str, Any]) -> str:+ url = f"{_base_url(host)}{config.path}"+ if not params:+ return url+ return f"{url}?{urlencode(params, doseq=True)}"+++def _hoist_cursor(config: JamfProEndpointConfig, row: dict[str, Any]) -> dict[str, Any]:+ """Copy the nested incremental cursor to a top-level column.++ The pipeline reads the watermark from a top-level column of the yielded rows, but Jamf+ nests its timestamps (e.g. ``general.reportDate``), so incremental endpoints expose the+ cursor under ``default_incremental_field`` as well.+ """+ if not (config.default_incremental_field and config.rsql_incremental_field):+ return row+ value: Any = row+ for part in config.rsql_incremental_field.split("."):+ value = value.get(part) if isinstance(value, dict) else None+ return {**row, config.default_incremental_field: value}+++def validate_credentials(+ host: str, credentials: JamfProCredentials, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Mint a bearer token to confirm the credentials are genuine.++ Jamf Pro grants privileges per resource, so a valid API client may legitimately lack access+ to endpoints the user never intends to sync — at source-create (``schema_name is None``) a+ successful token mint is enough. A scoped probe (``schema_name`` set) additionally requests+ the endpoint and treats 403 as a hard failure.+ """+ try:+ normalized = normalize_host(host)+ except Exception:+ return False, "Invalid Jamf Pro URL"++ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):+ return False, "Invalid Jamf Pro URL"++ # The host is fully customer-controlled (jamfcloud.com or self-hosted), so block hosts that+ # resolve to private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(normalized, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ # capture=False keeps the minted bearer token (returned in the response body) and any probed+ # row content out of opt-in HTTP sample capture — the name-based scrubbers can't recognise them.+ session = make_tracked_session(capture=False)+ token_manager = JamfProTokenManager(session, normalized, credentials)+ try:+ token = token_manager.get_token()+ except JamfProConfigurationError as e:+ return False, str(e)+ except JamfProHostNotAllowedError:+ return False, HOST_NOT_ALLOWED_ERROR+ except requests.HTTPError as e:+ if e.response is not None and e.response.status_code == 401:+ return False, "Invalid Jamf Pro credentials"+ return False, str(e)+ except (JamfProRetryableError, requests.exceptions.RequestException) as e:+ return False, str(e)++ if schema_name is None:+ return True, None++ config = JAMF_PRO_ENDPOINTS[schema_name]+ probe_params = {"page": 0, "page-size": 1} if config.paginated else {}+ try:+ # Stream and close without touching the body — the probe only needs the status. This keeps+ # a customer-controlled server from buffering an unbounded body into memory at source-create.+ response = session.get(+ _build_url(normalized, config, probe_params),+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},+ timeout=10,+ allow_redirects=False,+ stream=True,+ )+ try:+ is_redirect = response.is_redirect or response.is_permanent_redirect+ status_code = response.status_code+ finally:+ response.close()+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if is_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if status_code == 200:+ return True, None++ if status_code == 403:+ return False, f"Your Jamf Pro API client lacks the read privilege for {schema_name}"++ return False, f"Jamf Pro API returned status {status_code} for {schema_name}"+++def get_rows(+ host: str,+ credentials: JamfProCredentials,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JamfProResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = JAMF_PRO_ENDPOINTS[endpoint]++ # Re-check at run time (not just at source-create) in case the URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(normalize_host(host), team_id)+ if not host_ok:+ raise JamfProHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ # Token responses carry the bearer credential in the body, which the name-based sample+ # scrubbers can't recognise — keep auth exchanges out of sample capture entirely. The data+ # session is reused across every page so urllib3 keeps the connection alive; Jamf recommends+ # few concurrent connections rather than many short-lived ones.+ token_manager = JamfProTokenManager(make_tracked_session(capture=False), host, credentials)+ session = make_tracked_session(capture=config.capture_samples)++ @retry(+ retry=retry_if_exception_type((JamfProRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_url: str) -> Any:+ # get_token() inside the retry scope so an expired token or transient mint failure is+ # retried along with the page itself.+ headers = {"Authorization": f"Bearer {token_manager.get_token()}", "Accept": "application/json"}+ # stream=True so _read_capped_json bounds the body instead of `requests` buffering it whole.+ response = session.get(+ page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True+ )++ try:+ # Jamf has no server-side rate limiting or Retry-After headers; it recommends adaptive+ # backoff instead, which the exponential jitter above provides.+ if response.status_code == 429 or response.status_code >= 500:+ raise JamfProRetryableError(+ f"Jamf Pro API error (retryable): status={response.status_code}, url={page_url}"+ )++ if response.is_redirect or response.is_permanent_redirect:+ raise JamfProHostNotAllowedError(+ f"Jamf Pro API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ body = _read_body_preview(response)+ logger.error(f"Jamf Pro API error: status={response.status_code}, body={body}, url={page_url}")+ response.raise_for_status()++ return _read_capped_json(response)+ finally:+ response.close()++ if not config.paginated:+ data = fetch_page(_build_url(host, config, {}))+ rows = data if isinstance(data, list) else data.get("results", [])+ if rows:+ yield [_hoist_cursor(config, row) for row in rows]+ return++ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume_config.page if resume_config is not None else 0+ if resume_config is not None:+ logger.debug(f"Jamf Pro: resuming {endpoint} from page {page}")++ while True:+ # A server that never signals termination (non-empty results, missing/inflated totalCount)+ # would otherwise loop until the activity's week-long timeout — bound the page count. The+ # check is on the absolute page index so it holds across resumes, not just per run.+ if page >= MAX_PAGES:+ raise JamfProPaginationLimitError(+ f"Jamf Pro pagination for {endpoint} exceeded {MAX_PAGES} pages without terminating"+ )++ data = fetch_page(_build_url(host, config, {**params, "page": page}))++ results = data.get("results", [])+ if not results:+ break++ yield [_hoist_cursor(config, row) for row in results]++ total_count = data.get("totalCount")+ if total_count is not None and (page + 1) * config.page_size >= total_count:+ break++ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(JamfProResumeConfig(page=page + 1))+ page += 1+++def jamf_pro_source(+ host: str,+ credentials: JamfProCredentials,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JamfProResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = JAMF_PRO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ credentials=credentials,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[endpoint_config.primary_key],+ # Incremental runs request sort=general.reportDate:asc so the watermark can checkpoint+ # per batch; full refreshes sort by id for stable page boundaries.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/settings.pynew file mode 100644index 000000000000..7b2d52c0c2d8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/settings.py@@ -0,0 +1,122 @@+from dataclasses import dataclass, field+from typing import 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.DateTime,+ }+++# The computers-inventory endpoint returns only the GENERAL section unless asked for more.+# This curated set covers the fields device-inventory reporting actually uses while leaving+# out the unbounded per-device lists (APPLICATIONS, CERTIFICATES, FONTS, ...) that would blow+# up row size on large fleets.+COMPUTERS_INVENTORY_SECTIONS = [+ "GENERAL",+ "HARDWARE",+ "OPERATING_SYSTEM",+ "USER_AND_LOCATION",+ "SECURITY",+ "DISK_ENCRYPTION",+ "PURCHASING",+ "STORAGE",+ "GROUP_MEMBERSHIPS",+]+++@dataclass+class JamfProEndpointConfig:+ name: str+ path: str+ # Jamf Pro API collection endpoints return {"totalCount": N, "results": [...]} and take+ # page / page-size / sort. A few (sites, computer-groups) return a plain JSON array.+ paginated: bool = True+ page_size: int = 200+ primary_key: str = "id"+ # Explicit sort keeps page boundaries stable while paginating a full refresh.+ sort: Optional[str] = "id:asc"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # RSQL field used to build the server-side incremental filter (e.g. general.reportDate).+ # Only set when the endpoint documents RSQL filtering on a timestamp.+ rsql_incremental_field: Optional[str] = None+ # Column name the incremental cursor is exposed under in the yielded rows. The pipeline+ # reads the watermark from a top-level column, so nested API fields get hoisted to this.+ default_incremental_field: Optional[str] = None+ # Sort applied on incremental runs so rows arrive in ascending cursor order and the+ # watermark can checkpoint per batch.+ incremental_sort: Optional[str] = None+ # Repeated `section=` values (computers-inventory only).+ sections: list[str] = field(default_factory=list)+ # Whether responses may enter opt-in HTTP sample capture. Disabled for endpoints whose+ # bodies carry arbitrary customer content the name-based scrubbers can't recognise.+ capture_samples: bool = True+++JAMF_PRO_ENDPOINTS: dict[str, JamfProEndpointConfig] = {+ # Computer inventory is the only Jamf Pro collection that documents RSQL filtering on a+ # timestamp (general.reportDate advances on every inventory submission), so it is the only+ # incremental-capable table. The nested cursor is hoisted to a top-level `report_date`+ # column in the transport.+ "computers": JamfProEndpointConfig(+ name="computers",+ path="/api/v1/computers-inventory",+ page_size=100,+ rsql_incremental_field="general.reportDate",+ default_incremental_field="report_date",+ incremental_sort="general.reportDate:asc",+ incremental_fields=[_datetime_incremental_field("report_date")],+ sections=COMPUTERS_INVENTORY_SECTIONS,+ ),+ # The v2 mobile devices list carries identity fields only (no timestamps), so it is+ # full-refresh only. The richer /detail inventory endpoint is a follow-up.+ "mobile_devices": JamfProEndpointConfig(+ name="mobile_devices",+ path="/api/v2/mobile-devices",+ ),+ "buildings": JamfProEndpointConfig(+ name="buildings",+ path="/api/v1/buildings",+ ),+ "departments": JamfProEndpointConfig(+ name="departments",+ path="/api/v1/departments",+ ),+ "categories": JamfProEndpointConfig(+ name="categories",+ path="/api/v1/categories",+ ),+ "sites": JamfProEndpointConfig(+ name="sites",+ path="/api/v1/sites",+ paginated=False,+ sort=None,+ ),+ "computer_groups": JamfProEndpointConfig(+ name="computer_groups",+ path="/api/v1/computer-groups",+ paginated=False,+ sort=None,+ ),+ "scripts": JamfProEndpointConfig(+ name="scripts",+ path="/api/v1/scripts",+ # scriptContents routinely embeds deployment credentials; keep it out of sample capture.+ capture_samples=False,+ ),+ "packages": JamfProEndpointConfig(+ name="packages",+ path="/api/v1/packages",+ ),+}++ENDPOINTS = tuple(JAMF_PRO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in JAMF_PRO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/source.pyindex 364054f85e1f..a3a7e26b46b1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/source.py@@ -1,30 +1,224 @@-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 JamfProSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.jamf_pro import (+ HOST_NOT_ALLOWED_ERROR,+ INCOMPLETE_CREDENTIALS_ERROR,+ JamfProCredentials,+ JamfProResumeConfig,+ jamf_pro_source,+ validate_credentials as validate_jamf_pro_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _credentials_from_config(config: JamfProSourceConfig) -> JamfProCredentials:+ auth = config.auth_method+ if auth.selection == "client_credentials":+ return JamfProCredentials(+ method="client_credentials",+ client_id=auth.client_id,+ client_secret=auth.client_secret,+ )+ return JamfProCredentials(+ method="basic",+ username=auth.username,+ password=auth.password,+ )++@SourceRegistry.register-class JamfProSource(SimpleSource[JamfProSourceConfig]):+class JamfProSource(ResumableSource[JamfProSourceConfig, JamfProResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.JAMFPRO+ @property+ def connection_host_fields(self) -> list[str]:+ # `instance_url` is where the stored credentials are sent; retargeting it must re-require them.+ return ["instance_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.JAMF_PRO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Jamf Pro",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["jamf", "mdm", "apple", "device management"],+ caption="""Enter your Jamf Pro instance URL and credentials to pull your device inventory into the PostHog Data warehouse.++The recommended way to connect is an API client: in Jamf Pro go to **Settings > System > API roles and clients**, create an API role with **read** privileges for the objects you want to sync (Computers, Mobile Devices, Buildings, Departments, Categories, Sites, Smart Computer Groups, Static Computer Groups, Scripts, Packages), then create an API client with that role and enable it.++Alternatively, connect with a Jamf Pro user account that has read access to those objects.+""",iconPath="/static/services/jamf_pro.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/jamf-pro",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="instance_url",+ label="Jamf Pro URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany.jamfcloud.com",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="client_credentials",+ options=[+ SourceFieldSelectConfigOption(+ label="API client (recommended)",+ value="client_credentials",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="Username and password",+ value="basic",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid or expired Jamf Pro credentials. Please check the API client (or user account) and reconnect.",+ "403 Client Error": "Your Jamf Pro API client lacks the required read privileges. Grant them in the API role settings and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Jamf Pro URL is not allowed. Please use your organization's Jamf Pro instance URL.",+ INCOMPLETE_CREDENTIALS_ERROR: "Jamf Pro credentials are incomplete. Please re-enter them and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: JamfProSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ # Inventory records mutate in place (report_date advances on every check-in), so+ # append mode would duplicate devices — merge is the only incremental mode.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ 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: JamfProSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_jamf_pro_credentials(+ config.instance_url, _credentials_from_config(config), schema_name, team_id+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JamfProResumeConfig]:+ return ResumableSourceManager[JamfProResumeConfig](inputs, JamfProResumeConfig)++ def source_for_pipeline(+ self,+ config: JamfProSourceConfig,+ resumable_source_manager: ResumableSourceManager[JamfProResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return jamf_pro_source(+ host=config.instance_url,+ credentials=_credentials_from_config(config),+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ 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/jamf_pro/tests/test_jamf_pro.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/tests/test_jamf_pro.pynew file mode 100644index 000000000000..9495715bef5f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/tests/test_jamf_pro.py@@ -0,0 +1,550 @@+import json+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro import jamf_pro as jamf_pro_module+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.jamf_pro import (+ JamfProConfigurationError,+ JamfProCredentials,+ JamfProHostNotAllowedError,+ JamfProPaginationLimitError,+ JamfProResponseTooLargeError,+ JamfProResponseTooSlowError,+ JamfProResumeConfig,+ JamfProTokenManager,+ _build_params,+ _build_url,+ _format_incremental_value,+ get_rows,+ jamf_pro_source,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.settings import JAMF_PRO_ENDPOINTS++CLIENT_CREDENTIALS = JamfProCredentials(method="client_credentials", client_id="cid", client_secret="secret")+BASIC_CREDENTIALS = JamfProCredentials(method="basic", username="admin", password="hunter2")++TOKEN_JSON = {"access_token": "tok", "expires_in": 1199, "token_type": "Bearer"}+++def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.is_redirect = status_code in (302, 303, 307)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.json.return_value = json_data+ # Responses are read via stream=True + iter_content, so serve the body in that shape. A fresh+ # iterator per call lets a single mock response stand in for repeated fetches.+ if json_data is not None:+ body = json.dumps(json_data).encode()+ else:+ body = text.encode()+ response.iter_content.side_effect = lambda *args, **kwargs: iter([body] if body else [])+ if status_code >= 400:+ error = requests.HTTPError(+ f"{status_code} Client Error: for url: https://example.jamfcloud.com", response=response+ )+ response.raise_for_status.side_effect = error+ return response+++def _session(post_responses: list[Any] | None = None, get_responses: list[Any] | None = None) -> mock.MagicMock:+ session = mock.MagicMock()+ if post_responses is not None:+ session.post.side_effect = post_responses+ if get_responses is not None:+ session.get.side_effect = get_responses+ return session+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("example.jamfcloud.com", "example.jamfcloud.com"),+ ("https://example.jamfcloud.com", "example.jamfcloud.com"),+ ("http://example.jamfcloud.com/", "example.jamfcloud.com"),+ (" example.jamfcloud.com ", "example.jamfcloud.com"),+ ("example.jamfcloud.com/api/v1", "example.jamfcloud.com"),+ ("https://jamf.example.org/api/v1/computers-inventory", "jamf.example.org"),+ ],+ )+ def test_normalize_host(self, raw, expected):+ assert normalize_host(raw) == expected+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("already-a-cursor", "already-a-cursor"),+ ],+ )+ def test_format(self, value, expected):+ assert _format_incremental_value(value) == expected+++class TestBuildParams:+ def test_computers_incremental_builds_rsql_filter_and_sorts_by_cursor(self):+ params = _build_params(+ JAMF_PRO_ENDPOINTS["computers"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )+ assert params["filter"] == 'general.reportDate>="2024-01-01T00:00:00.000Z"'+ assert params["sort"] == "general.reportDate:asc"++ def test_computers_first_incremental_sync_has_no_filter_but_sorts_by_cursor(self):+ params = _build_params(+ JAMF_PRO_ENDPOINTS["computers"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert "filter" not in params+ assert params["sort"] == "general.reportDate:asc"++ def test_computers_full_refresh_has_no_filter(self):+ params = _build_params(+ JAMF_PRO_ENDPOINTS["computers"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )+ assert "filter" not in params+ assert params["sort"] == "id:asc"++ def test_non_incremental_endpoint_never_sends_filter(self):+ # Endpoints without a documented RSQL timestamp filter must not send one — the API+ # would reject the request.+ params = _build_params(+ JAMF_PRO_ENDPOINTS["scripts"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )+ assert "filter" not in params++ def test_computers_requests_inventory_sections(self):+ params = _build_params(+ JAMF_PRO_ENDPOINTS["computers"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ url = _build_url("example.jamfcloud.com", JAMF_PRO_ENDPOINTS["computers"], params)+ # Sections must be repeated params, not a single comma-joined value.+ assert "section=GENERAL" in url+ assert "section=HARDWARE" in url+++class TestTokenManager:+ def test_client_credentials_mints_oauth_token(self):+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)])+ manager = JamfProTokenManager(session, "example.jamfcloud.com", CLIENT_CREDENTIALS)++ assert manager.get_token() == "tok"+ url = session.post.call_args.args[0]+ assert url == "https://example.jamfcloud.com/api/oauth/token"+ assert session.post.call_args.kwargs["data"]["grant_type"] == "client_credentials"++ def test_basic_mints_token_with_http_basic(self):+ session = _session(post_responses=[_response(json_data={"token": "tok2", "expires": "2100-01-01T00:00:00Z"})])+ manager = JamfProTokenManager(session, "example.jamfcloud.com", BASIC_CREDENTIALS)++ assert manager.get_token() == "tok2"+ url = session.post.call_args.args[0]+ assert url == "https://example.jamfcloud.com/api/v1/auth/token"+ assert session.post.call_args.kwargs["auth"] == ("admin", "hunter2")++ def test_token_is_cached_until_expiry(self):+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)])+ manager = JamfProTokenManager(session, "example.jamfcloud.com", CLIENT_CREDENTIALS)++ manager.get_token()+ manager.get_token()+ assert session.post.call_count == 1++ def test_token_is_reminted_when_close_to_expiry(self):+ # Jamf tokens live ~20 minutes; a long-running sync must re-mint instead of sending an+ # expired token and failing every request with a 401.+ session = _session(+ post_responses=[+ _response(json_data={**TOKEN_JSON, "access_token": "first"}),+ _response(json_data={**TOKEN_JSON, "access_token": "second"}),+ ]+ )+ manager = JamfProTokenManager(session, "example.jamfcloud.com", CLIENT_CREDENTIALS)+ manager.get_token()+ manager._deadline = 0.0 # simulate the token reaching its expiry margin++ assert manager.get_token() == "second"+ assert session.post.call_count == 2++ @pytest.mark.parametrize(+ "credentials",+ [+ JamfProCredentials(method="client_credentials", client_id="cid", client_secret=None),+ JamfProCredentials(method="basic", username=None, password="pw"),+ ],+ )+ def test_missing_credential_fields_raise_configuration_error(self, credentials):+ manager = JamfProTokenManager(_session(), "example.jamfcloud.com", credentials)+ with pytest.raises(JamfProConfigurationError):+ manager.get_token()++ def test_redirect_on_token_endpoint_is_rejected(self):+ # The host is customer-controlled; following a redirect could leak credentials to an+ # arbitrary Location (SSRF).+ session = _session(post_responses=[_response(status_code=302)])+ manager = JamfProTokenManager(session, "example.jamfcloud.com", CLIENT_CREDENTIALS)+ with pytest.raises(JamfProHostNotAllowedError):+ manager.get_token()++ def test_401_raises_http_error(self):+ session = _session(post_responses=[_response(status_code=401)])+ manager = JamfProTokenManager(session, "example.jamfcloud.com", CLIENT_CREDENTIALS)+ with pytest.raises(requests.HTTPError):+ manager.get_token()++ def test_slow_token_response_is_rejected(self):+ # A host dribbling the token body under the read timeout must not hold a worker open past the+ # wall-clock budget. A negative budget forces the deadline into the past on the first chunk.+ token_resp = _response(json_data=TOKEN_JSON)+ session = _session(post_responses=[token_resp])+ manager = JamfProTokenManager(session, "example.jamfcloud.com", CLIENT_CREDENTIALS)+ with mock.patch.object(jamf_pro_module, "MAX_DOWNLOAD_SECONDS", -1):+ with pytest.raises(JamfProResponseTooSlowError):+ manager.get_token()+ token_resp.close.assert_called()+++class TestValidateCredentials:+ def _patch_session(self, session: mock.MagicMock):+ return mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session)++ def test_successful_token_mint_is_enough_at_source_create(self):+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)])+ with self._patch_session(session) as factory:+ assert validate_credentials("example.jamfcloud.com", CLIENT_CREDENTIALS) == (True, None)+ # Privileges are per-resource in Jamf, so create-time must not probe endpoints.+ session.get.assert_not_called()+ # The mint response body carries the bearer token; it must stay out of sample capture.+ assert factory.call_args.kwargs == {"capture": False}++ def test_invalid_credentials(self):+ session = _session(post_responses=[_response(status_code=401)])+ with self._patch_session(session):+ valid, msg = validate_credentials("example.jamfcloud.com", CLIENT_CREDENTIALS)+ assert valid is False+ assert msg == "Invalid Jamf Pro credentials"++ def test_incomplete_credentials_return_friendly_error(self):+ with self._patch_session(_session()):+ valid, msg = validate_credentials("example.jamfcloud.com", JamfProCredentials(method="client_credentials"))+ assert valid is False+ assert "incomplete" in (msg or "")++ @pytest.mark.parametrize("bad_host", ["", "not a host!", "https://"])+ def test_invalid_host_short_circuits(self, bad_host):+ valid, msg = validate_credentials(bad_host, CLIENT_CREDENTIALS)+ assert valid is False+ assert msg == "Invalid Jamf Pro URL"++ def test_blocks_unsafe_host(self):+ session = _session()+ with (+ mock.patch.object(jamf_pro_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(session),+ ):+ valid, msg = validate_credentials("10.0.0.1", CLIENT_CREDENTIALS, team_id=99)+ assert valid is False+ assert msg == "internal address"+ session.post.assert_not_called()++ def test_scoped_probe_403_fails(self):+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)], get_responses=[_response(status_code=403)])+ with self._patch_session(session):+ valid, msg = validate_credentials("example.jamfcloud.com", CLIENT_CREDENTIALS, schema_name="computers")+ assert valid is False+ assert "computers" in (msg or "")++ def test_scoped_probe_200_succeeds(self):+ session = _session(+ post_responses=[_response(json_data=TOKEN_JSON)],+ get_responses=[_response(json_data={"totalCount": 1, "results": [{"id": "1"}]})],+ )+ with self._patch_session(session):+ assert validate_credentials("example.jamfcloud.com", CLIENT_CREDENTIALS, schema_name="computers") == (+ True,+ None,+ )++ def test_request_exception_returns_failure(self):+ session = mock.MagicMock()+ session.post.side_effect = requests.exceptions.ConnectionError("boom")+ with self._patch_session(session):+ valid, msg = validate_credentials("example.jamfcloud.com", CLIENT_CREDENTIALS)+ assert valid is False+ assert "boom" in (msg or "")+++class TestGetRows:+ def _run(+ self,+ manager: mock.MagicMock,+ get_responses: list[Any],+ endpoint: str = "computers",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[Any], mock.MagicMock]:+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)], get_responses=get_responses)+ with mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session):+ rows: list[Any] = []+ for batch in get_rows(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows, session++ def _manager(self, resume: Optional[JamfProResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager++ def test_paginates_until_total_count_reached(self):+ manager = self._manager()+ page1 = _response(json_data={"totalCount": 150, "results": [{"id": str(i)} for i in range(100)]})+ page2 = _response(json_data={"totalCount": 150, "results": [{"id": str(i)} for i in range(100, 150)]})+ rows, session = self._run(manager, [page1, page2])++ assert len(rows) == 150+ assert session.get.call_count == 2+ assert "page=0" in session.get.call_args_list[0].args[0]+ assert "page=1" in session.get.call_args_list[1].args[0]+ # State is saved once, AFTER yielding page 0 and only because more pages remain.+ manager.save_state.assert_called_once_with(JamfProResumeConfig(page=1))++ def test_stops_on_empty_results_without_total_count(self):+ manager = self._manager()+ page1 = _response(json_data={"results": [{"id": "1"}]})+ empty = _response(json_data={"results": []})+ rows, session = self._run(manager, [page1, empty])++ assert [r["id"] for r in rows] == ["1"]+ assert session.get.call_count == 2++ def test_resumes_from_saved_page(self):+ manager = self._manager(resume=JamfProResumeConfig(page=3))+ page = _response(json_data={"totalCount": 301, "results": [{"id": "301"}]})+ _rows, session = self._run(manager, [page])++ assert "page=3" in session.get.call_args_list[0].args[0]++ def test_computers_rows_expose_top_level_report_date(self):+ # The pipeline reads the incremental watermark from a top-level column, so the nested+ # general.reportDate must be hoisted onto every row.+ manager = self._manager()+ page = _response(+ json_data={+ "totalCount": 1,+ "results": [{"id": "1", "general": {"reportDate": "2024-06-01T00:00:00.000Z"}}],+ }+ )+ rows, _session_ = self._run(manager, [page])++ assert rows[0]["report_date"] == "2024-06-01T00:00:00.000Z"+ assert rows[0]["general"]["reportDate"] == "2024-06-01T00:00:00.000Z"++ def test_computers_rows_missing_general_get_null_report_date(self):+ manager = self._manager()+ page = _response(json_data={"totalCount": 1, "results": [{"id": "1"}]})+ rows, _session_ = self._run(manager, [page])++ assert rows[0]["report_date"] is None++ def test_incremental_run_sends_rsql_filter(self):+ manager = self._manager()+ page = _response(json_data={"totalCount": 1, "results": [{"id": "1", "general": {}}]})+ _rows, session = self._run(+ manager,+ [page],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )++ url = session.get.call_args_list[0].args[0]+ assert "filter=general.reportDate%3E%3D%222024-01-01T00%3A00%3A00.000Z%22" in url++ def test_unpaginated_endpoint_yields_array_response(self):+ manager = self._manager()+ page = _response(json_data=[{"id": "1", "name": "HQ"}])+ rows, session = self._run(manager, [page], endpoint="sites")++ assert rows == [{"id": "1", "name": "HQ"}]+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_blocks_unsafe_host_before_any_request(self):+ manager = self._manager()+ with mock.patch.object(jamf_pro_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(JamfProHostNotAllowedError):+ list(+ get_rows(+ host="10.0.0.1",+ credentials=CLIENT_CREDENTIALS,+ endpoint="computers",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )++ def test_rejects_redirect_response(self):+ manager = self._manager()+ with pytest.raises(JamfProHostNotAllowedError):+ self._run(manager, [_response(status_code=302)])++ @pytest.mark.parametrize(+ "endpoint, data_capture",+ [+ ("computers", True),+ # scriptContents routinely embeds deployment credentials, so the scripts data+ # session must stay out of sample capture too.+ ("scripts", False),+ ],+ )+ def test_token_mint_session_is_excluded_from_sample_capture(self, endpoint, data_capture):+ # The mint response body carries the bearer token, which the name-based sample+ # scrubbers can't recognise — re-enabling capture there would persist a live credential.+ manager = self._manager()+ page = _response(json_data={"totalCount": 1, "results": [{"id": "1"}]})+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)], get_responses=[page])+ with mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session) as factory:+ list(+ get_rows(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ assert factory.call_args_list == [mock.call(capture=False), mock.call(capture=data_capture)]++ def test_requests_do_not_follow_redirects(self):+ manager = self._manager()+ page = _response(json_data={"totalCount": 1, "results": [{"id": "1", "general": {}}]})+ _rows, session = self._run(manager, [page])++ assert session.get.call_args.kwargs["allow_redirects"] is False+ assert session.post.call_args.kwargs["allow_redirects"] is False++ def test_oversized_page_body_is_rejected(self):+ # The instance URL is customer-controlled; a hostile server returning a body larger than the+ # cap must fail the sync rather than buffer it whole into a shared worker's memory.+ manager = self._manager()+ big_page = _response(json_data={"results": [{"id": "1"}]})+ big_page.iter_content.side_effect = lambda *a, **k: iter([b"x" * 2048])+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)], get_responses=[big_page])+ with (+ mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session),+ mock.patch.object(jamf_pro_module, "MAX_RESPONSE_BYTES", 1024),+ ):+ with pytest.raises(JamfProResponseTooLargeError):+ list(+ get_rows(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint="computers",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )++ def test_slow_page_body_is_rejected(self):+ # The token mints within budget; the page body then dribbles past the wall-clock budget and+ # must be aborted. The read timeout only bounds each socket read, not total transfer time.+ manager = self._manager()+ clock = {"t": 0.0}+ token_resp = _response(json_data=TOKEN_JSON)+ page_resp = _response(json_data={"results": [{"id": "1"}]})++ def slow_page_chunks(*args, **kwargs):+ clock["t"] += jamf_pro_module.MAX_DOWNLOAD_SECONDS + 1 # jump past the budget mid-download+ yield b'{"results": []}'++ page_resp.iter_content.side_effect = slow_page_chunks+ session = _session(post_responses=[token_resp], get_responses=[page_resp])+ with (+ mock.patch.object(jamf_pro_module.time, "monotonic", lambda: clock["t"]),+ mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session),+ ):+ with pytest.raises(JamfProResponseTooSlowError):+ list(+ get_rows(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint="computers",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ page_resp.close.assert_called()++ def test_pagination_stops_when_server_never_terminates(self):+ # A server returning a non-empty page forever with no totalCount would otherwise loop until+ # the activity's week-long timeout; the hard page cap breaks that.+ manager = self._manager()+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)])+ session.get.return_value = _response(json_data={"results": [{"id": "1"}]})+ with (+ mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session),+ mock.patch.object(jamf_pro_module, "MAX_PAGES", 3),+ ):+ with pytest.raises(JamfProPaginationLimitError):+ list(+ get_rows(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint="computers",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ # Pages 0, 1, 2 fetched; the loop raises before fetching page 3.+ assert session.get.call_count == 3+++class TestJamfProSourceResponse:+ @pytest.mark.parametrize("endpoint", list(JAMF_PRO_ENDPOINTS.keys()))+ def test_response_shape(self, endpoint):+ response = jamf_pro_source(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/tests/test_jamf_pro_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/tests/test_jamf_pro_source.pynew file mode 100644index 000000000000..e9a12625c279--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/tests/test_jamf_pro_source.py@@ -0,0 +1,148 @@+import pytest+from unittest import mock++from posthog.schema import 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.generated_configs import (+ JamfProAuthMethodConfig,+ JamfProSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.jamf_pro import JamfProResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.source import JamfProSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestJamfProSource:+ def setup_method(self):+ self.source = JamfProSource()+ self.team_id = 123+ self.config = JamfProSourceConfig(+ instance_url="example.jamfcloud.com",+ auth_method=JamfProAuthMethodConfig(+ selection="client_credentials", client_id="cid", client_secret="secret"+ ),+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.JAMFPRO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "JamfPro"+ assert config.label == "Jamf Pro"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA++ field_names = [f.name for f in config.fields]+ assert field_names == ["instance_url", "auth_method"]++ url_field, auth_field = config.fields+ assert isinstance(url_field, SourceFieldInputConfig)+ assert url_field.secret is False+ assert url_field.required is True++ assert isinstance(auth_field, SourceFieldSelectConfig)+ assert [option.value for option in auth_field.options] == ["client_credentials", "basic"]+ secret_flags = {+ f.name: f.secret for option in auth_field.options for f in option.fields or [] if hasattr(f, "secret")+ }+ assert secret_flags == {"client_id": False, "client_secret": True, "username": False, "password": True}++ def test_connection_host_fields_covers_instance_url(self):+ # Without this, an org member could retarget the instance URL at a server they control+ # and exfiltrate the preserved credentials.+ assert self.source.connection_host_fields == ["instance_url"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 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", list(ENDPOINTS))+ def test_schema_sync_modes(self, endpoint):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ # Only computer inventory documents a server-side RSQL timestamp filter; everything else+ # is full-refresh. Inventory records mutate in place, so append mode is never offered.+ assert schemas[endpoint].supports_incremental is (endpoint == "computers")+ assert schemas[endpoint].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["computers"])+ assert [s.name for s in schemas] == ["computers"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.source.validate_jamf_pro_credentials"+ )+ def test_validate_credentials_maps_client_credentials(self, mock_validate):+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="computers")++ assert result == (True, None)+ args = mock_validate.call_args.args+ assert args[0] == "example.jamfcloud.com"+ credentials = args[1]+ assert credentials.method == "client_credentials"+ assert credentials.client_id == "cid"+ assert credentials.client_secret == "secret"+ assert args[2] == "computers"+ assert args[3] == self.team_id++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.source.validate_jamf_pro_credentials"+ )+ def test_validate_credentials_maps_basic_auth(self, mock_validate):+ mock_validate.return_value = (True, None)+ config = JamfProSourceConfig(+ instance_url="example.jamfcloud.com",+ auth_method=JamfProAuthMethodConfig(selection="basic", username="admin", password="pw"),+ )++ self.source.validate_credentials(config, self.team_id)++ credentials = mock_validate.call_args.args[1]+ assert credentials.method == "basic"+ assert credentials.username == "admin"+ assert credentials.password == "pw"++ def test_get_resumable_source_manager(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is JamfProResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.source.jamf_pro_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_jamf_pro_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "computers"+ inputs.team_id = 42+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00.000Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_jamf_pro_source.call_args.kwargs+ assert kwargs["host"] == "example.jamfcloud.com"+ assert kwargs["credentials"].client_id == "cid"+ assert kwargs["endpoint"] == "computers"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00.000Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.jamf_pro.source.jamf_pro_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_jamf_pro_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "buildings"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_jamf_pro_source.call_args.kwargs["db_incremental_field_last_value"] is None