Skip to content

: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.

feat(data-warehouse): implement automox import source (#71234)

Tom Owers21931606c688
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 5cf949da338d..4a5cfb359d00 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -71,6 +71,7 @@ the row lists both.
| assemblyai | HTTP | requests | ✅ |
| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| automox | HTTP | requests | ✅ |
| aviationstack | HTTP | requests | ✅ |
| aviator | HTTP | requests | ✅ |
| awin | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/automox.py b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/automox.py
new file mode 100644
index 000000000000..6b2c61b385e5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/automox.py
@@ -0,0 +1,334 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+import structlog
+from dateutil import parser as dateutil_parser
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.settings import (
+ AUTOMOX_ENDPOINTS,
+ AutomoxEndpointConfig,
+)
+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.resumable import ResumableSourceManager
+
+AUTOMOX_BASE_URL = "https://console.automox.com/api"
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Credential-bearing field names stripped from every row before it lands in the warehouse, at any
+# depth. `access_key` is the org agent-enrollment secret (embedded on organization records and again
+# under each user's `orgs[]` entry) — a teammate with warehouse query access could otherwise read it
+# and enroll an attacker-controlled device. `intercom_hmac` is an Intercom identity-verification
+# token on user records; paired with the user's ID and email it lets someone impersonate that user
+# to Intercom.
+CREDENTIAL_FIELD_NAMES = frozenset({"access_key", "intercom_hmac"})
+
+# Stable prefixes for the auth-failure messages matched by `get_non_retryable_errors` — retrying
+# can never fix a bad key or a misconfigured organization, so syncs stop instead of looping.
+ORG_NOT_FOUND_ERROR = "Automox organization not found"
+MULTIPLE_ORGS_ERROR = "Automox API key has access to multiple organizations"
+
+
+class AutomoxRetryableError(Exception):
+ pass
+
+
+class AutomoxOrganizationError(Exception):
+ pass
+
+
+class AutomoxResumeConfig:
+ # Zero-indexed page of the next request. Automox paginates with page/limit, so persisting the
+ # page number lets a sync pick back up after a heartbeat timeout.
+ page: int = 0
+ # The server-side time filter value the interrupted run was using. Reused verbatim on resume:
+ # recomputing it from the (possibly advanced) watermark would change the filtered result set
+ # and make the saved page number point at different rows.
+ incremental_param_value: str | None = None
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # `redact_values` masks the bearer token in logged URLs and captured HTTP samples so a failed
+ # or sampled request can never persist the raw Automox credential in PostHog's HTTP telemetry.
+ # `capture=False` keeps requests metered and logged but excludes their bodies from HTTP sample
+ # capture: `/orgs` and `/users` responses embed org `access_key` enrollment secrets that the
+ # name-based sample scrubbers don't recognise, and capture happens before row sanitization.
+ return make_tracked_session(
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ redact_values=(api_key,),
+ capture=False,
+ )
+
+
+def _strip_credentials(value: Any) -> Any:
+ """Recursively drop credential-bearing keys (see ``CREDENTIAL_FIELD_NAMES``) from a row."""
+ if isinstance(value, dict):
+ return {k: _strip_credentials(v) for k, v in value.items() if k not in CREDENTIAL_FIELD_NAMES}
+ if isinstance(value, list):
+ return [_strip_credentials(item) for item in value]
+ return value
+
+
+def _scope_row_to_org(row: dict[str, Any], org_id: int | None, field_map: dict[str, str]) -> dict[str, Any]:
+ """Drop nested list entries tagged to organizations other than the resolved one.
+
+ The `o` query param scopes which users are *listed*, but each user row still carries its full
+ org memberships and org-tagged roles — metadata for organizations the source owner never
+ selected. `field_map` maps a nested list field to the key on each entry carrying the org id.
+ """
+ if org_id is None or not field_map:
+ return row
+ scoped = dict(row)
+ for field_name, org_key in field_map.items():
+ value = scoped.get(field_name)
+ if isinstance(value, list):
+ scoped[field_name] = [
+ item for item in value if isinstance(item, dict) and str(item.get(org_key)) == str(org_id)
+ ]
+ return scoped
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ query = {key: value for key, value in params.items() if value is not None and value != ""}
+ return f"{AUTOMOX_BASE_URL}{path}?{urlencode(query)}"
+
+
+@retry(
+ retry=retry_if_exception_type((AutomoxRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_json(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AutomoxRetryableError(f"Automox API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Don't log the response body: it can echo back request details we'd rather not persist.
+ logger.error(f"Automox API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _fetch_page(
+ session: requests.Session, config: AutomoxEndpointConfig, url: str, logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ payload = _fetch_json(session, url, logger)
+
+ if config.data_selector is not None:
+ if not isinstance(payload, dict):
+ raise ValueError(f"Automox API returned a non-object response: url={url}")
+ payload = payload.get(config.data_selector) or []
+
+ # A non-list 200 is a permanent API-contract violation (wrapped payload, proxy HTML, …), not a
+ # transient failure — raise a plain ValueError so it surfaces immediately instead of burning
+ # the retry budget on something retries can't fix.
+ if not isinstance(payload, list):
+ raise ValueError(f"Automox API returned a non-list response: url={url}")
+
+ return payload
+
+
+def list_organizations(session: requests.Session, logger: FilteringBoundLogger) -> list[dict[str, Any]]:
+ # A single max-size page is plenty: an account with >500 zones is not a realistic case, and
+ # `/orgs` is only used to resolve the org the user configured (or the key's only org).
+ url = _build_url("/orgs", {"limit": 500, "page": 0})
+ payload = _fetch_json(session, url, logger)
+ if not isinstance(payload, list):
+ raise ValueError("Automox API returned a non-list response for /orgs")
+ return payload
+
+
+def resolve_organization(
+ session: requests.Session, organization_id: str | None, logger: FilteringBoundLogger
+) -> tuple[int, str | None]:
+ """Resolve the numeric organization ID and UUID the sync should run against.
+
+ Automox global API keys can access several organizations, and two endpoint families need the
+ org identifier in different shapes: most Console API endpoints take the numeric ID (`o=`),
+ while Policy History takes the UUID (`org=`). Both come from one `/orgs` call.
+ """
+ organizations = list_organizations(session, logger)
+
+ normalized = (organization_id or "").strip()
+ if normalized:
+ for org in organizations:
+ if str(org.get("id")) == normalized:
+ return org["id"], org.get("uuid")
+ raise AutomoxOrganizationError(
+ f"{ORG_NOT_FOUND_ERROR}: no organization with ID {normalized} is accessible with this API key"
+ )
+
+ if len(organizations) == 1:
+ only = organizations[0]
+ return only["id"], only.get("uuid")
+
+ raise AutomoxOrganizationError(
+ f"{MULTIPLE_ORGS_ERROR}: set the organization ID on the source to pick which one to sync"
+ )
+
+
+def validate_credentials(api_key: str, organization_id: str | None = None) -> tuple[bool, str | None]:
+ logger = structlog.get_logger(__name__)
+ session = _make_session(api_key)
+ try:
+ resolve_organization(session, organization_id, logger)
+ except AutomoxOrganizationError as e:
+ return False, str(e)
+ except Exception:
+ return False, "Automox authentication failed. Check that your API key is valid and not expired."
+ return True, None
+
+
+def _coerce_datetime(value: Any) -> datetime | None:
+ """Coerce a persisted incremental watermark (datetime, date, ISO string, or epoch) to UTC."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, int | float):
+ return datetime.fromtimestamp(value, tz=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = dateutil_parser.parse(value)
+ except (ValueError, OverflowError):
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ return None
+
+
+def _incremental_param_value(config: AutomoxEndpointConfig, last_value: Any) -> str | None:
+ """Format the persisted watermark as the endpoint's server-side time filter value."""
+ dt = _coerce_datetime(last_value)
+ if dt is None:
+ return None
+
+ # Cap a future-dated cursor at now so bad upstream data can't wedge the filter.
+ now = datetime.now(UTC)
+ if dt > now:
+ dt = now
+
+ if config.incremental_lookback is not None:
+ dt = dt - config.incremental_lookback
+
+ if config.incremental_param_is_date:
+ return dt.astimezone(UTC).date().isoformat()
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def get_rows(
+ api_key: str,
+ organization_id: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AutomoxResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = AUTOMOX_ENDPOINTS[endpoint]
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = _make_session(api_key)
+
+ org_id: int | None = None
+ org_uuid: str | None = None
+ if config.needs_org_id_param or config.org_uuid_param or config.restrict_to_org or "{org_id}" in config.path:
+ org_id, org_uuid = resolve_organization(session, organization_id, logger)
+ if config.org_uuid_param and not org_uuid:
+ raise AutomoxOrganizationError(
+ f"{ORG_NOT_FOUND_ERROR}: the organization has no UUID, which the {endpoint} endpoint requires"
+ )
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume else 0
+
+ incremental_value: str | None = None
+ if config.incremental_param and should_use_incremental_field:
+ if resume:
+ incremental_value = resume.incremental_param_value
+ else:
+ incremental_value = _incremental_param_value(config, db_incremental_field_last_value)
+ if resume:
+ logger.debug(f"Automox: resuming {endpoint} from page={page}")
+
+ path = config.path.replace("{org_id}", str(org_id)) if org_id is not None else config.path
+
+ while True:
+ params: dict[str, Any] = {
+ "page": page,
+ "limit": config.page_size,
+ **config.extra_params,
+ }
+ if config.needs_org_id_param and org_id is not None:
+ params["o"] = org_id
+ if config.org_uuid_param and org_uuid is not None:
+ params[config.org_uuid_param] = org_uuid
+ if config.incremental_param and incremental_value is not None:
+ params[config.incremental_param] = incremental_value
+
+ rows = _fetch_page(session, config, _build_url(path, params), logger)
+ if not rows:
+ break
+
+ # Terminate on the raw page length: filtering below can shrink the page without meaning
+ # the resource is exhausted.
+ reached_end = len(rows) < config.page_size
+
+ if config.restrict_to_org:
+ rows = [row for row in rows if org_id is not None and str(row.get("id")) == str(org_id)]
+
+ rows = [_strip_credentials(row) for row in rows]
+ if config.org_scoped_list_fields:
+ rows = [_scope_row_to_org(row, org_id, config.org_scoped_list_fields) for row in rows]
+ if rows:
+ yield rows
+
+ # A short page means we've reached the end of the resource.
+ if reached_end:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-runs from the last persisted page rather than skipping
+ # ahead; the merge dedupes any re-pulled rows on the primary key.
+ resumable_source_manager.save_state(AutomoxResumeConfig(page=page, incremental_param_value=incremental_value))
+
+
+def automox_source(
+ api_key: str,
+ organization_id: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AutomoxResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = AUTOMOX_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ organization_id=organization_id,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode=config.sort_mode,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/canonical_descriptions.py
new file mode 100644
index 000000000000..6635efddc47d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/canonical_descriptions.py
@@ -0,0 +1,176 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the official Automox Console API reference (https://console.automox.com/api/docs).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "devices": {
+ "description": "A device (server, workstation, or endpoint) managed by the Automox agent, with OS details, connection state, and patch/compliance status.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Unique identifier for the device.",
+ "uuid": "UUID of the device.",
+ "name": "Hostname of the device.",
+ "custom_name": "Custom display name assigned to the device in the console.",
+ "display_name": "Name shown for the device in the Automox console.",
+ "organization_id": "ID of the organization that owns this device.",
+ "server_group_id": "ID of the server group this device belongs to.",
+ "os_family": "Operating system family (e.g. Windows, Mac, Linux).",
+ "os_name": "Name of the device's operating system.",
+ "os_version": "Version of the device's operating system.",
+ "agent_version": "Version of the Automox agent installed on the device.",
+ "connected": "Whether the device is currently connected to Automox.",
+ "compliant": "Whether the device is compliant with its assigned policies.",
+ "pending_patches": "Number of patches pending on the device.",
+ "needs_reboot": "Whether the device needs a reboot to finish applying patches.",
+ "needs_attention": "Whether the device is flagged as needing attention.",
+ "exception": "Whether the device is excluded from reports and statistics.",
+ "last_logged_in_user": "The user most recently logged in to the device.",
+ "last_refresh_time": "Date and time when the device last refreshed.",
+ "last_update_time": "Date and time when the device record was last updated.",
+ "last_disconnect_time": "Date and time when the device last disconnected.",
+ "create_time": "Date and time when the device was added to Automox.",
+ "ip_addrs": "Public IP addresses of the device.",
+ "ip_addrs_private": "Private IP addresses of the device.",
+ "serial_number": "Hardware serial number of the device.",
+ "tags": "Tags assigned to the device.",
+ },
+ },
+ "events": {
+ "description": "An entry from the Automox console activity log, such as patches applied or failed, devices added or deleted, and policy actions.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Unique identifier for the event.",
+ "name": "Event type (e.g. system.patch.applied, system.add, system.policy.action).",
+ "user_id": "ID of the user associated with the event.",
+ "server_id": "ID of the device associated with the event.",
+ "server_name": "Name of the device associated with the event.",
+ "organization_id": "ID of the organization the event belongs to.",
+ "policy_id": "Policy ID associated with the event.",
+ "policy_name": "Name of the policy associated with the event.",
+ "policy_type_name": "Type of the policy associated with the event.",
+ "data": "Event-specific payload with additional details.",
+ "create_time": "Date and time when the event occurred.",
+ },
+ },
+ "organizations": {
+ "description": "An Automox organization (zone) the API key can access, with device counts and limits.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Organization ID.",
+ "uuid": "Organization UUID.",
+ "name": "Organization name.",
+ "create_time": "Date and time when the organization was created.",
+ "device_count": "The current number of installed devices for the organization.",
+ "device_limit": "Device limit for the organization, if one is set.",
+ "parent_id": "ID of the parent organization.",
+ "tier": "Service tier level for the organization.",
+ "trial_end_time": "Date and time when the trial period ends.",
+ },
+ },
+ "packages": {
+ "description": "A software package on a managed device, including installation state, patch severity, and associated CVEs. One row per package per device.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Unique identifier for the package record.",
+ "server_id": "ID of the device where this package is installed or available.",
+ "package_id": "ID of the package definition.",
+ "package_version_id": "ID of the package version.",
+ "software_id": "ID of the associated software.",
+ "name": "Name of the package.",
+ "display_name": "Display name of the package.",
+ "version": "Version of the package.",
+ "installed": "Whether the package is installed.",
+ "ignored": "Whether the package is ignored.",
+ "deferred_until": "Date until which the package installation is deferred.",
+ "severity": "Security severity level of the package.",
+ "agent_severity": "Security severity as determined by the agent (text severity or CVSS numeric score).",
+ "cves": "List of CVE identifiers associated with this package.",
+ "cve_score": "CVE score for the package.",
+ "impact": "Impact level of the package.",
+ "requires_reboot": "Whether the package requires a system reboot after installation.",
+ "is_managed": "Whether the package is managed by Automox.",
+ "os_name": "Name of the device's operating system.",
+ "os_version": "Version of the device's operating system.",
+ "organization_id": "ID of the organization that owns this package record.",
+ "create_time": "Date and time when the package record was created.",
+ },
+ },
+ "policies": {
+ "description": "An Automox policy (patch, required software, or custom worklet) with its schedule and configuration.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Policy ID.",
+ "uuid": "Policy UUID.",
+ "name": "Name of the policy.",
+ "organization_id": "Organization ID for the policy.",
+ "policy_type_name": "Type of the policy (patch, custom, required_software).",
+ "configuration": "Configuration settings for the policy.",
+ "status": "Status of the policy (active or inactive).",
+ "notes": "Any notes associated with the policy.",
+ "create_time": "The date and time that the policy was created.",
+ "next_remediation": "The date and time that the policy is scheduled to execute next, or null if not scheduled.",
+ "server_count": "The number of devices that the policy will execute on.",
+ "server_groups": "The server groups that the policy is associated with.",
+ "schedule_days": "Decimal value of the binary day schedule.",
+ "schedule_weeks_of_month": "Decimal value of the binary week schedule.",
+ "schedule_months": "Decimal value of the binary month schedule.",
+ "schedule_time": "Scheduled wall-clock time for automatic policy execution (hh:mm).",
+ },
+ },
+ "policy_runs": {
+ "description": "A policy execution from the Automox Policy History API, with per-status device counts for the run.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "policy_uuid": "UUID of the policy that ran.",
+ "policy_id": "ID of the policy that ran.",
+ "policy_name": "Name of the policy that ran.",
+ "policy_type": "Type of the policy (custom, patch, required_software).",
+ "policy_deleted_at": "Date and time the policy was deleted, if it no longer exists.",
+ "org_uuid": "UUID of the organization the run belongs to.",
+ "execution_token": "Token identifying this policy execution.",
+ "run_time": "Date and time when the policy ran.",
+ "run_count": "Number of runs aggregated in this row.",
+ "device_count": "Number of devices the run targeted.",
+ "success": "Number of devices where the run succeeded.",
+ "failed": "Number of devices where the run failed.",
+ "pending": "Number of devices where the run is still pending.",
+ "not_included": "Number of devices not included in the run.",
+ "remediation_not_applicable": "Number of devices where remediation was not applicable.",
+ },
+ },
+ "server_groups": {
+ "description": "A server group used to organize devices and target policies.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Unique identifier for the server group.",
+ "name": "Name of the server group.",
+ "organization_id": "ID of the organization that owns this group.",
+ "parent_server_group_id": "ID of the parent server group.",
+ "refresh_interval": "Refresh interval for devices in the group, in minutes.",
+ "server_count": "Number of devices in the group.",
+ "policies": "IDs of the policies associated with the group.",
+ "notes": "Any notes associated with the group.",
+ "ui_color": "Display color of the group in the Automox console.",
+ "enable_os_auto_update": "Whether OS auto-update is enabled for the group.",
+ "wsus_config": "WSUS configuration settings for managing device patches.",
+ },
+ },
+ "users": {
+ "description": "A user with access to the Automox organization.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "firstname": "User's first name.",
+ "lastname": "User's last name.",
+ "email": "User's email address.",
+ "orgs": "Organizations the user has access to.",
+ "rbac_roles": "Role-based access control roles assigned to the user.",
+ "server_groups": "Server groups the user has access to.",
+ "tags": "Tags assigned to the user.",
+ "saml_enabled": "Whether SAML single sign-on is enabled for the user.",
+ "sso_enabled": "Whether single sign-on is enabled for the user.",
+ "tfa_type": "Type of two-factor authentication configured for the user.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/docs/automox.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/docs/automox.mdx
new file mode 100644
index 000000000000..743ff60f108a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/docs/automox.mdx
@@ -0,0 +1,62 @@
+---
+title: Linking Automox as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Automox
+---
+
+<!--
+This is the user-facing posthog.com source doc. It lives here only because no posthog.com
+checkout was available when the source was implemented. Move it to
+`posthog.com/contents/docs/cdp/sources/automox.mdx` and delete this copy, then run
+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.
+-->
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+import AlphaRelease from '../_snippets/alpha-release.mdx'
+
+<AlphaRelease />
+
+[Automox](https://www.automox.com) is a cloud-native patch management and endpoint management platform. Linking it as a source syncs your device inventory, policies, patch history, and software packages into the PostHog Data warehouse, so you can trend remediation coverage and device compliance across your fleet alongside your product data.
+
+## Prerequisites
+
+To connect Automox, you need:
+
+- An Automox account with access to **Settings → API Keys** in the Automox console.
+- An API key created there (used as a bearer token). API keys are user-scoped, so requests are attributed to the user who created the key.
+- If your API key has access to more than one organization (zone), the numeric organization ID to sync, visible under **Settings → Organization**.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+1. Open the Automox console and go to **Settings → API Keys**.
+2. Create a new API key and copy it.
+3. Paste the key into the **API key** field in PostHog.
+4. If your key can access more than one organization, also enter the **Organization ID** the source should sync. Leave it blank when the key only belongs to one organization.
+
+## Sync modes
+
+<SyncModes />
+
+The `policy_runs` table (policy execution history) and the `events` table (console activity log) support **incremental** sync using Automox's server-side time filters, so they only fetch new rows on each run. The core inventory tables (devices, policies, packages, server groups, users, organizations) have no server-side "updated since" filter and sync as a **full refresh** — each sync re-reads the resource and merges on the primary key.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **"Automox authentication failed"** when connecting: the API key is wrong or has expired. Create a new key under **Settings → API Keys** in the Automox console and re-enter it.
+- **"Automox API key has access to multiple organizations"**: the key can access several organizations, so PostHog can't pick one for you. Enter the numeric organization ID on the source.
+- **"Automox organization not found"**: the configured organization ID doesn't match any organization the key can access. Check the ID under **Settings → Organization** in the Automox console.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/settings.py
new file mode 100644
index 000000000000..b11f92068ef5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/settings.py
@@ -0,0 +1,137 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class AutomoxEndpointConfig:
+ # Console API path, relative to https://console.automox.com/api. May contain an
+ # `{org_id}` placeholder resolved at sync time.
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-style timestamp used for datetime partitioning (never a field that churns).
+ partition_key: str | None = None
+ # Key the row list is nested under when the response is wrapped (e.g. policy_runs `data`).
+ # None means the endpoint returns a bare JSON array.
+ data_selector: str | None = None
+ # Automox caps `limit` at 500 for Console API list endpoints (policy_runs allows more, but
+ # 500 keeps response sizes bounded).
+ page_size: int = 500
+ # Pass the resolved numeric organization ID as the `o` query param. Most Console API list
+ # endpoints take it; without it the API falls back to the key's default organization.
+ needs_org_id_param: bool = False
+ # Name of the query param carrying the organization UUID (Policy History endpoints use
+ # `org=<uuid>` instead of `o=<numeric id>`).
+ org_uuid_param: str | None = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Server-side time filter query param backing incremental sync. None means the endpoint has
+ # no server-side filter and syncs as full refresh only.
+ incremental_param: str | None = None
+ # `True` when the filter param only accepts a date (YYYY-MM-DD) rather than a full timestamp.
+ incremental_param_is_date: bool = False
+ # Safety overlap subtracted from the incremental watermark on every run; re-pulled rows are
+ # deduped on the primary key by the merge.
+ incremental_lookback: timedelta | None = None
+ # Extra query params sent on every request (e.g. an explicit sort).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ sort_mode: SortMode = "asc"
+ # When True, keep only the single configured organization's row. `/orgs` lists every
+ # organization the API key can access, so without this the table would expose metadata for
+ # organizations the source owner never selected.
+ restrict_to_org: bool = False
+ # Nested list fields to trim to the resolved organization, mapping the field name to the key on
+ # each entry carrying the org id. The `o` param scopes which rows are listed, but per-row
+ # membership metadata (a user's `orgs[]`, their org-tagged `rbac_roles[]`) still carries other
+ # organizations the source owner never selected.
+ org_scoped_list_fields: dict[str, str] = field(default_factory=dict)
+
+
+AUTOMOX_ENDPOINTS: dict[str, AutomoxEndpointConfig] = {
+ # Core device inventory. No server-side updated-since filter exists, so full refresh only.
+ "devices": AutomoxEndpointConfig(
+ path="/servers",
+ partition_key="create_time",
+ needs_org_id_param=True,
+ ),
+ # Console activity log. `startDate` is a server-side date filter, so incremental sync on
+ # `create_time` genuinely reduces the pages fetched. The API does not document the sort
+ # order of results, so `sort_mode="desc"` makes the pipeline persist the watermark only
+ # when a sync completes instead of checkpointing per batch on an unverified ordering.
+ "events": AutomoxEndpointConfig(
+ path="/events",
+ partition_key="create_time",
+ needs_org_id_param=True,
+ incremental_fields=[_datetime_incremental_field("create_time")],
+ incremental_param="startDate",
+ incremental_param_is_date=True,
+ # `startDate` has date granularity and the docs don't say whether the boundary day is
+ # included, so re-pull an extra day and let the merge dedupe on `id`.
+ incremental_lookback=timedelta(days=1),
+ sort_mode="desc",
+ ),
+ # Organizations the API key can access. Tiny table, full refresh. `/orgs` returns every
+ # accessible organization, so restrict the table to the one this source is configured for.
+ "organizations": AutomoxEndpointConfig(
+ path="/orgs",
+ partition_key="create_time",
+ restrict_to_org=True,
+ ),
+ # All software packages across all devices in the organization, including patch status and
+ # severity. The docs don't state whether the package record `id` is unique beyond its device,
+ # so include `server_id` in the key to be safe.
+ "packages": AutomoxEndpointConfig(
+ path="/orgs/{org_id}/packages",
+ primary_keys=["id", "server_id"],
+ partition_key="create_time",
+ ),
+ "policies": AutomoxEndpointConfig(
+ path="/policies",
+ partition_key="create_time",
+ needs_org_id_param=True,
+ ),
+ # Policy History API v2: one row per policy execution with per-status device counts.
+ # `start_time` is a server-side timestamp filter and the endpoint accepts an explicit
+ # ascending sort, so incremental sync is fully supported.
+ "policy_runs": AutomoxEndpointConfig(
+ path="/policy-history/policy-runs",
+ primary_keys=["policy_uuid", "execution_token"],
+ partition_key="run_time",
+ data_selector="data",
+ org_uuid_param="org",
+ incremental_fields=[_datetime_incremental_field("run_time")],
+ incremental_param="start_time",
+ # A run's per-device result counts keep updating while devices report back, so re-pull a
+ # day of runs each sync; the merge dedupes on the primary key.
+ incremental_lookback=timedelta(hours=24),
+ extra_params={"sort": "run_time:asc"},
+ sort_mode="asc",
+ ),
+ "server_groups": AutomoxEndpointConfig(
+ path="/servergroups",
+ needs_org_id_param=True,
+ ),
+ "users": AutomoxEndpointConfig(
+ path="/users",
+ needs_org_id_param=True,
+ # User records embed the user's full org memberships and org-tagged roles regardless of the
+ # `o` scope, so trim both to the organization this source syncs.
+ org_scoped_list_fields={"orgs": "id", "rbac_roles": "organization_id"},
+ ),
+}
+
+ENDPOINTS = tuple(AUTOMOX_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in AUTOMOX_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/source.py
index 78e78b345423..ad93f58cd128 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/source.py
@@ -1,30 +1,155 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.automox import (
+ MULTIPLE_ORGS_ERROR,
+ ORG_NOT_FOUND_ERROR,
+ AutomoxResumeConfig,
+ automox_source,
+ validate_credentials as validate_automox_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.settings import (
+ AUTOMOX_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AutomoxSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AutomoxSource(SimpleSource[AutomoxSourceConfig]):
+class AutomoxSource(ResumableSource[AutomoxSourceConfig, AutomoxResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AUTOMOX
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored API key syncs whichever `organization_id` is configured, so changing it
+ # retargets the saved credential at a different organization — force secret re-entry.
+ return ["organization_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.AUTOMOX,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Automox",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Automox API key to sync your patch management and device compliance data into the PostHog Data warehouse.
+
+Create an API key in the Automox console under **Settings → API Keys**, then paste it here.
+
+If your API key has access to more than one organization, also enter the numeric organization ID (visible in **Settings → Organization**) the source should sync.""",
iconPath="/static/services/automox.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/automox",
+ keywords=["patch management", "endpoint management", "device compliance"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="organization_id",
+ label="Organization ID (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.automox.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or expired API key surfaces as a requests HTTPError when `_fetch_json`
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop
+ # the sync. Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://console.automox.com": "Your Automox API key is invalid or has expired. Create a new key under Settings → API Keys in the Automox console, then reconnect.",
+ "403 Client Error: Forbidden for url: https://console.automox.com": "Your Automox API key does not have permission to read this data. Check the key's permissions, then reconnect.",
+ ORG_NOT_FOUND_ERROR: "The configured organization ID is not accessible with this API key. Check the organization ID on the source, then try again.",
+ MULTIPLE_ORGS_ERROR: "Your Automox API key has access to multiple organizations. Set the organization ID on the source to pick which one to sync.",
+ }
+
+ def get_schemas(
+ self,
+ config: AutomoxSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(AUTOMOX_ENDPOINTS[endpoint].incremental_fields) > 0,
+ supports_append=len(AUTOMOX_ENDPOINTS[endpoint].incremental_fields) > 0,
+ incremental_fields=AUTOMOX_ENDPOINTS[endpoint].incremental_fields,
+ detected_primary_keys=AUTOMOX_ENDPOINTS[endpoint].primary_keys,
+ )
+ 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: AutomoxSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_automox_credentials(config.api_key, config.organization_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AutomoxResumeConfig]:
+ return ResumableSourceManager[AutomoxResumeConfig](inputs, AutomoxResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AutomoxSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AutomoxResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return automox_source(
+ api_key=config.api_key,
+ organization_id=config.organization_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox.py b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox.py
new file mode 100644
index 000000000000..9934123c061a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox.py
@@ -0,0 +1,452 @@
+import json
+from datetime import UTC, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox import automox
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.automox import (
+ MULTIPLE_ORGS_ERROR,
+ ORG_NOT_FOUND_ERROR,
+ AutomoxOrganizationError,
+ AutomoxResumeConfig,
+ AutomoxRetryableError,
+ _build_url,
+ _incremental_param_value,
+ automox_source,
+ get_rows,
+ resolve_organization,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.settings import (
+ AUTOMOX_ENDPOINTS,
+ ENDPOINTS,
+)
+
+ORGS_BODY = [
+ {"id": 123, "uuid": "uuid-123", "name": "Org A"},
+ {"id": 456, "uuid": "uuid-456", "name": "Org B"},
+]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: AutomoxResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[AutomoxResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> AutomoxResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: AutomoxResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _response_with_status(status_code: int, body: Any = None) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ response._content = b"" if body is None else json.dumps(body).encode()
+ return response
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestBuildUrl:
+ def test_page_zero_is_kept(self) -> None:
+ # page=0 is the first page; it must not be dropped as a falsy value.
+ url = _build_url("/servers", {"page": 0, "limit": 500})
+ assert url == "https://console.automox.com/api/servers?page=0&limit=500"
+
+ def test_omits_none_values(self) -> None:
+ url = _build_url("/servers", {"page": 0, "o": None})
+ assert "o=" not in url
+
+
+class TestFetchJson:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(status)
+ # No-op the backoff sleep so the 5 attempts run instantly.
+ with patch.object(automox._fetch_json.retry, "sleep", lambda *a, **k: None): # type: ignore[attr-defined]
+ with pytest.raises(AutomoxRetryableError):
+ automox._fetch_json(session, "https://console.automox.com/api/servers", MagicMock())
+ assert session.get.call_count == 5
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_http_error(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(status)
+ with pytest.raises(requests.HTTPError):
+ automox._fetch_json(session, "https://console.automox.com/api/servers", MagicMock())
+
+
+class TestFetchPage:
+ def test_unwraps_data_selector(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(200, {"data": [{"policy_id": 1}], "metadata": {}})
+ rows = automox._fetch_page(
+ session, AUTOMOX_ENDPOINTS["policy_runs"], "https://console.automox.com/api/x", MagicMock()
+ )
+ assert rows == [{"policy_id": 1}]
+
+ def test_missing_data_key_returns_empty_list(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(200, {"metadata": {}})
+ rows = automox._fetch_page(
+ session, AUTOMOX_ENDPOINTS["policy_runs"], "https://console.automox.com/api/x", MagicMock()
+ )
+ assert rows == []
+
+ @parameterized.expand(
+ [
+ ("bare_endpoint_object_body", "devices", {"error": "unexpected"}),
+ ("wrapped_endpoint_list_body", "policy_runs", [{"policy_id": 1}]),
+ ]
+ )
+ def test_contract_violations_raise_value_error(self, _name: str, endpoint: str, body: Any) -> None:
+ # A malformed 200 is a permanent contract violation, so it must bypass the retry decorator.
+ session = MagicMock()
+ session.get.return_value = _response_with_status(200, body)
+ with pytest.raises(ValueError):
+ automox._fetch_page(session, AUTOMOX_ENDPOINTS[endpoint], "https://console.automox.com/api/x", MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestIncrementalParamValue:
+ @parameterized.expand(
+ [
+ # policy_runs subtracts the 24h lookback and formats a full RFC3339 timestamp.
+ (
+ "policy_runs_datetime",
+ "policy_runs",
+ datetime(2026, 3, 10, 12, 0, 0, tzinfo=UTC),
+ "2026-03-09T12:00:00Z",
+ ),
+ ("policy_runs_string", "policy_runs", "2026-03-10T12:00:00Z", "2026-03-09T12:00:00Z"),
+ # events subtracts a 1-day lookback and formats a date-only value.
+ ("events_datetime", "events", datetime(2026, 3, 10, 12, 0, 0, tzinfo=UTC), "2026-03-09"),
+ ("events_string", "events", "2026-03-10T12:00:00Z", "2026-03-09"),
+ ]
+ )
+ def test_formats_watermark(self, _name: str, endpoint: str, last_value: Any, expected: str) -> None:
+ assert _incremental_param_value(AUTOMOX_ENDPOINTS[endpoint], last_value) == expected
+
+ @parameterized.expand([("none", None), ("garbage_string", "not-a-date")])
+ def test_unusable_watermark_returns_none(self, _name: str, last_value: Any) -> None:
+ assert _incremental_param_value(AUTOMOX_ENDPOINTS["policy_runs"], last_value) is None
+
+ def test_future_watermark_is_clamped_to_now(self) -> None:
+ # A future-dated cursor must not produce a filter past now, which would skip new rows forever.
+ value = _incremental_param_value(AUTOMOX_ENDPOINTS["policy_runs"], datetime(2099, 1, 1, tzinfo=UTC))
+ assert value is not None
+ assert datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC) <= datetime.now(UTC)
+
+
+class TestResolveOrganization:
+ @parameterized.expand(
+ [
+ ("explicit_id", "456", (456, "uuid-456")),
+ ("explicit_id_with_whitespace", " 123 ", (123, "uuid-123")),
+ ]
+ )
+ def test_explicit_id_is_matched(self, _name: str, organization_id: str, expected: tuple[int, str]) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(200, ORGS_BODY)
+ assert resolve_organization(session, organization_id, MagicMock()) == expected
+
+ def test_single_org_is_used_when_id_not_set(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(200, [ORGS_BODY[0]])
+ assert resolve_organization(session, None, MagicMock()) == (123, "uuid-123")
+
+ @parameterized.expand(
+ [
+ ("unknown_id", "999", ORG_NOT_FOUND_ERROR),
+ ("multiple_orgs_no_id", None, MULTIPLE_ORGS_ERROR),
+ ]
+ )
+ def test_unresolvable_org_raises(self, _name: str, organization_id: str | None, expected_prefix: str) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(200, ORGS_BODY)
+ with pytest.raises(AutomoxOrganizationError, match=expected_prefix):
+ resolve_organization(session, organization_id, MagicMock())
+
+
+class TestMakeSession:
+ def test_disables_sample_capture_and_redacts_key(self) -> None:
+ # `/orgs` and `/users` responses carry org `access_key` secrets the name-based sample
+ # scrubbers don't recognise, so the session must opt out of HTTP sample capture and mask
+ # the bearer token in logged URLs.
+ with patch.object(automox, "make_tracked_session") as mock_session:
+ automox._make_session("secret-key")
+ kwargs = mock_session.call_args.kwargs
+ assert kwargs["capture"] is False
+ assert kwargs["redact_values"] == ("secret-key",)
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response: requests.Response) -> Any:
+ session = MagicMock()
+ session.get.return_value = response
+ return patch.object(automox, "make_tracked_session", return_value=session)
+
+ def test_valid_key_single_org(self) -> None:
+ with self._patch_session(_response_with_status(200, [ORGS_BODY[0]])):
+ assert validate_credentials("key") == (True, None)
+
+ def test_invalid_key_returns_friendly_error(self) -> None:
+ with self._patch_session(_response_with_status(401)):
+ ok, error = validate_credentials("bad-key")
+ assert ok is False
+ assert error is not None
+ assert "API key" in error
+
+ def test_multiple_orgs_without_id_returns_org_error(self) -> None:
+ with self._patch_session(_response_with_status(200, ORGS_BODY)):
+ ok, error = validate_credentials("key")
+ assert ok is False
+ assert error is not None
+ assert MULTIPLE_ORGS_ERROR in error
+
+ def test_unknown_org_id_returns_org_error(self) -> None:
+ with self._patch_session(_response_with_status(200, ORGS_BODY)):
+ ok, error = validate_credentials("key", "999")
+ assert ok is False
+ assert error is not None
+ assert ORG_NOT_FOUND_ERROR in error
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ endpoint: str,
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: list[list[dict]],
+ organization_id: str | None = "123",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ orgs_body: list[dict] | None = None,
+ ) -> tuple[list[dict], list[str]]:
+ """Drive ``get_rows`` with canned page bodies, returning rows and requested URLs."""
+ fetched_urls: list[str] = []
+ config = AUTOMOX_ENDPOINTS[endpoint]
+
+ def fake_fetch_json(session: Any, url: str, logger: Any) -> Any:
+ fetched_urls.append(url)
+ parsed = urlparse(url)
+ query = parse_qs(parsed.query)
+ # Org resolution calls /orgs without our endpoint's page-size marker.
+ if parsed.path.endswith("/orgs") and query.get("limit") == ["500"] and endpoint != "organizations":
+ return orgs_body if orgs_body is not None else ORGS_BODY
+ index = int(query["page"][0])
+ page = pages[index] if index < len(pages) else []
+ return {"data": page, "metadata": {}} if config.data_selector else page
+
+ monkeypatch.setattr(automox, "_fetch_json", fake_fetch_json)
+ monkeypatch.setattr(automox, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for page in get_rows(
+ api_key="key",
+ organization_id=organization_id,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ):
+ rows.extend(page)
+ return rows, fetched_urls
+
+ def test_paginates_until_short_page_and_saves_state_after_yield(self, monkeypatch: Any) -> None:
+ page_size = AUTOMOX_ENDPOINTS["devices"].page_size
+ full_page = [{"id": i} for i in range(page_size)]
+ last_page = [{"id": page_size}]
+ manager = _FakeResumableManager()
+ rows, urls = self._collect("devices", manager, monkeypatch, [full_page, last_page])
+
+ assert len(rows) == page_size + 1
+ # One org-resolution call plus two pages.
+ page_urls = [u for u in urls if "/servers" in u]
+ assert [_query(u)["page"] for u in page_urls] == [["0"], ["1"]]
+ # The `o` org param rides on every page request.
+ assert all(_query(u)["o"] == ["123"] for u in page_urls)
+ # State points at the next page and is only saved after a full (non-terminal) page.
+ assert manager.saved == [AutomoxResumeConfig(page=1, incremental_param_value=None)]
+
+ def test_single_short_page_stops_without_saving_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, _ = self._collect("devices", manager, monkeypatch, [[{"id": 1}]])
+ assert rows == [{"id": 1}]
+ assert manager.saved == []
+
+ def test_resume_seeds_page_and_reuses_stored_incremental_value(self, monkeypatch: Any) -> None:
+ # On resume the original run's time filter must be reused verbatim: recomputing it from the
+ # advanced watermark would change the filtered result set under the saved page number.
+ manager = _FakeResumableManager(AutomoxResumeConfig(page=1, incremental_param_value="2026-01-01T00:00:00Z"))
+ _, urls = self._collect(
+ "policy_runs",
+ manager,
+ monkeypatch,
+ [[{"execution_token": "a"}], [{"execution_token": "b"}]],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 1, tzinfo=UTC),
+ )
+ page_urls = [u for u in urls if "policy-runs" in u]
+ assert [_query(u)["page"] for u in page_urls] == [["1"]]
+ assert all(_query(u)["start_time"] == ["2026-01-01T00:00:00Z"] for u in page_urls)
+
+ def test_policy_runs_sends_org_uuid_sort_and_start_time(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, urls = self._collect(
+ "policy_runs",
+ manager,
+ monkeypatch,
+ [[{"execution_token": "a"}]],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 10, 12, 0, 0, tzinfo=UTC),
+ )
+ run_urls = [u for u in urls if "policy-runs" in u]
+ assert len(run_urls) == 1
+ query = _query(run_urls[0])
+ assert query["org"] == ["uuid-123"]
+ assert query["sort"] == ["run_time:asc"]
+ # 24h lookback applied to the watermark.
+ assert query["start_time"] == ["2026-03-09T12:00:00Z"]
+
+ def test_first_incremental_sync_omits_time_filter(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, urls = self._collect(
+ "policy_runs",
+ manager,
+ monkeypatch,
+ [[{"execution_token": "a"}]],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ run_urls = [u for u in urls if "policy-runs" in u]
+ assert "start_time" not in _query(run_urls[0])
+
+ def test_events_sends_date_only_filter(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, urls = self._collect(
+ "events",
+ manager,
+ monkeypatch,
+ [[{"id": 1}]],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 10, 12, 0, 0, tzinfo=UTC),
+ )
+ event_urls = [u for u in urls if "/events" in u]
+ assert _query(event_urls[0])["startDate"] == ["2026-03-09"]
+
+ def test_packages_formats_org_id_into_path(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, urls = self._collect("packages", manager, monkeypatch, [[{"id": 1, "server_id": 2}]])
+ package_urls = [u for u in urls if "/packages" in u]
+ assert len(package_urls) == 1
+ assert urlparse(package_urls[0]).path == "/api/orgs/123/packages"
+
+ def test_organizations_endpoint_restricts_to_configured_org(self, monkeypatch: Any) -> None:
+ # `/orgs` lists every organization the API key can access, but the table must expose only
+ # the org this source is configured for — otherwise a teammate could read metadata for
+ # organizations the source owner never selected.
+ manager = _FakeResumableManager()
+ org_rows = [
+ {"id": 123, "uuid": "uuid-123", "name": "Org A"},
+ {"id": 456, "uuid": "uuid-456", "name": "Org B"},
+ ]
+ rows, _ = self._collect("organizations", manager, monkeypatch, [org_rows], organization_id="456")
+ assert rows == [{"id": 456, "uuid": "uuid-456", "name": "Org B"}]
+
+ def test_credential_fields_are_stripped_from_rows(self, monkeypatch: Any) -> None:
+ # Automox embeds an org enrollment `access_key` at the top level and again under nested
+ # `orgs[]` entries, plus an `intercom_hmac` identity token on user rows; none may reach the
+ # warehouse, at any depth.
+ manager = _FakeResumableManager()
+ user_row = {
+ "id": 7,
+ "access_key": "org-enrollment-secret",
+ "intercom_hmac": "identity-token",
+ "orgs": [{"id": 123, "access_key": "nested-secret", "name": "Org A"}],
+ }
+ rows, _ = self._collect("users", manager, monkeypatch, [[user_row]])
+ assert rows == [{"id": 7, "orgs": [{"id": 123, "name": "Org A"}]}]
+
+ def test_user_rows_are_scoped_to_configured_org(self, monkeypatch: Any) -> None:
+ # The `o` param scopes which users are listed, but each row still carries the user's full org
+ # memberships and org-tagged roles — data for organizations the source never selected.
+ manager = _FakeResumableManager()
+ user_row = {
+ "id": 7,
+ "orgs": [{"id": 123, "name": "Org A"}, {"id": 456, "name": "Org B"}],
+ "rbac_roles": [
+ {"name": "Admin", "organization_id": 123},
+ {"name": "Viewer", "organization_id": 456},
+ ],
+ }
+ rows, _ = self._collect("users", manager, monkeypatch, [[user_row]], organization_id="123")
+ assert rows == [
+ {
+ "id": 7,
+ "orgs": [{"id": 123, "name": "Org A"}],
+ "rbac_roles": [{"name": "Admin", "organization_id": 123}],
+ }
+ ]
+
+ def test_missing_org_uuid_raises_for_policy_runs(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ with pytest.raises(AutomoxOrganizationError, match=ORG_NOT_FOUND_ERROR):
+ self._collect(
+ "policy_runs",
+ manager,
+ monkeypatch,
+ [[]],
+ orgs_body=[{"id": 123, "name": "Org A"}],
+ )
+
+
+class TestAutomoxSourceResponse:
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_source_response_shape(self, name: str) -> None:
+ config = AUTOMOX_ENDPOINTS[name]
+ response = automox_source(
+ api_key="key",
+ organization_id="123",
+ endpoint=name,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == name
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == config.sort_mode
+ if config.partition_key:
+ assert response.partition_keys == [config.partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+
+ def test_policy_runs_is_ascending_and_events_defers_watermark(self) -> None:
+ # policy_runs requests an explicit ascending sort so per-batch watermark checkpoints are
+ # safe; events has no documented ordering, so it must stay "desc" (watermark persisted only
+ # on completed syncs).
+ assert AUTOMOX_ENDPOINTS["policy_runs"].sort_mode == "asc"
+ assert AUTOMOX_ENDPOINTS["events"].sort_mode == "desc"
+
+ def test_partition_keys_are_stable_creation_fields(self) -> None:
+ # Guards against accidentally partitioning on a churning field like last_refresh_time.
+ assert {cfg.partition_key for cfg in AUTOMOX_ENDPOINTS.values() if cfg.partition_key} == {
+ "create_time",
+ "run_time",
+ }
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox_source.py
new file mode 100644
index 000000000000..c6fea816c495
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox_source.py
@@ -0,0 +1,183 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.automox import (
+ MULTIPLE_ORGS_ERROR,
+ ORG_NOT_FOUND_ERROR,
+ AutomoxResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.automox.source import AutomoxSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(api_key: str = "key", organization_id: str | None = None) -> Any:
+ config = MagicMock()
+ config.api_key = api_key
+ config.organization_id = organization_id
+ return config
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert AutomoxSource().source_type == ExternalDataSourceType.AUTOMOX
+
+ def test_config_is_visible_and_alpha(self) -> None:
+ config = AutomoxSource().get_source_config
+ # A finished source must not be hidden from users.
+ assert getattr(config, "unreleasedSource", None) in (None, False)
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/automox"
+
+ def test_fields(self) -> None:
+ fields = {f.name: f for f in AutomoxSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(fields) == {"api_key", "organization_id"}
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+ # The organization id is a non-secret, optional connection parameter.
+ assert fields["organization_id"].required is False
+ assert fields["organization_id"].secret is False
+
+ def test_connection_host_fields_force_secret_reentry_on_org_change(self) -> None:
+ # Changing organization_id retargets the stored API key, so it must count as a host field.
+ assert AutomoxSource().connection_host_fields == ["organization_id"]
+
+
+class TestGetSchemas:
+ def test_only_server_side_filtered_endpoints_are_incremental(self) -> None:
+ schemas = {s.name: s for s in AutomoxSource().get_schemas(_config(), team_id=1)}
+ assert set(schemas) == set(ENDPOINTS)
+ # Only events (startDate) and policy_runs (start_time) have a server-side time filter.
+ assert {name for name, s in schemas.items() if s.supports_incremental} == {"events", "policy_runs"}
+ assert [f["field"] for f in schemas["events"].incremental_fields] == ["create_time"]
+ assert [f["field"] for f in schemas["policy_runs"].incremental_fields] == ["run_time"]
+ # Fan-out style composite keys where uniqueness beyond the parent is undocumented.
+ assert schemas["packages"].detected_primary_keys == ["id", "server_id"]
+ assert schemas["policy_runs"].detected_primary_keys == ["policy_uuid", "execution_token"]
+
+ def test_names_filter(self) -> None:
+ schemas = AutomoxSource().get_schemas(_config(), team_id=1, names=["devices", "policies"])
+ assert {s.name for s in schemas} == {"devices", "policies"}
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog (no I/O) — public docs render the table list.
+ assert AutomoxSource.lists_tables_without_credentials is True
+ tables = {t["name"]: t for t in AutomoxSource().get_documented_tables()}
+ assert set(tables) == set(ENDPOINTS)
+ assert tables["devices"]["sync_methods"] == ["Full refresh"]
+ assert "Incremental" in tables["policy_runs"]["sync_methods"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", (True, None)),
+ ("invalid", (False, "Automox authentication failed.")),
+ ]
+ )
+ def test_plumbs_transport_result(self, _name: str, result: tuple[bool, str | None]) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.automox.source.validate_automox_credentials",
+ return_value=result,
+ ) as mocked:
+ assert AutomoxSource().validate_credentials(_config(organization_id="7"), team_id=1) == result
+ mocked.assert_called_once_with("key", "7")
+
+
+class TestResumableWiring:
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = AutomoxSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AutomoxResumeConfig
+
+ @parameterized.expand(
+ [
+ ("incremental", True, "2026-01-01"),
+ # A stale watermark must not leak into a full-refresh run.
+ ("full_refresh", False, None),
+ ]
+ )
+ def test_source_for_pipeline_plumbs_arguments(
+ self, _name: str, should_use_incremental_field: bool, expected_last_value: Any
+ ) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "policy_runs"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.automox.source.automox_source"
+ ) as mocked:
+ AutomoxSource().source_for_pipeline(_config(organization_id="3"), manager, inputs)
+ mocked.assert_called_once_with(
+ api_key="key",
+ organization_id="3",
+ endpoint="policy_runs",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=expected_last_value,
+ )
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://console.automox.com/api/servers?page=0&limit=500",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://console.automox.com/api/policies?page=0",
+ ),
+ # Raised by resolve_organization — the message prefixes must stay matchable.
+ ("org_not_found", f"{ORG_NOT_FOUND_ERROR}: no organization with ID 999 is accessible with this API key"),
+ (
+ "multiple_orgs",
+ f"{MULTIPLE_ORGS_ERROR}: set the organization ID on the source to pick which one to sync",
+ ),
+ ]
+ )
+ def test_permanent_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = AutomoxSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='console.automox.com', port=443): Read timed out."),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://console.automox.com/api/servers",
+ ),
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://console.automox.com/api/servers",
+ ),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = AutomoxSource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+
+class TestCanonicalDescriptions:
+ def test_canonical_descriptions_keys_are_known_endpoints(self) -> None:
+ # Every documented table must map to a real endpoint, or its descriptions never apply.
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+
+ def test_source_exposes_canonical_descriptions(self) -> None:
+ assert AutomoxSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index d36bfb370936..b53085a7b5a9 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
@@ -446,7 +446,8 @@ class Auth0SourceConfig(config.Config):
@config.config
class AutomoxSourceConfig(config.Config):
- pass
+ api_key: str
+ organization_id: str | None = None
@config.config