: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
import re
from collections.abc import Iterable
from typing import Any, Optional, cast
from urllib.parse import parse_qsl, urlsplit
from requests import Request, Response
from requests.exceptions import RequestException
from products.warehouse_sources.sources.kandji.settings import (
EU_API_HOST_TEMPLATE,
KANDJI_ENDPOINTS,
US_API_HOST_TEMPLATE,
KandjiEndpointConfig,
)
from products.warehouse_sources.sources.sdk import (
BasePaginator,
ClientConfig,
Endpoint,
EndpointResource,
OffsetPaginator,
RESTAPIConfig,
ResumableSourceManager,
SinglePagePaginator,
SourceResponse,
build_dependent_resource,
frozen,
make_tracked_session,
rest_api_resource,
)
@frozen
class KandjiResumeConfig:
# What the framework handed the resume hook: the next offset or `next` query of a list endpoint,
# or the device listing position and finished devices of a fan-out. Stored unchanged.
paginator_state: dict[str, Any] | None = None
# The last page of a list endpoint is handed on, so a resume reads nothing again.
completed: bool = False
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"},
}
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 init_request(self, request: Request) -> None:
# Apply a resumed `next` query to the first request.
self.update_request(request)
def update_request(self, request: Request) -> None:
if self._next_params is not None:
request.params = {**(request.params or {}), **self._next_params}
def get_resume_state(self) -> Optional[dict[str, Any]]:
return {"next_params": self._next_params} if self._has_next_page and self._next_params else None
def set_resume_state(self, state: dict[str, Any]) -> None:
next_params = state.get("next_params")
if isinstance(next_params, dict) and next_params:
self._next_params = {str(key): str(value) for key, value in next_params.items()}
self._has_next_page = True
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",
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": dict(config.params),
"data_selector": config.data_selector,
"paginator": _list_paginator(config),
}
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, manager: ResumableSourceManager[KandjiResumeConfig]
) -> SourceResponse:
return SourceResponse(
name=config.name,
on_complete=manager.clear_state,
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,
resumable_source_manager: ResumableSourceManager[KandjiResumeConfig],
) -> SourceResponse:
config = KANDJI_ENDPOINTS[endpoint]
base_url = build_base_url(subdomain, region)
client_config = _rest_api_client_config(base_url, api_token)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
initial_paginator_state = resume.paginator_state if resume is not None else None
def save_checkpoint(state: dict[str, Any] | None) -> None:
if state:
resumable_source_manager.save_state(KandjiResumeConfig(paginator_state=state))
elif state is None:
resumable_source_manager.save_state(KandjiResumeConfig(completed=True))
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": _list_paginator(config),
"data_selector": config.data_selector,
},
resume_hook=save_checkpoint,
initial_paginator_state=initial_paginator_state,
resume_parent_pagination=True,
),
)
return _make_source_response(config, lambda: dependent_resource, resumable_source_manager)
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,
resume_hook=save_checkpoint,
initial_paginator_state=initial_paginator_state,
)
completed = resume is not None and resume.completed
return _make_source_response(config, lambda: [] if completed else resource, resumable_source_manager)