: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(warehouse-sources): add jamf pro users, mdm command and patch tables (#112527)
Tom Owers37eedbef9eb0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 2f9076df0d5a..30d73f5798fd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -4470,12 +4470,12 @@ Today (9): `buildings`, `categories`, `computer_groups`, `computers`, `departmenDiffed against: <https://developer.jamf.com/jamf-pro/reference/get_v1-buildings>-- [ ] `GET /api/v1/users` — lookup resolving the user/owner assigned to the computers and mobile devices we sync (high)+- [x] `GET /api/v1/users` — lookup resolving the user/owner assigned to the computers and mobile devices we sync (high)- [ ] `GET /api/v2/computer-groups/smart-group-membership/{id} and /static-group-membership/{id}` — membership junction for the computer_groups we already sync — group rows without members are unusable (high)- [ ] `GET /api/v2/mobile-device-groups (+ smart/static group membership)` — mobile equivalent of computer_groups plus its membership; we sync mobile_devices but no groups (high)-- [ ] `GET /api/v3/patch-software-title-configurations and /{id}/patch-report, /{id}/patch-summary` — patch compliance per software title and per device — Jamf's headline reporting surface (high)-- [ ] `GET /api/v2/mdm-commands` — MDM command history and status per device; the state-transition record for device management (high)-- [ ] `GET /api/v1/managed-software-updates/update-statuses (+ /computers/{id}, /computer-groups/{id})` — OS update enforcement status per device — core compliance metric (high)+- [x] `GET /api/v3/patch-software-title-configurations and /{id}/patch-report, /{id}/patch-summary` — patch compliance per software title and per device — Jamf's headline reporting surface (high)+- [x] `GET /api/v2/mdm-commands` — MDM command history and status per device; the state-transition record for device management (high)+- [x] `GET /api/v1/managed-software-updates/update-statuses (+ /computers/{id}, /computer-groups/{id})` — OS update enforcement status per device — core compliance metric (high)- [ ] `GET /api/v2/patch-policies and /api/v2/patch-policies/{id}/logs` — per-device patch deployment outcomes for the packages we sync (medium)- [ ] `GET /api/v1/computers-inventory/filevault (and /{id}/filevault)` — FileVault encryption compliance per computer (medium)- [ ] `GET /api/v1/computer-extension-attributes and /api/v1/mobile-device-extension-attributes` — lookup resolving the custom extension-attribute IDs embedded in inventory records (medium)diff --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.pyindex 0f231b6e8407..18cd18782b08 100644--- 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.py@@ -117,4 +117,95 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"sha256": "SHA-256 checksum of the package file.",},},+ "users": {+ "description": "Users in the Jamf Pro inventory, the people that computers and mobile devices are assigned to.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-users",+ "columns": {+ "id": "Unique identifier of the user.",+ "username": "Username of the user.",+ "realname": "Full name of the user.",+ "email": "Email address of the user.",+ "phone": "Phone number of the user.",+ "position": "Job position of the user.",+ "managedAppleId": "Managed Apple Account of the user.",+ },+ },+ "mdm_commands": {+ "description": "MDM commands Jamf Pro sent to managed devices, with each command's state and result.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-mdm-commands",+ "columns": {+ "uuid": "Unique identifier of the command.",+ "dateSent": "Timestamp when Jamf Pro sent the command.",+ "dateCompleted": "Timestamp when the device completed the command.",+ "client": "Target of the command: its management ID and client type (computer, mobile device, or user).",+ "commandState": "State of the command: PENDING, ACKNOWLEDGED, NOT_NOW, ERROR, or COMMAND_FORMAT_ERROR.",+ "commandType": "Type of MDM command, for example DEVICE_LOCK or INSTALL_PROFILE.",+ "commandError": "Error code, domain, and description that the device returned for a failed command.",+ "profileId": "Identifier of the configuration profile the command installs or removes.",+ },+ },+ "managed_software_update_statuses": {+ "description": "Status of managed software (OS) updates on each computer and mobile device.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v1-managed-software-updates-update-statuses",+ "columns": {+ "osUpdatesStatusId": "Unique identifier of the update status.",+ "device": "Device the status applies to: its device ID and object type.",+ "downloadPercentComplete": "Fraction of the update download that is complete.",+ "downloaded": "Whether the device downloaded the update.",+ "productKey": "Apple product key of the update.",+ "status": "Current status of the update on the device.",+ "deferralsRemaining": "Number of deferrals the user has left.",+ "maxDeferrals": "Maximum number of deferrals allowed.",+ "nextScheduledInstall": "Timestamp of the next scheduled install attempt.",+ "pastNotifications": "Timestamps of the notifications already shown to the user.",+ "created": "Timestamp when the status was created.",+ "updated": "Timestamp when the status last changed.",+ },+ },+ "patch_software_title_configurations": {+ "description": "Patch management software titles configured in Jamf Pro, with their patch source and packages.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v3-patch-software-title-configurations",+ "columns": {+ "id": "Unique identifier of the software title configuration.",+ "displayName": "Display name of the software title configuration.",+ "categoryId": "Identifier of the category the title belongs to.",+ "siteId": "Identifier of the site the title belongs to.",+ "softwareTitleId": "Identifier of the software title in the patch source.",+ "softwareTitleName": "Name of the software title.",+ "softwareTitlePublisher": "Publisher of the software title.",+ "patchSourceName": "Name of the patch source that provides the title definitions.",+ "jamfOfficial": "Whether the title comes from the Jamf official patch source.",+ "packages": "Packages mapped to versions of the software title.",+ },+ },+ "patch_reports": {+ "description": "Patch report for each software title configuration: one row per computer with the version it has installed.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v3-patch-software-title-configurations-id-patch-report",+ "columns": {+ "softwareTitleConfigurationId": "Identifier of the software title configuration the row reports on.",+ "deviceId": "Identifier of the computer.",+ "computerName": "Name of the computer.",+ "username": "Username assigned to the computer.",+ "operatingSystemVersion": "Operating system version of the computer.",+ "lastCheckIn": "Timestamp of the computer's last check-in.",+ "buildingName": "Building assigned to the computer.",+ "departmentName": "Department assigned to the computer.",+ "siteName": "Site the computer belongs to.",+ "version": "Version of the software title installed on the computer.",+ },+ },+ "patch_summaries": {+ "description": "Patch compliance summary for each software title configuration: latest version and up-to-date versus out-of-date counts.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v3-patch-software-title-configurations-id-patch-summary",+ "columns": {+ "softwareTitleConfigurationId": "Identifier of the software title configuration.",+ "softwareTitleId": "Identifier of the software title in the patch source.",+ "title": "Name of the software title.",+ "latestVersion": "Latest available version of the software title.",+ "releaseDate": "Release date of the latest version.",+ "upToDate": "Number of computers on the latest version.",+ "outOfDate": "Number of computers on an older version.",+ "onDashboard": "Whether the title appears on the Jamf Pro dashboard.",+ },+ },}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.pyindex 09a82a9fa413..026ce61d80fc 100644--- 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.py@@ -2,10 +2,11 @@ import reimport jsonimport timeimport dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetime+from functools import partialfrom typing import Any, Literal, Optional-from urllib.parse import urlencode+from urllib.parse import quote, urlencodeimport requestsfrom structlog.types import FilteringBoundLogger@@ -135,11 +136,13 @@ def _read_body_preview(response: requests.Response) -> str:return b"".join(chunks)[:_ERROR_BODY_PREVIEW_BYTES].decode("utf-8", errors="replace")[email protected](frozen=False)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+ # Fan-out endpoints only: the parent whose child pages `page` indexes into.+ parent_id: str | None = None@frozen@@ -272,7 +275,7 @@ def _build_params(should_use_incremental_field: bool,db_incremental_field_last_value: Any,) -> dict[str, Any]:- params: dict[str, Any] = {"page-size": config.page_size}+ params: dict[str, Any] = {"page-size": config.page_size} if config.paginated else {}sort = config.sortif should_use_incremental_field and config.rsql_incremental_field:@@ -284,6 +287,9 @@ def _build_params(# double-quoted because RSQL treats bare colons in timestamps as reserved characters.params["filter"] = f'{config.rsql_incremental_field}>="{formatted}"'+ if "filter" not in params and config.default_filter:+ params["filter"] = config.default_filter+if sort:params["sort"] = sortif config.sections:@@ -292,8 +298,9 @@ def _build_params(return params-def _build_url(host: str, config: JamfProEndpointConfig, params: dict[str, Any]) -> str:- url = f"{_base_url(host)}{config.path}"+def _build_url(host: str, config: JamfProEndpointConfig, params: dict[str, Any], parent_id: str | None = None) -> str:+ path = config.path if parent_id is None else config.path.replace("{id}", quote(parent_id, safe=""))+ url = f"{_base_url(host)}{path}"if not params:return urlreturn f"{url}?{urlencode(params, doseq=True)}"@@ -360,12 +367,16 @@ def validate_credentials(return True, Noneconfig = JAMF_PRO_ENDPOINTS[schema_name]- probe_params = {"page": 0, "page-size": 1} if config.paginated else {}+ # Fan-out children need a parent id to address, and they share the parent's read privilege.+ probe_config = JAMF_PRO_ENDPOINTS[config.parent] if config.parent else config+ probe_params: dict[str, Any] = {"page": 0, "page-size": 1} if probe_config.paginated else {}+ if probe_config.default_filter:+ probe_params["filter"] = probe_config.default_filtertry:# 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),+ _build_url(normalized, probe_config, probe_params),headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},timeout=10,allow_redirects=False,@@ -391,6 +402,76 @@ def validate_credentials(return False, f"Jamf Pro API returned status {status_code} for {schema_name}"+def _parent_sort_key(parent_id: str) -> tuple[int, int | str]:+ return (0, int(parent_id)) if parent_id.isdigit() else (1, parent_id)+++def _iter_endpoint_pages(+ fetch_page: Callable[[str], Any],+ host: str,+ config: JamfProEndpointConfig,+ params: dict[str, Any],+ page: int,+ resumable_source_manager: ResumableSourceManager[JamfProResumeConfig],+ resume_state: Callable[[int], JamfProResumeConfig],+ parent_id: str | None = None,+ request_budget: list[int] | None = None,+) -> Iterator[list[dict[str, Any]]]:+ def fetch_bounded(page_url: str) -> Any:+ if request_budget is not None:+ if request_budget[0] >= MAX_PAGES:+ raise JamfProPaginationLimitError(+ f"Jamf Pro pagination for {config.name} exceeded {MAX_PAGES} requests without terminating"+ )+ request_budget[0] += 1+ return fetch_page(page_url)++ def shape(row: dict[str, Any]) -> dict[str, Any]:+ row = _hoist_cursor(config, row)+ if parent_id is not None and config.parent_id_field:+ row = {**row, config.parent_id_field: parent_id}+ return row++ if not config.paginated:+ data = fetch_bounded(_build_url(host, config, params, parent_id))+ if isinstance(data, list):+ rows = data+ elif "results" in data:+ rows = data["results"]+ else:+ # Single-object responses (e.g. a title's patch summary) become one row.+ rows = [data] if data else []+ if rows:+ yield [shape(row) for row in rows]+ return++ 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 {config.name} exceeded {MAX_PAGES} pages without terminating"+ )++ data = fetch_bounded(_build_url(host, config, {**params, "page": page}, parent_id))++ results = data.get("results", [])+ if not results:+ break++ yield [shape(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(resume_state(page + 1))+ page += 1++def get_rows(host: str,credentials: JamfProCredentials,@@ -453,45 +534,63 @@ def get_rows(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]+ if config.parent is 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}")+ yield from _iter_endpoint_pages(+ fetch_page,+ host,+ config,+ params,+ page,+ resumable_source_manager,+ lambda next_page: JamfProResumeConfig(page=next_page),+ )+ return- total_count = data.get("totalCount")- if total_count is not None and (page + 1) * config.page_size >= total_count:- break+ parent_config = JAMF_PRO_ENDPOINTS[config.parent]+ parent_data = fetch_page(_build_url(host, parent_config, {}))+ parent_rows = parent_data if isinstance(parent_data, list) else parent_data.get("results", [])+ # Walk parents in a deterministic order so a resume can skip the parents already synced.+ parent_ids = sorted((str(row["id"]) for row in parent_rows if row.get("id") is not None), key=_parent_sort_key)++ if resume_config is not None and resume_config.parent_id is not None:+ resume_key = _parent_sort_key(resume_config.parent_id)+ parent_ids = [pid for pid in parent_ids if _parent_sort_key(pid) >= resume_key]+ logger.debug(f"Jamf Pro: resuming {endpoint} from parent {resume_config.parent_id} page {resume_config.page}")++ request_budget = [0]+ for index, parent_id in enumerate(parent_ids):+ start_page = (+ resume_config.page+ if resume_config is not None and index == 0 and resume_config.parent_id == parent_id+ else 0+ )+ try:+ yield from _iter_endpoint_pages(+ fetch_page,+ host,+ config,+ params,+ start_page,+ resumable_source_manager,+ partial(JamfProResumeConfig, parent_id=parent_id),+ parent_id=parent_id,+ request_budget=request_budget,+ )+ except requests.HTTPError as e:+ # A title deleted between listing the parents and fetching its children 404s.+ if e.response is None or e.response.status_code != 404:+ raise+ logger.debug(f"Jamf Pro: {endpoint} parent {parent_id} no longer exists, skipping")- # 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+ if index + 1 < len(parent_ids):+ resumable_source_manager.save_state(JamfProResumeConfig(page=0, parent_id=parent_ids[index + 1]))+ resumable_source_manager.safe_point()def jamf_pro_source(@@ -518,7 +617,7 @@ def jamf_pro_source(should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,),- primary_keys=[endpoint_config.primary_key],+ primary_keys=endpoint_config.primary_keys,# 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.pyindex 7b2d52c0c2d8..2f97cae0fc7e 100644--- 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.py@@ -30,7 +30,7 @@ COMPUTERS_INVENTORY_SECTIONS = []-@dataclass+@dataclass(frozen=False)class JamfProEndpointConfig:name: strpath: str@@ -38,7 +38,7 @@ class JamfProEndpointConfig:# page / page-size / sort. A few (sites, computer-groups) return a plain JSON array.paginated: bool = Truepage_size: int = 200- primary_key: str = "id"+ primary_keys: list[str] = field(default_factory=lambda: ["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)@@ -47,7 +47,11 @@ class JamfProEndpointConfig: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.+ # Leave unset when the RSQL field is already a top-level column.default_incremental_field: Optional[str] = None+ # RSQL filter sent whenever no incremental filter applies, for endpoints that reject a+ # request without any filter.+ default_filter: 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@@ -56,6 +60,10 @@ class JamfProEndpointConfig:# 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+ # Fan-out children: `path` holds an `{id}` placeholder filled from each row of this parent+ # endpoint, and the parent id is written to `parent_id_field` on every child row.+ parent: Optional[str] = None+ parent_id_field: Optional[str] = NoneJAMF_PRO_ENDPOINTS: dict[str, JamfProEndpointConfig] = {@@ -113,6 +121,58 @@ JAMF_PRO_ENDPOINTS: dict[str, JamfProEndpointConfig] = {name="packages",path="/api/v1/packages",),+ "users": JamfProEndpointConfig(+ name="users",+ path="/api/v1/users",+ ),+ # The endpoint rejects requests without a filter, so full refreshes send an always-true+ # dateSent bound. Commands keep their dateSent as their state moves from pending to+ # acknowledged, so an incremental run only picks up commands sent since the last sync. A+ # full refresh refreshes the state of older commands.+ "mdm_commands": JamfProEndpointConfig(+ name="mdm_commands",+ path="/api/v2/mdm/commands",+ primary_keys=["uuid"],+ sort="dateSent:asc",+ rsql_incremental_field="dateSent",+ incremental_sort="dateSent:asc",+ incremental_fields=[_datetime_incremental_field("dateSent")],+ default_filter='dateSent>="1970-01-01T00:00:00.000Z"',+ ),+ # Unpaginated: the endpoint takes only `filter` and returns every status in one response.+ # `updated` advances whenever a device's update status changes.+ "managed_software_update_statuses": JamfProEndpointConfig(+ name="managed_software_update_statuses",+ path="/api/v1/managed-software-updates/update-statuses",+ paginated=False,+ sort=None,+ primary_keys=["osUpdatesStatusId"],+ rsql_incremental_field="updated",+ incremental_fields=[_datetime_incremental_field("updated")],+ ),+ "patch_software_title_configurations": JamfProEndpointConfig(+ name="patch_software_title_configurations",+ path="/api/v3/patch-software-title-configurations",+ paginated=False,+ sort=None,+ ),+ "patch_reports": JamfProEndpointConfig(+ name="patch_reports",+ path="/api/v3/patch-software-title-configurations/{id}/patch-report",+ primary_keys=["softwareTitleConfigurationId", "deviceId"],+ sort="deviceId:asc",+ parent="patch_software_title_configurations",+ parent_id_field="softwareTitleConfigurationId",+ ),+ "patch_summaries": JamfProEndpointConfig(+ name="patch_summaries",+ path="/api/v3/patch-software-title-configurations/{id}/patch-summary",+ paginated=False,+ sort=None,+ primary_keys=["softwareTitleConfigurationId"],+ parent="patch_software_title_configurations",+ parent_id_field="softwareTitleConfigurationId",+ ),}ENDPOINTS = tuple(JAMF_PRO_ENDPOINTS.keys())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 969ae81a0ee6..505c32915a0d 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@@ -73,7 +73,7 @@ class JamfProSource(ResumableSource[JamfProSourceConfig, JamfProResumeConfig]):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.+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, Users, Patch Management Software Titles), plus **View MDM command information in Jamf Pro API** for MDM commands, 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.""",@@ -180,8 +180,9 @@ Alternatively, connect with a Jamf Pro user account that has read access to thosSourceSchema(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.+ # Incremental records mutate in place (report_date advances on every check-in, command+ # and update states change), so append mode would duplicate rows — merge is the only+ # incremental mode.supports_append=False,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),)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.pyindex 9495715bef5f..ef33096712bd 100644--- 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.py@@ -134,6 +134,38 @@ class TestBuildParams:)assert "filter" not in params+ @pytest.mark.parametrize(+ "should_use_incremental_field, last_value, expected_filter",+ [+ (False, None, 'dateSent>="1970-01-01T00:00:00.000Z"'),+ (True, None, 'dateSent>="1970-01-01T00:00:00.000Z"'),+ (True, datetime(2024, 1, 1, tzinfo=UTC), 'dateSent>="2024-01-01T00:00:00.000Z"'),+ ],+ )+ def test_mdm_commands_always_sends_a_filter(self, should_use_incremental_field, last_value, expected_filter):+ params = _build_params(+ JAMF_PRO_ENDPOINTS["mdm_commands"],+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+ assert params["filter"] == expected_filter+ assert params["sort"] == "dateSent:asc"++ @pytest.mark.parametrize(+ "should_use_incremental_field, last_value, expected",+ [+ (False, None, {}),+ (True, datetime(2024, 1, 1, tzinfo=UTC), {"filter": 'updated>="2024-01-01T00:00:00.000Z"'}),+ ],+ )+ def test_update_statuses_sends_no_paging_params(self, should_use_incremental_field, last_value, expected):+ params = _build_params(+ JAMF_PRO_ENDPOINTS["managed_software_update_statuses"],+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+ assert params == expected+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@@ -286,6 +318,30 @@ class TestValidateCredentials:None,)+ @pytest.mark.parametrize(+ "schema_name, expected_path, expected_query",+ [+ ("patch_reports", "/api/v3/patch-software-title-configurations", ""),+ ("patch_summaries", "/api/v3/patch-software-title-configurations", ""),+ (+ "mdm_commands",+ "/api/v2/mdm/commands",+ "page=0&page-size=1&filter=dateSent%3E%3D%221970-01-01T00%3A00%3A00.000Z%22",+ ),+ ],+ )+ def test_scoped_probe_targets_an_addressable_url(self, schema_name, expected_path, expected_query):+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)], get_responses=[_response(json_data=[])])+ with self._patch_session(session):+ assert validate_credentials("example.jamfcloud.com", CLIENT_CREDENTIALS, schema_name=schema_name) == (+ True,+ None,+ )+ url = session.get.call_args.args[0]+ path, _, query = url.removeprefix("https://example.jamfcloud.com").partition("?")+ assert path == expected_path+ assert query == expected_query+def test_request_exception_returns_failure(self):session = mock.MagicMock()session.post.side_effect = requests.exceptions.ConnectionError("boom")@@ -399,6 +455,97 @@ class TestGetRows:assert session.get.call_count == 1manager.save_state.assert_not_called()+ def test_fan_out_walks_each_parent_and_tags_child_rows(self):+ manager = self._manager()+ parents = _response(json_data=[{"id": "10"}, {"id": "2"}, {"id": "7"}])+ parent_2_page_0 = _response(json_data={"totalCount": 201, "results": [{"deviceId": "a"}] * 200})+ parent_2_page_1 = _response(json_data={"totalCount": 201, "results": [{"deviceId": "b"}]})+ parent_7_missing = _response(status_code=404)+ parent_10_page_0 = _response(json_data={"totalCount": 1, "results": [{"deviceId": "c"}]})+ rows, session = self._run(+ manager,+ [parents, parent_2_page_0, parent_2_page_1, parent_7_missing, parent_10_page_0],+ endpoint="patch_reports",+ )++ urls = [call.args[0] for call in session.get.call_args_list]+ assert urls[0] == "https://example.jamfcloud.com/api/v3/patch-software-title-configurations"+ assert [url.split("?")[0].rsplit("/", 2)[1] for url in urls[1:]] == ["2", "2", "7", "10"]+ assert "page=1" in urls[2]+ assert len(rows) == 202+ assert {row["softwareTitleConfigurationId"] for row in rows} == {"2", "10"}+ assert rows[-1] == {"deviceId": "c", "softwareTitleConfigurationId": "10"}+ assert manager.save_state.call_args_list == [+ mock.call(JamfProResumeConfig(page=1, parent_id="2")),+ mock.call(JamfProResumeConfig(page=0, parent_id="7")),+ mock.call(JamfProResumeConfig(page=0, parent_id="10")),+ ]++ def test_fan_out_has_one_request_budget_across_all_parents(self):+ manager = self._manager()+ parents = _response(json_data=[{"id": str(parent_id)} for parent_id in range(4)])+ child_page = _response(json_data={"totalCount": 1, "results": [{"deviceId": "a"}]})+ session = _session(+ post_responses=[_response(json_data=TOKEN_JSON)],+ get_responses=[parents, child_page, child_page, child_page],+ )+ 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="patch_reports",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )++ # The parent-list request is outside the child-page budget; only three children are fetched.+ assert session.get.call_count == 4++ def test_fan_out_resumes_from_saved_parent_and_page(self):+ manager = self._manager(resume=JamfProResumeConfig(page=3, parent_id="7"))+ parents = _response(json_data=[{"id": "2"}, {"id": "7"}, {"id": "10"}])+ parent_7 = _response(json_data={"totalCount": 601, "results": [{"deviceId": "a"}]})+ parent_10 = _response(json_data={"totalCount": 1, "results": [{"deviceId": "b"}]})+ _rows, session = self._run(manager, [parents, parent_7, parent_10], endpoint="patch_reports")++ urls = [call.args[0] for call in session.get.call_args_list]+ assert "/7/patch-report?" in urls[1]+ assert "page=3" in urls[1]+ assert "/10/patch-report?" in urls[2]+ assert "page=0" in urls[2]++ def test_fan_out_single_object_child_becomes_one_row(self):+ manager = self._manager()+ parents = _response(json_data=[{"id": "1"}])+ summary = _response(json_data={"softwareTitleId": "s1", "upToDate": 4, "outOfDate": 1})+ rows, _session_ = self._run(manager, [parents, summary], endpoint="patch_summaries")++ assert rows == [{"softwareTitleId": "s1", "upToDate": 4, "outOfDate": 1, "softwareTitleConfigurationId": "1"}]++ def test_unpaginated_incremental_endpoint_sends_filter(self):+ manager = self._manager()+ page = _response(json_data={"totalCount": 1, "results": [{"osUpdatesStatusId": "1"}]})+ rows, session = self._run(+ manager,+ [page],+ endpoint="managed_software_update_statuses",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )++ assert rows == [{"osUpdatesStatusId": "1"}]+ assert session.get.call_args.args[0] == (+ "https://example.jamfcloud.com/api/v1/managed-software-updates/update-statuses"+ "?filter=updated%3E%3D%222024-01-01T00%3A00%3A00.000Z%22"+ )+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")):@@ -546,5 +693,4 @@ class TestJamfProSourceResponse: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.pyindex ab2f491750ce..f72a2a9e617c 100644--- 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.py@@ -32,9 +32,11 @@ class TestJamfProSource:@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")+ # Only these endpoints document a server-side RSQL timestamp filter; everything else is+ # full-refresh. Their records mutate in place, so append mode is never offered.+ assert schemas[endpoint].supports_incremental is (+ endpoint in {"computers", "mdm_commands", "managed_software_update_statuses"}+ )assert schemas[endpoint].supports_append is Falsedef test_get_schemas_filtered_by_names(self):