: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 kandji import source (#71149)
Tom Owersda61417aee34
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex fab04f9ea27d..b58aa3698e7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -251,6 +251,7 @@ the row lists both.| justcall | HTTP | requests | ✅ || justsift | HTTP | requests | ✅ || k6_cloud | HTTP | requests | ✅ |+| kandji | HTTP | requests (rest_source.RESTClient) | ✅ || katana | HTTP | requests | ✅ || kernel | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ |@@ -707,7 +708,6 @@ doesn't conflict with concurrent PRs.- justsift- kafka- kajabi-- kandji- kapa_ai- keka- kickscalediff --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 564d203c2cd1..3b0b1e771b0b 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@@ -2216,7 +2216,9 @@ class KajabiSourceConfig(config.Config):@config.configclass KandjiSourceConfig(config.Config):- pass+ api_token: str+ subdomain: str+ region: Literal["us", "eu"] = config.value(default="us")@config.configdiff --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.pynew file mode 100644index 000000000000..b1875ee49bf2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/canonical_descriptions.py@@ -0,0 +1,62 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from Kandji's (Iru) public API docs. Columns not covered here fall back to LLM enrichment,+# so partial coverage is fine; keys match the endpoint/schema names returned by `get_schemas`.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "devices": {+ "description": "Every device enrolled in your Kandji tenant, one row per device.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "device_id": "Unique identifier for the device in Kandji.",+ "device_name": "Display name of the device.",+ "serial_number": "Hardware serial number of the device.",+ "platform": "Device platform (e.g. Mac, iPhone, iPad, AppleTV).",+ "os_version": "Operating system version currently installed on the device.",+ "model": "Hardware model of the device.",+ "asset_tag": "Asset tag assigned to the device.",+ "blueprint_id": "Identifier of the blueprint the device is assigned to.",+ "blueprint_name": "Name of the blueprint the device is assigned to.",+ "last_check_in": "Timestamp of the device's most recent check-in with Kandji.",+ "user": "User associated with the device.",+ },+ },+ "blueprints": {+ "description": "Configuration blueprints defined in your tenant that group library items and settings.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "id": "Unique identifier for the blueprint.",+ "name": "Name of the blueprint.",+ "enrollment_code": "Enrollment code configuration for the blueprint.",+ "device_count": "Number of devices assigned to the blueprint.",+ },+ },+ "device_details": {+ "description": "Detailed inventory for each device (hardware, network, security, and OS sections).",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "device_id": "Identifier of the device these details belong to.",+ },+ },+ "device_apps": {+ "description": "Applications installed on each device, one row per device/app pairing.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "device_id": "Identifier of the device the app is installed on.",+ "app_name": "Name of the installed application.",+ "version": "Installed version of the application.",+ "bundle_id": "Application bundle identifier.",+ },+ },+ "device_library_items": {+ "description": "Library items (profiles, apps, scripts) applied to each device and their status.",+ "docs_url": "https://api-docs.kandji.io/",+ "columns": {+ "device_id": "Identifier of the device the library item is applied to.",+ "id": "Unique identifier of the library item.",+ "name": "Name of the library item.",+ "status": "Installation/enforcement status of the library item on the device.",+ },+ },+}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.pynew file mode 100644index 000000000000..7e910ccf9861--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/kandji.py@@ -0,0 +1,187 @@+import re+from collections.abc import Iterable+from typing import Any, Optional, cast++from requests.exceptions import RequestException++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.settings import (+ EU_API_HOST_TEMPLATE,+ KANDJI_ENDPOINTS,+ US_API_HOST_TEMPLATE,+ KandjiEndpointConfig,+)++REGION_TEMPLATES = {+ "us": US_API_HOST_TEMPLATE,+ "eu": EU_API_HOST_TEMPLATE,+}++# Kandji subdomains are a single DNS label. Allowlist strictly: any other character (`.`, `/`,+# `?`, `#`, `@`, `%`, …) could rewrite the URL authority and send the bearer token elsewhere.+_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$")+++def build_base_url(subdomain: str, region: str) -> str:+ """Build the tenant- and region-scoped API base URL (with the `/api/v1` prefix).++ Raises `ValueError` for an unknown region or a subdomain that is not a bare DNS label,+ so a malformed value is rejected before any request carries the token.+ """+ template = REGION_TEMPLATES.get(region.lower().strip())+ if template is None:+ raise ValueError("Region must be either 'us' or 'eu'.")++ clean_subdomain = subdomain.strip()+ if not _SUBDOMAIN_RE.match(clean_subdomain):+ raise ValueError("Subdomain must be the single label from your Kandji API URL (e.g. 'accuhive').")++ return template.format(subdomain=clean_subdomain)+++def _auth_headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}+++def _rest_api_client_config(base_url: str, api_token: str) -> ClientConfig:+ return {+ "base_url": base_url,+ "auth": {"type": "bearer", "token": api_token},+ "headers": {"Accept": "application/json"},+ }+++def _list_paginator(config: KandjiEndpointConfig) -> OffsetPaginator:+ return OffsetPaginator(+ limit=config.page_size,+ offset_param="offset",+ limit_param="limit",+ total_path=config.total_path,+ )+++def validate_credentials(+ api_token: str, subdomain: str, region: str, schema_name: Optional[str] = None+) -> tuple[bool, str | None]:+ """Probe the token against List Devices — the cheapest authenticated call.++ Accepts a 403 at source-create (a token may legitimately lack scope for some endpoints, which the+ user can still deselect); a 403 for a specific schema is surfaced as a permission error.+ """+ try:+ base_url = build_base_url(subdomain, region)+ except ValueError as exc:+ return False, str(exc)++ try:+ response = make_tracked_session().get(+ f"{base_url}/devices",+ headers=_auth_headers(api_token),+ params={"limit": 1},+ timeout=10,+ )+ except RequestException as exc:+ return False, f"Could not reach the Kandji API: {exc}"++ if response.status_code == 401:+ return False, "Invalid Kandji API token."+ if response.status_code == 403:+ if schema_name is not None:+ return False, "Your Kandji API token is missing the scope required for this table."+ # Valid token, missing scope for this endpoint — don't block source-create.+ return True, None+ if response.status_code != 200:+ return False, f"Kandji API returned an unexpected status ({response.status_code})."++ return True, None+++def get_resource(config: KandjiEndpointConfig) -> EndpointResource:+ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {},+ "data_selector": config.data_selector,+ "paginator": _list_paginator(config) if config.paginated else SinglePagePaginator(),+ }+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(config: KandjiEndpointConfig, items_fn) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_key if isinstance(config.primary_key, list) else [config.primary_key],+ # Full refresh only — Kandji's list endpoints expose no stable updated-since cursor.+ sort_mode="asc",+ )+++def kandji_source(+ api_token: str,+ subdomain: str,+ region: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ config = KANDJI_ENDPOINTS[endpoint]+ base_url = build_base_url(subdomain, region)+ client_config = _rest_api_client_config(base_url, api_token)++ if config.fanout is not None:+ parent_config = KANDJI_ENDPOINTS[config.fanout.parent_name]+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=KANDJI_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ page_size_param="limit",+ parent_endpoint_extra={+ "paginator": _list_paginator(parent_config),+ "data_selector": parent_config.data_selector,+ },+ child_endpoint_extra={+ "paginator": SinglePagePaginator(),+ "data_selector": config.data_selector,+ },+ ),+ )+ return _make_source_response(config, lambda: dependent_resource)++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(config)],+ }+ resource = rest_api_resource(rest_config, team_id, job_id, None)+ return _make_source_response(config, lambda: resource)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.pynew file mode 100644index 000000000000..8df7a201fd4d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/settings.py@@ -0,0 +1,108 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+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++# 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+class KandjiEndpointConfig:+ name: str+ path: str+ # jsonpath selector into the response body: "$" for a bare array, or the wrapper key+ # ("results", "apps", "library_items") for endpoints that nest their rows.+ data_selector: str+ primary_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+ # `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 = None+ page_size: int = DEVICES_PAGE_SIZE+ 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.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+++KANDJI_ENDPOINTS: dict[str, KandjiEndpointConfig] = {+ "devices": KandjiEndpointConfig(+ name="devices",+ path="/devices",+ # List Devices returns a bare JSON array with no count/next, so we page until an empty response.+ data_selector="$",+ primary_key="device_id",+ total_path=None,+ ),+ "blueprints": KandjiEndpointConfig(+ name="blueprints",+ path="/blueprints",+ # Blueprints uses the wrapped `{count, next, previous, results}` shape.+ data_selector="results",+ primary_key="id",+ total_path="count",+ ),+ "device_details": KandjiEndpointConfig(+ name="device_details",+ path="/devices/{device_id}/details",+ # Details returns a single nested object per device; `$` selects that object.+ data_selector="$",+ primary_key="device_id",+ paginated=False,+ 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_apps": KandjiEndpointConfig(+ name="device_apps",+ path="/devices/{device_id}/apps",+ data_selector="apps",+ # 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,+ 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_library_items": KandjiEndpointConfig(+ name="device_library_items",+ path="/devices/{device_id}/library-items",+ 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,+ 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"},+ ),+ ),+}++ENDPOINTS = tuple(KANDJI_ENDPOINTS)++# Kandji's documented list endpoints expose no reliable updated-since/created-since filter or stable+# cursor, so every stream is full-refresh only. No endpoint advertises incremental fields.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in 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 d97a1825b483..f04ede7ec232 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@@ -1,30 +1,155 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KandjiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji import (+ kandji_source,+ validate_credentials as validate_kandji_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass KandjiSource(SimpleSource[KandjiSourceConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KANDJI+ @property+ def connection_host_fields(self) -> list[str]:+ # `subdomain` and `region` determine which host the stored API token is sent to;+ # retargeting either must force the editor to re-enter the token.+ return ["subdomain", "region"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your Kandji API token is invalid or expired. Generate a new token in Settings → Access and reconnect.",+ "403 Client Error: Forbidden for url": "Your Kandji API token is missing the scope required to sync this table. Update the token's permissions in Settings → Access and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: KandjiSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ 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: KandjiSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_kandji_credentials(+ api_token=config.api_token,+ subdomain=config.subdomain,+ region=config.region,+ schema_name=schema_name,+ )++ def source_for_pipeline(self, config: KandjiSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return kandji_source(+ api_token=config.api_token,+ subdomain=config.subdomain,+ region=config.region,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.KANDJI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Kandji (Iru Endpoint Management)",+ caption=(+ "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."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/kandji",iconPath="/static/services/kandji.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="subdomain",+ label="Subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="accuhive",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.kandji.io)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.kandji.io)", value="eu"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)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.pynew file mode 100644index 000000000000..ddd7ddd184aa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji.py@@ -0,0 +1,189 @@+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji import (+ build_base_url,+ get_resource,+ kandji_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.settings import KANDJI_ENDPOINTS+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestKandjiTransport:+ @parameterized.expand(+ [+ ("us", "accuhive", "us", "https://accuhive.api.kandji.io/api/v1"),+ ("eu", "accuhive", "eu", "https://accuhive.api.eu.kandji.io/api/v1"),+ ("region_case_insensitive", "accuhive", "US", "https://accuhive.api.kandji.io/api/v1"),+ ("subdomain_trimmed", " accuhive ", "us", "https://accuhive.api.kandji.io/api/v1"),+ ]+ )+ def test_build_base_url(self, _name, subdomain, region, expected) -> None:+ assert build_base_url(subdomain, region) == expected++ @parameterized.expand(+ [+ ("unknown_region", "accuhive", "apac"),+ ("empty_subdomain", "", "us"),+ ("subdomain_with_dot", "accuhive.api.kandji.io", "us"),+ ("subdomain_with_slash", "accuhive/devices", "us"),+ # URL metacharacters would rewrite the request authority and leak the bearer token+ # to an attacker-controlled host (e.g. "attacker?" resolves to https://attacker/).+ ("subdomain_with_query", "attacker?", "us"),+ ("subdomain_with_fragment", "attacker#", "us"),+ ("subdomain_with_percent_encoding", "attacker%2eexample%2ecom", "us"),+ ("subdomain_with_userinfo", "user@attacker", "us"),+ ("subdomain_with_colon", "attacker:443", "us"),+ ("subdomain_leading_hyphen", "-accuhive", "us"),+ ]+ )+ def test_build_base_url_rejects_bad_input(self, _name, subdomain, region) -> None:+ with pytest.raises(ValueError):+ build_base_url(subdomain, region)++ @parameterized.expand(+ [+ ("unauthorized", 401, None, False),+ ("forbidden_at_create", 403, None, True),+ ("forbidden_for_schema", 403, "devices", False),+ ("ok", 200, None, True),+ ("unexpected", 500, None, False),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self, _name, status_code, schema_name, expected_ok, mock_session+ ) -> None:+ response = Mock(status_code=status_code)+ mock_session.return_value.get.return_value = response++ is_valid, _message = validate_credentials(+ api_token="tok", subdomain="accuhive", region="us", schema_name=schema_name+ )++ assert is_valid is expected_ok++ def test_validate_credentials_rejects_bad_base_url_before_request(self) -> None:+ is_valid, message = validate_credentials(api_token="tok", subdomain="", region="us")+ assert is_valid is False+ assert message is not None++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji.make_tracked_session")+ def test_validate_credentials_probes_devices_with_bearer(self, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=200)++ validate_credentials(api_token="tok", subdomain="accuhive", region="us")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://accuhive.api.kandji.io/api/v1/devices"+ assert call.kwargs["headers"]["Authorization"] == "Bearer tok"+ assert call.kwargs["params"] == {"limit": 1}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji.make_tracked_session")+ def test_validate_credentials_handles_request_exception(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = requests.exceptions.RequestException("boom")+ is_valid, message = validate_credentials(api_token="tok", subdomain="accuhive", region="us")+ assert is_valid is False+ assert message is not None and "boom" in message++ def test_get_resource_devices_bare_array_offset_paginated(self) -> None:+ resource = cast(dict[str, Any], get_resource(KANDJI_ENDPOINTS["devices"]))+ assert resource["name"] == "devices"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/devices"+ # List Devices returns a bare array, paginated by limit/offset.+ assert resource["endpoint"]["data_selector"] == "$"+ assert isinstance(resource["endpoint"]["paginator"], OffsetPaginator)++ def test_get_resource_blueprints_wrapped_results(self) -> None:+ resource = cast(dict[str, Any], get_resource(KANDJI_ENDPOINTS["blueprints"]))+ assert resource["endpoint"]["data_selector"] == "results"+ paginator = resource["endpoint"]["paginator"]+ assert isinstance(paginator, OffsetPaginator)+ assert paginator.total_path == "count"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.kandji.kandji.rest_api_resource")+ def test_kandji_source_devices_top_level(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = kandji_source(+ api_token="tok",+ subdomain="accuhive",+ region="us",+ endpoint="devices",+ team_id=1,+ job_id="job-1",+ )++ assert response.name == "devices"+ assert response.primary_keys == ["device_id"]+ assert response.sort_mode == "asc"++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_kandji_source_device_apps_fanout_injects_parent_id(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("devices", [{"device_id": "dev_1"}]),+ _FakeDltResource("device_apps", [{"bundle_id": "com.apple.Safari", "_devices_device_id": "dev_1"}]),+ ]++ response = kandji_source(+ api_token="tok",+ subdomain="accuhive",+ region="us",+ endpoint="device_apps",+ team_id=1,+ job_id="job-1",+ )++ rows = list(cast(Any, response.items()))+ # The parent device id is injected onto each child row and renamed to device_id.+ assert rows == [{"bundle_id": "com.apple.Safari", "device_id": "dev_1"}]+ # 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"]++ @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:+ mock_build_dependent_resource.return_value = iter([])++ kandji_source(+ api_token="tok",+ subdomain="accuhive",+ region="us",+ endpoint="device_library_items",+ team_id=1,+ job_id="job-1",+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ # Kandji is full-refresh only — the fan-out must not request incremental merge behavior.+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["child_endpoint_extra"]["data_selector"] == "library_items"+ assert 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)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji_source.pynew file mode 100644index 000000000000..6595fb92afe1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kandji/tests/test_kandji_source.py@@ -0,0 +1,132 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KandjiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.kandji.source import KandjiSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestKandjiSource:+ def setup_method(self) -> None:+ self.source = KandjiSource()+ self.team_id = 123+ self.config = KandjiSourceConfig(api_token="tok", subdomain="accuhive", region="us")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.KANDJI++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Kandji"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/kandji"++ def test_source_is_released_not_hidden(self) -> None:+ # A finished source must be visible: `unreleasedSource` hides it from every user.+ assert not self.source.get_source_config.unreleasedSource++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ input_fields = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ select_fields = [f.name for f in config.fields if isinstance(f, SourceFieldSelectConfig)]+ assert input_fields == ["api_token", "subdomain"]+ assert select_fields == ["region"]++ def test_api_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_region_options(self) -> None:+ config = self.source.get_source_config+ region = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")+ assert {o.value for o in region.options} == {"us", "eu"}+ assert region.defaultValue == "us"++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_all_full_refresh(self) -> None:+ # Kandji exposes no server-side updated-since cursor, so no stream is incremental.+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["devices"])+ assert [s.name for s in schemas] == ["devices"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — powers the public docs table list.+ assert self.source.lists_tables_without_credentials is True++ def test_connection_host_fields_cover_token_destination(self) -> None:+ # Dropping either field would let an editor retarget the stored bearer token at a host+ # they control without re-entering it (the update serializer keys off this list).+ assert self.source.connection_host_fields == ["subdomain", "region"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://accuhive.api.kandji.io/api/v1/devices",+ "403 Client Error: Forbidden for url: https://accuhive.api.kandji.io/api/v1/devices",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(+ key in "503 Server Error for url: https://accuhive.api.kandji.io/api/v1/devices" for key in non_retryable+ )++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.kandji.source.validate_kandji_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="devices")++ assert result == (True, None)+ kwargs = mock_validate.call_args.kwargs+ assert kwargs["api_token"] == "tok"+ assert kwargs["subdomain"] == "accuhive"+ assert kwargs["region"] == "us"+ assert kwargs["schema_name"] == "devices"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.kandji.source.kandji_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_kandji_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "device_apps"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"++ self.source.source_for_pipeline(self.config, inputs)++ kwargs = mock_kandji_source.call_args.kwargs+ assert kwargs["api_token"] == "tok"+ assert kwargs["subdomain"] == "accuhive"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "device_apps"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"