: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 kandji library, users, and device parameter tables (#113317)
Tom Owers83850785ba27
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 a38446ce32f1..b1617b957d8a 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@@ -4721,9 +4721,9 @@ Diffed against: <https://documenter.gw.postman.com/api/collections/15284493/TzCT- [ ] `vulnerability-management/detections` — per-device CVE detections — the fact table for vulnerability posture reporting (high)- [ ] `vulnerability-management/vulnerabilities` — CVE lookup table resolving the vulnerability IDs carried on detections (high)- [ ] `v2/threat/threat-details` — malware/threat detections per device with quarantine status (high)-- [ ] `users` — lookup table resolving the user IDs already carried on every device record (high)-- [ ] `devices/{device_id}/status` — library-item run status per device — the compliance state behind device_library_items (high)-- [ ] `library/custom-apps, library/custom-scripts, library/custom-profiles, library/ipa-apps` — catalog lookup resolving the library item IDs we already sync in device_library_items (high)+- [x] `users` — lookup table resolving the user IDs already carried on every device record (high)+- [x] `devices/{device_id}/status` — library-item run status per device — the compliance state behind device_library_items (high)+- [x] `library/custom-apps, library/custom-scripts, library/custom-profiles, library/ipa-apps` — catalog lookup resolving the library item IDs we already sync in device_library_items (high)- [ ] `v2/threat/behavioral-detections/events` — behavioral detection event stream, the time-series counterpart to threat details (medium)- [ ] `devices/{device_id}/activity` — per-device activity/state-transition history for enrollment and drift analysis (medium)- [ ] `audit/events` — tenant-wide audit event log — who changed what, when (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/canonical_descriptions.pyindex b1875ee49bf2..903daafa33a3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/canonical_descriptions.py@@ -59,4 +59,86 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"status": "Installation/enforcement status of the library item on the device.",},},+ "device_parameters": {+ "description": "Status of each compliance parameter (security and configuration check) on each device.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "device_id": "Identifier of the device the parameter was evaluated on.",+ "item_id": "Identifier of the parameter.",+ "name": "Name of the parameter.",+ "category": "Category the parameter belongs to.",+ "subcategory": "Subcategory the parameter belongs to.",+ "status": "Result of the parameter on the device (PASS, ERROR, INCOMPATIBLE, PENDING, REMEDIATED, or WARNING).",+ },+ },+ "library_custom_apps": {+ "description": "Custom app library items (uploaded packages) defined in your tenant.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "id": "Unique identifier of the library item.",+ "name": "Name of the custom app.",+ "install_type": "How the app is installed (e.g. package, zip, image).",+ "install_enforcement": "Install enforcement mode (e.g. install_once, continuously_enforce, no_enforcement).",+ "active": "Whether the library item is active.",+ "show_in_self_service": "Whether the app is offered in Self Service.",+ "created_at": "Timestamp the library item was created.",+ "updated_at": "Timestamp the library item was last updated.",+ },+ },+ "library_custom_profiles": {+ "description": "Custom configuration profile library items defined in your tenant.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "id": "Unique identifier of the library item.",+ "name": "Name of the custom profile.",+ "active": "Whether the library item is active.",+ "profile": "The configuration profile payload (XML).",+ "mdm_identifier": "MDM payload identifier of the profile.",+ "created_at": "Timestamp the library item was created.",+ "updated_at": "Timestamp the library item was last updated.",+ },+ },+ "library_custom_scripts": {+ "description": "Custom script library items defined in your tenant.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "id": "Unique identifier of the library item.",+ "name": "Name of the custom script.",+ "active": "Whether the library item is active.",+ "execution_frequency": "How often the script runs (e.g. once, every_15_min, every_day, no_enforcement).",+ "script": "Body of the audit/enforcement script.",+ "remediation_script": "Body of the remediation script.",+ "created_at": "Timestamp the library item was created.",+ "updated_at": "Timestamp the library item was last updated.",+ },+ },+ "library_in_house_apps": {+ "description": "In-house (.ipa) app library items defined in your tenant.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "id": "Unique identifier of the library item.",+ "name": "Name of the in-house app library item.",+ "app_identifier": "Bundle identifier of the app.",+ "app_version": "Version of the uploaded app.",+ "minimum_os_version": "Minimum OS version the app supports.",+ "active": "Whether the library item is active.",+ "created_at": "Timestamp the library item was created.",+ "updated_at": "Timestamp the library item was last updated.",+ },+ },+ "users": {+ "description": "Users imported from your user directory integrations.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "id": "Unique identifier of the user.",+ "name": "Name of the user.",+ "email": "Email address of the user.",+ "active": "Whether the user is active in the directory.",+ "archived": "Whether the user is archived in Kandji.",+ "integration": "Directory integration the user was imported from.",+ "device_count": "Number of devices assigned to the user.",+ "created_at": "Timestamp the user was created in Kandji.",+ "updated_at": "Timestamp the user was last updated in Kandji.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/kandji.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/kandji.pyindex 7abc33987ab4..d26792270715 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/kandji.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/kandji.py@@ -1,7 +1,9 @@import refrom collections.abc import Iterablefrom typing import Any, Optional, cast+from urllib.parse import parse_qsl, urlsplit+from requests import Request, Responsefrom requests.exceptions import RequestExceptionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -13,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resbuild_dependent_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,OffsetPaginator,SinglePagePaginator,)@@ -68,7 +71,38 @@ def _rest_api_client_config(base_url: str, api_token: str) -> ClientConfig:}-def _list_paginator(config: KandjiEndpointConfig) -> OffsetPaginator:+class KandjiNextLinkPaginator(BasePaginator):+ """Pages by copying the query string of the body's `next` URL onto the original request.++ The request is never sent to the `next` URL itself, whose host can differ from the validated+ tenant API host (Kandji's docs show `next` links on the non-`api` subdomain), so the bearer+ token only ever goes to the host built by `build_base_url`.+ """++ def __init__(self) -> None:+ super().__init__()+ self._next_params: dict[str, str] | None = None++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ body = response.json()+ next_url = body.get("next") if isinstance(body, dict) else None+ next_params = dict(parse_qsl(urlsplit(next_url).query)) if next_url else None+ if not next_params or next_params == self._next_params:+ self._has_next_page = False+ return+ self._next_params = next_params+ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ if self._next_params is not None:+ request.params = {**(request.params or {}), **self._next_params}+++def _list_paginator(config: KandjiEndpointConfig) -> BasePaginator:+ if config.pagination == "single":+ return SinglePagePaginator()+ if config.pagination == "next_link":+ return KandjiNextLinkPaginator()return OffsetPaginator(limit=config.page_size,offset_param="offset",@@ -116,9 +150,9 @@ def validate_credentials(def get_resource(config: KandjiEndpointConfig) -> EndpointResource:endpoint_config: Endpoint = {"path": config.path,- "params": {},+ "params": dict(config.params),"data_selector": config.data_selector,- "paginator": _list_paginator(config) if config.paginated else SinglePagePaginator(),+ "paginator": _list_paginator(config),}return {"name": config.name,@@ -171,7 +205,7 @@ def kandji_source("data_selector": parent_config.data_selector,},child_endpoint_extra={- "paginator": SinglePagePaginator(),+ "paginator": _list_paginator(config),"data_selector": config.data_selector,},),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/settings.pyindex 8df7a201fd4d..fa292c395d1c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/settings.py@@ -1,4 +1,5 @@from dataclasses import dataclass, field+from typing import Any, Literalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (DependentEndpointConfig,@@ -8,13 +9,17 @@ from products.warehouse_sources.backend.types import IncrementalField# Kandji's List Devices endpoint caps `limit` at 300; the other list endpoints share the same cap.DEVICES_PAGE_SIZE = 300+# "offset": limit/offset. "next_link": follow the query string of the body's `next` URL (library and+# users endpoints). "single": the full list comes back in one response (per-device children).+KandjiPagination = Literal["offset", "next_link", "single"]+# Kandji exposes per-tenant, region-scoped base URLs. Both region and subdomain are user-supplied,# and the API lives under the `/api/v1` prefix on that host.US_API_HOST_TEMPLATE = "https://{subdomain}.api.kandji.io/api/v1"EU_API_HOST_TEMPLATE = "https://{subdomain}.api.eu.kandji.io/api/v1"-@dataclass+@dataclass(frozen=True)class KandjiEndpointConfig:name: strpath: str@@ -22,13 +27,12 @@ class KandjiEndpointConfig:# ("results", "apps", "library_items") for endpoints that nest their rows.data_selector: strprimary_key: str | list[str]- # Top-level list endpoints paginate with limit/offset. Per-device children return the full- # list in one response, so they are fetched as a single page.- paginated: bool = True+ pagination: KandjiPagination = "offset"# `total`-like count field in the response, used to terminate offset pagination. `None` when the# endpoint returns a bare array with no count (we then stop on the first empty/short page).total_path: str | None = Nonepage_size: int = DEVICES_PAGE_SIZE+ params: dict[str, Any] = field(default_factory=dict)fanout: DependentEndpointConfig | None = None# Kandji has no server-side updated-since filter on these endpoints, so every stream is# full-refresh; these stay empty but satisfy the fan-out helper's endpoint protocol.@@ -59,7 +63,7 @@ KANDJI_ENDPOINTS: dict[str, KandjiEndpointConfig] = {# Details returns a single nested object per device; `$` selects that object.data_selector="$",primary_key="device_id",- paginated=False,+ pagination="single",fanout=DependentEndpointConfig(parent_name="devices",resolve_param="device_id",@@ -75,7 +79,7 @@ KANDJI_ENDPOINTS: dict[str, KandjiEndpointConfig] = {# App rows are unique per device; `bundle_id` identifies the app within a device. The parent# device id keeps the key unique across the table (this stream aggregates every device's apps).primary_key=["device_id", "bundle_id"],- paginated=False,+ pagination="single",fanout=DependentEndpointConfig(parent_name="devices",resolve_param="device_id",@@ -90,7 +94,24 @@ KANDJI_ENDPOINTS: dict[str, KandjiEndpointConfig] = {data_selector="library_items",# Library-item `id` is unique within a device; the parent device id keeps it unique table-wide.primary_key=["device_id", "id"],- paginated=False,+ pagination="single",+ fanout=DependentEndpointConfig(+ parent_name="devices",+ resolve_param="device_id",+ resolve_field="device_id",+ include_from_parent=["device_id"],+ parent_field_renames={"device_id": "device_id"},+ ),+ ),+ "device_parameters": KandjiEndpointConfig(+ name="device_parameters",+ # Device Status returns `library_items` and `parameters`. Only `parameters` is synced: the+ # library-item half is a subset of what `device_library_items` already carries.+ path="/devices/{device_id}/status",+ data_selector="parameters",+ # `item_id` identifies the parameter, which repeats across devices.+ primary_key=["device_id", "item_id"],+ pagination="single",fanout=DependentEndpointConfig(parent_name="devices",resolve_param="device_id",@@ -99,6 +120,43 @@ KANDJI_ENDPOINTS: dict[str, KandjiEndpointConfig] = {parent_field_renames={"device_id": "device_id"},),),+ "library_custom_apps": KandjiEndpointConfig(+ name="library_custom_apps",+ path="/library/custom-apps",+ data_selector="results",+ primary_key="id",+ pagination="next_link",+ ),+ "library_custom_profiles": KandjiEndpointConfig(+ name="library_custom_profiles",+ path="/library/custom-profiles",+ data_selector="results",+ primary_key="id",+ pagination="next_link",+ ),+ "library_custom_scripts": KandjiEndpointConfig(+ name="library_custom_scripts",+ path="/library/custom-scripts",+ data_selector="results",+ primary_key="id",+ pagination="next_link",+ ),+ "library_in_house_apps": KandjiEndpointConfig(+ name="library_in_house_apps",+ path="/library/ipa-apps",+ data_selector="results",+ primary_key="id",+ pagination="next_link",+ ),+ "users": KandjiEndpointConfig(+ name="users",+ path="/users",+ # List Users pages with a `cursor` carried in the `next` URL; it has no `count`.+ data_selector="results",+ primary_key="id",+ pagination="next_link",+ params={"sizePerPage": DEVICES_PAGE_SIZE},+ ),}ENDPOINTS = tuple(KANDJI_ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/source.pyindex b8ca609ed4bc..fe1c505b0363 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/source.py@@ -117,7 +117,7 @@ class KandjiSource(SimpleSource[KandjiSourceConfig]):"Connect Kandji with a tenant-level **API token**, created in Kandji under ""**Settings → Access**. Your API URL is shown there too — enter its **subdomain** and pick ""the matching **region** (US or EU). The token needs read access to the devices, blueprints, "- "and device-detail endpoints for the tables you want to sync."+ "device-detail, library, and users endpoints for the tables you want to sync."),docsUrl="https://posthog.com/docs/cdp/sources/kandji",iconPath="/static/services/kandji.png",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji.pyindex ddd7ddd184aa..371f0880b70a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji.py@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resSinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji import (+ KandjiNextLinkPaginator,build_base_url,get_resource,kandji_source,@@ -165,15 +166,24 @@ class TestKandjiTransport:# bundle_id is only unique within a device, so the parent device id is part of the key.assert response.primary_keys == ["device_id", "bundle_id"]+ @parameterized.expand(+ [+ ("library_items", "device_library_items", "library_items"),+ # Device Status also returns `library_items`; only its `parameters` list is synced.+ ("status_parameters", "device_parameters", "parameters"),+ ]+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji.build_dependent_resource")- def test_kandji_source_fanout_wires_single_page_children(self, mock_build_dependent_resource) -> None:+ def test_kandji_source_fanout_wires_single_page_children(+ self, _name, endpoint, expected_selector, mock_build_dependent_resource+ ) -> None:mock_build_dependent_resource.return_value = iter([])kandji_source(api_token="tok",subdomain="accuhive",region="us",- endpoint="device_library_items",+ endpoint=endpoint,team_id=1,job_id="job-1",)@@ -182,8 +192,42 @@ class TestKandjiTransport:# Kandji is full-refresh only — the fan-out must not request incremental merge behavior.assert kwargs["should_use_incremental_field"] is Falseassert kwargs["db_incremental_field_last_value"] is None- assert kwargs["child_endpoint_extra"]["data_selector"] == "library_items"+ assert kwargs["child_endpoint_extra"]["data_selector"] == expected_selectorassert isinstance(kwargs["child_endpoint_extra"]["paginator"], SinglePagePaginator)# The devices parent lists a bare array.assert kwargs["parent_endpoint_extra"]["data_selector"] == "$"assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], OffsetPaginator)+++class TestKandjiNextLinkPaginator:+ def test_copies_next_query_onto_original_request(self) -> None:+ paginator = KandjiNextLinkPaginator()+ request = requests.Request(+ method="GET", url="https://accuhive.api.kandji.io/api/v1/users", params={"sizePerPage": 300}+ )+ response = Mock()+ # Kandji documents `next` links on the non-`api` host; the token must not follow them there.+ response.json.return_value = {"next": "https://accuhive.kandji.io/api/v1/users?cursor=cD0yOTE0Mw%3D%3D"}++ paginator.update_state(response, [{"id": "u1"}])+ paginator.update_request(request)++ assert paginator.has_next_page is True+ assert request.url == "https://accuhive.api.kandji.io/api/v1/users"+ assert request.params == {"sizePerPage": 300, "cursor": "cD0yOTE0Mw=="}++ @parameterized.expand(+ [+ ("null_next", [{"next": None}]),+ ("missing_next", [{"results": []}]),+ ("repeated_next", [{"next": "https://x/api/v1/library/custom-apps?page=2"}] * 2),+ ]+ )+ def test_stops_paging(self, _name, bodies) -> None:+ paginator = KandjiNextLinkPaginator()+ for body in bodies:+ response = Mock()+ response.json.return_value = body+ paginator.update_state(response, [])++ assert paginator.has_next_page is False