: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 mobile group and patch policy tables (#113303)
Tom Owers92e90e642471
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 a8daae263e93..ce06c3708c44 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@@ -4498,13 +4498,13 @@ Today (9): `buildings`, `categories`, `computer_groups`, `computers`, `departmenDiffed against: <https://developer.jamf.com/jamf-pro/reference/get_v1-buildings>- [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/v2/computer-groups/smart-group-membership/{id} and /static-group-membership/{id}`~~ — skipped: the Jamf Pro API has no static computer group membership endpoint, and `computers` already carries every computer's smart and static memberships in its `groupMemberships` section (high)+- [x] `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). Added as `mobile_device_groups`, `mobile_device_smart_group_memberships` and `mobile_device_static_group_memberships` (fan-out over smart or static groups, cut down to the device id).- [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)+- [x] `GET /api/v2/patch-policies and /api/v2/patch-policies/{id}/logs` — per-device patch deployment outcomes for the packages we sync (medium). Added as `patch_policies` and `patch_policy_logs` (fan-out over `patch_policies`).+- ~~`GET /api/v1/computers-inventory/filevault (and /{id}/filevault)`~~ — skipped: `computers` already syncs the `DISK_ENCRYPTION` section with the same compliance fields; the only extra field is the personal recovery key, a secret that does not belong in the warehouse (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)- [ ] `GET /api/v1/volume-purchasing-locations/{id}/content and /api/v1/volume-purchasing-subscriptions` — VPP app license inventory and consumption (medium)- [ ] `GET /api/v1/device-enrollments and /{id}/devices` — ADE/DEP enrollment records and their device rosters (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 18cd18782b08..07e393454c26 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@@ -208,4 +208,61 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"onDashboard": "Whether the title appears on the Jamf Pro dashboard.",},},+ "patch_policies": {+ "description": "Patch policies that deploy software title updates, with their deployment counts by status.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-patch-policies",+ "columns": {+ "id": "Unique identifier of the patch policy.",+ "policyName": "Name of the patch policy.",+ "policyEnabled": "Whether the patch policy is enabled.",+ "policyTargetVersion": "Software title version the policy deploys.",+ "policyDeploymentMethod": "How the policy deploys the update (for example, self service or automatic install).",+ "softwareTitle": "Name of the software title the policy patches.",+ "softwareTitleConfigurationId": "Identifier of the software title configuration the policy belongs to.",+ "pending": "Number of devices with a pending deployment.",+ "completed": "Number of devices where the deployment completed.",+ "deferred": "Number of devices where the user deferred the deployment.",+ "failed": "Number of devices where the deployment failed.",+ },+ },+ "patch_policy_logs": {+ "description": "Deployment log for each patch policy: one row per device with its latest deployment status.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-patch-policies-id-logs",+ "columns": {+ "patchPolicyId": "Identifier of the patch policy.",+ "deviceId": "Identifier of the device.",+ "deviceName": "Name of the device.",+ "statusCode": "Numeric deployment status code.",+ "statusDate": "Timestamp of the latest status change.",+ "statusEnum": "Deployment status of the device.",+ "attemptNumber": "Number of deployment attempts on the device.",+ "ignoredForPatchPolicyId": "Identifier of the patch policy the device is ignored for, if any.",+ },+ },+ "mobile_device_groups": {+ "description": "Smart and static mobile device groups defined in Jamf Pro.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-mobile-device-groups",+ "columns": {+ "id": "Unique identifier of the mobile device group.",+ "name": "Name of the mobile device group.",+ "description": "Description of the mobile device group.",+ "isSmartGroup": "Whether the group is a smart group (criteria-based) rather than a static group.",+ },+ },+ "mobile_device_smart_group_memberships": {+ "description": "Membership of each smart mobile device group: one row per group and member device.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-mobile-device-groups-smart-group-membership-id",+ "columns": {+ "mobileDeviceGroupId": "Identifier of the smart mobile device group.",+ "mobileDeviceId": "Identifier of the member mobile device.",+ },+ },+ "mobile_device_static_group_memberships": {+ "description": "Membership of each static mobile device group: one row per group and member device.",+ "docs_url": "https://developer.jamf.com/jamf-pro/reference/get_v2-mobile-device-groups-static-group-membership-id",+ "columns": {+ "mobileDeviceGroupId": "Identifier of the static mobile device group.",+ "mobileDeviceId": "Identifier of the member mobile device.",+ },+ },}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 8d24f7917665..47c33329bbfb 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@@ -48,6 +48,11 @@ MAX_DOWNLOAD_SECONDS = 300# 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+# Fan-out parents are collected before any child is fetched, so the host also must not be able to+# grow that list without bound. Real parents (titles, policies, groups) number in the hundreds and+# have short numeric ids.+MAX_PARENT_IDS = 100_000+MAX_PARENT_ID_LENGTH = 256# 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@@ -428,6 +433,8 @@ def _iter_endpoint_pages(def shape(row: dict[str, Any]) -> dict[str, Any]:row = _hoist_cursor(config, row)+ if config.row_fields:+ row = {key: row.get(key) for key in config.row_fields}if parent_id is not None and config.parent_id_field:row = {**row, config.parent_id_field: parent_id}return row@@ -472,6 +479,45 @@ def _iter_endpoint_pages(page += 1+def _fetch_parent_ids(+ fetch_page: Callable[[str], Any], host: str, config: JamfProEndpointConfig, parent_config: JamfProEndpointConfig+) -> list[str]:+ """Collect the ids of the parents to fan out over, keeping only the ids so memory stays bounded."""+ ids: list[str] = []++ def collect(rows: list[dict[str, Any]]) -> None:+ for row in rows:+ if row.get("id") is None:+ continue+ if config.parent_filter is not None and row.get(config.parent_filter[0]) != config.parent_filter[1]:+ continue+ parent_id = str(row["id"])+ if len(parent_id) > MAX_PARENT_ID_LENGTH or len(ids) >= MAX_PARENT_IDS:+ raise JamfProPaginationLimitError(+ f"Jamf Pro {parent_config.name} returned more parents or longer ids than any real tenant holds"+ )+ ids.append(parent_id)++ if not parent_config.paginated:+ data = fetch_page(_build_url(host, parent_config, {}))+ collect(data if isinstance(data, list) else data.get("results", []))+ return ids++ params = _build_params(parent_config, False, None)+ seen = 0+ for page in range(MAX_PAGES):+ data = fetch_page(_build_url(host, parent_config, {**params, "page": page}))+ results = data.get("results", [])+ collect(results)+ seen += len(results)+ total_count = data.get("totalCount")+ if not results or (total_count is not None and seen >= total_count):+ return ids+ raise JamfProPaginationLimitError(+ f"Jamf Pro pagination for {parent_config.name} exceeded {MAX_PAGES} pages without terminating"+ )++def get_rows(host: str,credentials: JamfProCredentials,@@ -553,10 +599,8 @@ def get_rows(returnparent_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)+ parent_ids = sorted(_fetch_parent_ids(fetch_page, host, config, parent_config), 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)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 2f97cae0fc7e..aa111c4b2ad1 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@@ -1,5 +1,5 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Any, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -64,6 +64,10 @@ class JamfProEndpointConfig:# endpoint, and the parent id is written to `parent_id_field` on every child row.parent: Optional[str] = Noneparent_id_field: Optional[str] = None+ # (field, value): fan out only over parent rows whose `field` equals `value`.+ parent_filter: Optional[tuple[str, Any]] = None+ # Keep only these keys of each child row (before the parent id is added).+ row_fields: list[str] = field(default_factory=list)JAMF_PRO_ENDPOINTS: dict[str, JamfProEndpointConfig] = {@@ -173,6 +177,48 @@ JAMF_PRO_ENDPOINTS: dict[str, JamfProEndpointConfig] = {parent="patch_software_title_configurations",parent_id_field="softwareTitleConfigurationId",),+ "patch_policies": JamfProEndpointConfig(+ name="patch_policies",+ path="/api/v2/patch-policies",+ ),+ "patch_policy_logs": JamfProEndpointConfig(+ name="patch_policy_logs",+ path="/api/v2/patch-policies/{id}/logs",+ primary_keys=["patchPolicyId", "deviceId"],+ sort="deviceId:asc",+ parent="patch_policies",+ parent_id_field="patchPolicyId",+ ),+ "mobile_device_groups": JamfProEndpointConfig(+ name="mobile_device_groups",+ path="/api/v2/mobile-device-groups",+ paginated=False,+ sort=None,+ ),+ # The membership endpoints return full mobile device inventory records (including the AirPlay+ # password), so rows are cut down to the device id: a junction to the mobile_devices table.+ "mobile_device_smart_group_memberships": JamfProEndpointConfig(+ name="mobile_device_smart_group_memberships",+ path="/api/v2/mobile-device-groups/smart-group-membership/{id}",+ primary_keys=["mobileDeviceGroupId", "mobileDeviceId"],+ sort="mobileDeviceId:asc",+ capture_samples=False,+ parent="mobile_device_groups",+ parent_id_field="mobileDeviceGroupId",+ parent_filter=("isSmartGroup", True),+ row_fields=["mobileDeviceId"],+ ),+ "mobile_device_static_group_memberships": JamfProEndpointConfig(+ name="mobile_device_static_group_memberships",+ path="/api/v2/mobile-device-groups/static-group-membership/{id}",+ primary_keys=["mobileDeviceGroupId", "mobileDeviceId"],+ sort="mobileDeviceId:asc",+ capture_samples=False,+ parent="mobile_device_groups",+ parent_id_field="mobileDeviceGroupId",+ parent_filter=("isSmartGroup", False),+ row_fields=["mobileDeviceId"],+ ),}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 505c32915a0d..ebb996a8e540 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, 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.+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, Smart Mobile Device Groups, Static Mobile Device Groups, Scripts, Packages, Users, Patch Management Software Titles, Patch Policies), 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.""",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 ef33096712bd..c7e663a3414e 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@@ -529,6 +529,68 @@ class TestGetRows:assert rows == [{"softwareTitleId": "s1", "upToDate": 4, "outOfDate": 1, "softwareTitleConfigurationId": "1"}]+ def test_fan_out_pages_through_a_paginated_parent(self):+ manager = self._manager()+ parents_page_0 = _response(json_data={"totalCount": 201, "results": [{"id": str(i)} for i in range(200)]})+ parents_page_1 = _response(json_data={"totalCount": 201, "results": [{"id": "200"}]})+ child = _response(json_data={"totalCount": 1, "results": [{"deviceId": "d1", "statusEnum": "COMPLETE"}]})+ rows, session = self._run(+ manager, [parents_page_0, parents_page_1] + [child] * 201, endpoint="patch_policy_logs"+ )++ urls = [call.args[0] for call in session.get.call_args_list]+ assert urls[0].startswith("https://example.jamfcloud.com/api/v2/patch-policies?")+ assert "page=1" in urls[1]+ assert "/patch-policies/200/logs?" in urls[-1]+ assert len(rows) == 201+ assert rows[-1] == {"deviceId": "d1", "statusEnum": "COMPLETE", "patchPolicyId": "200"}++ def test_fan_out_refuses_an_unbounded_parent_list(self):+ manager = self._manager()+ endless_parents = _response(json_data={"totalCount": 10**9, "results": [{"id": "1"}, {"id": "2"}]})+ session = _session(post_responses=[_response(json_data=TOKEN_JSON)], get_responses=[endless_parents] * 3)+ with (+ mock.patch.object(jamf_pro_module, "make_tracked_session", return_value=session),+ mock.patch.object(jamf_pro_module, "MAX_PARENT_IDS", 3),+ ):+ with pytest.raises(JamfProPaginationLimitError):+ list(+ get_rows(+ host="example.jamfcloud.com",+ credentials=CLIENT_CREDENTIALS,+ endpoint="patch_policy_logs",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )++ assert all("/logs" not in call.args[0] for call in session.get.call_args_list)++ @pytest.mark.parametrize(+ "endpoint, expected_parent_ids",+ [+ ("mobile_device_smart_group_memberships", ["1"]),+ ("mobile_device_static_group_memberships", ["2"]),+ ],+ )+ def test_mobile_group_membership_fans_out_by_group_type_and_keeps_only_device_ids(+ self, endpoint, expected_parent_ids+ ):+ manager = self._manager()+ groups = _response(json_data=[{"id": 1, "isSmartGroup": True}, {"id": 2, "isSmartGroup": False}])+ members = _response(+ json_data={+ "totalCount": 1,+ "results": [{"mobileDeviceId": "5", "displayName": "iPad", "airPlayPassword": "pw"}],+ }+ )+ rows, session = self._run(manager, [groups, members], endpoint=endpoint)++ urls = [call.args[0] for call in session.get.call_args_list]+ assert [url.split("?")[0].rsplit("/", 1)[1] for url in urls[1:]] == expected_parent_ids+ assert rows == [{"mobileDeviceId": "5", "mobileDeviceGroupId": expected_parent_ids[0]}]+def test_unpaginated_incremental_endpoint_sends_filter(self):manager = self._manager()page = _response(json_data={"totalCount": 1, "results": [{"osUpdatesStatusId": "1"}]})