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(automox): add policy stats, device inventory and issue tables (#99676)

Tom Owersfd7f537a6d76
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 9b6d6fa823e5..c2ad13ca0778 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -581,14 +581,14 @@ Note: This is a webhook-ingestion source (the directory contains webhook_templat
## Automox — gaps
-Today (8): `devices`, `events`, `organizations`, `packages`, `policies`, `policy_runs`, `server_groups`, `users`
+Today (11): `device_inventory`, `devices`, `events`, `organizations`, `packages`, `policies`, `policy_runs`, `policy_stats`, `remediation_issues`, `server_groups`, `users`
Diffed against: <https://console.automox.com/api/docs/specs/console-api.json>
- [ ] `GET /servers/{deviceID}/packages` — per-device installed/available/missing patch inventory - the core patch-compliance fact table; the synced packages table is org-level only (high)
-- [ ] `GET /policystats` — per-policy compliance counts, the headline dashboard metric (high)
-- [ ] `GET /orgs/{orgID}/remediations/action-sets/{actionSetID}/issues` — vulnerability findings per remediation action set; joins to devices for risk reporting (high)
-- [ ] `GET /device-details/orgs/{orgUUID}/devices/{deviceUUID}/inventory` — hardware/software inventory detail per device beyond the base device record (medium)
+- [x] `GET /policystats` — per-policy compliance counts, the headline dashboard metric (high)
+- [x] `GET /orgs/{orgID}/remediations/action-sets/{actionSetID}/issues` — vulnerability findings per remediation action set; joins to devices for risk reporting (high)
+- [x] `GET /device-details/orgs/{orgUUID}/devices/{deviceUUID}/inventory` — hardware/software inventory detail per device beyond the base device record (medium)
- [ ] `GET /reports/needs-attention` — devices flagged as needing action, a ready-made operational breakdown (medium)
- [ ] `GET /reports/prepatch` — pre-patch report of pending patches per device before a run (medium)
- [ ] `GET /audit-service/v1/orgs/{orgUuid}/events` — console audit trail of who changed what, distinct from the device event stream already synced (medium)
@@ -598,6 +598,8 @@ Diffed against: <https://console.automox.com/api/docs/specs/console-api.json>
- [ ] `GET /accounts/{accountUUID}/rbac-roles` — role lookup resolving the rbac_role field on synced users (low)
- [ ] `GET /policy-windows/org/{orgUUID}/group/{groupUUID}/scheduled-windows` — maintenance windows per group, needed to interpret when policy runs could execute (low)
+Note: `GET /servers/{deviceID}/packages` was checked and not built. It returns the same `Packages` schema as `GET /orgs/{orgID}/packages`, which the spec describes as covering every device in the organization and whose rows already carry `server_id`, so the synced `packages` table is already the per-device patch inventory. Fanning out per device would rebuild that table at one paginated walk per device.
+
Note: Automox publishes six separate Scalar specs at /api/docs/specs/\*.json (console-api, server-groups, policy-report, audit-trail, webhooks, cloud-worklets-public); the gaps above span console-api, audit-trail and cloud-worklets-public. policy-report's /policy-history/\* endpoints are already covered by the synced policy_runs table.
## Autumn — adequate
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
index 0763bbb75b62..fcbcf88db4ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/automox.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/automox.py
@@ -1,5 +1,5 @@
-import dataclasses
-from collections.abc import Iterator
+import json
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
from urllib.parse import urlencode
@@ -10,9 +10,12 @@ 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 posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.automox.settings import (
AUTOMOX_ENDPOINTS,
AutomoxEndpointConfig,
+ AutomoxFanOutConfig,
)
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
@@ -34,6 +37,10 @@ CREDENTIAL_FIELD_NAMES = frozenset({"access_key", "intercom_hmac"})
ORG_NOT_FOUND_ERROR = "Automox organization not found"
MULTIPLE_ORGS_ERROR = "Automox API key has access to multiple organizations"
+# Reshapes one raw endpoint payload into warehouse rows, for the endpoints that don't already
+# answer with a flat row list.
+PayloadTransform = Callable[[Any], list[dict[str, Any]]]
+
class AutomoxRetryableError(Exception):
pass
@@ -43,7 +50,7 @@ class AutomoxOrganizationError(Exception):
pass
+@frozen
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.
@@ -52,6 +59,10 @@ class AutomoxResumeConfig:
# 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
+ # Fan-out endpoints only: the parent-list page the interrupted run was on, and the index within
+ # that page of the parent whose children `page` refers to.
+ parent_page: int | None = None
+ parent_index: int = 0
def _make_session(api_key: str) -> requests.Session:
@@ -95,6 +106,69 @@ def _scope_row_to_org(row: dict[str, Any], org_id: int | None, field_map: dict[s
return scoped
+def _inventory_value(value: Any) -> str | None:
+ """Render one inventory reading as text.
+
+ Automox types a reading's `value` per attribute — a plain string for most, a list of records
+ for `data_records` entries — so storing it as-is would give the column a different type
+ depending on which devices synced.
+ """
+ if value is None or isinstance(value, str):
+ return value
+ return json.dumps(value)
+
+
+def _flatten_device_inventory(payload: Any) -> list[dict[str, Any]]:
+ """Flatten a device's nested inventory tree into one row per collected attribute.
+
+ Automox answers with `categories -> <category> -> sub_categories -> <sub category> -> data`,
+ where each data entry is a single named reading. A row per reading keeps the table's columns
+ stable, which the tree is not: the categories present vary by OS and by the customer's tier.
+ """
+ documents = payload if isinstance(payload, list) else [payload]
+ rows: list[dict[str, Any]] = []
+ for document in documents:
+ if not isinstance(document, dict):
+ continue
+ categories = document.get("categories")
+ # The reference documents a second `Categories` level under `categories`, while the
+ # example responses omit it. Accept either.
+ if isinstance(categories, dict) and isinstance(categories.get("Categories"), dict):
+ categories = categories["Categories"]
+ if not isinstance(categories, dict):
+ continue
+ for category_name, category in categories.items():
+ sub_categories = category.get("sub_categories") if isinstance(category, dict) else None
+ if not isinstance(sub_categories, dict):
+ continue
+ for sub_category_name, sub_category in sub_categories.items():
+ entries = sub_category.get("data") if isinstance(sub_category, dict) else None
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if not isinstance(entry, dict) or entry.get("name") is None:
+ continue
+ rows.append(
+ {
+ "category": category_name,
+ "sub_category": sub_category_name,
+ "name": entry.get("name"),
+ "friendly_name": entry.get("friendly_name"),
+ "description": entry.get("description"),
+ "type": entry.get("type"),
+ "value": _inventory_value(entry.get("value")),
+ "tags": entry.get("tags"),
+ "collected_at": entry.get("collected_at"),
+ }
+ )
+ return rows
+
+
+PAYLOAD_TRANSFORMS: dict[str, PayloadTransform] = {
+ "device_inventory": _flatten_device_inventory,
+}
+
+
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)}"
@@ -121,7 +195,11 @@ def _fetch_json(session: requests.Session, url: str, logger: FilteringBoundLogge
def _fetch_page(
- session: requests.Session, config: AutomoxEndpointConfig, url: str, logger: FilteringBoundLogger
+ session: requests.Session,
+ config: AutomoxEndpointConfig,
+ url: str,
+ logger: FilteringBoundLogger,
+ transform: Optional["PayloadTransform"] = None,
) -> list[dict[str, Any]]:
payload = _fetch_json(session, url, logger)
@@ -130,6 +208,9 @@ def _fetch_page(
raise ValueError(f"Automox API returned a non-object response: url={url}")
payload = payload.get(config.data_selector) or []
+ if transform is not None:
+ return transform(payload)
+
# 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.
@@ -226,6 +307,149 @@ def _incremental_param_value(config: AutomoxEndpointConfig, last_value: Any) ->
return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _fan_out_configs(config: AutomoxEndpointConfig) -> list[AutomoxEndpointConfig]:
+ return [config] if config.fan_out is None else [config, config.fan_out.parent]
+
+
+def _needs_organization(config: AutomoxEndpointConfig) -> bool:
+ return any(
+ c.needs_org_id_param or c.org_uuid_param or c.restrict_to_org or "{org_id}" in c.path or "{org_uuid}" in c.path
+ for c in _fan_out_configs(config)
+ )
+
+
+def _requires_org_uuid(config: AutomoxEndpointConfig) -> bool:
+ return any(c.org_uuid_param is not None or "{org_uuid}" in c.path for c in _fan_out_configs(config))
+
+
+def _resolve_path(path: str, org_id: int | None, org_uuid: str | None) -> str:
+ if org_id is not None:
+ path = path.replace("{org_id}", str(org_id))
+ if org_uuid is not None:
+ path = path.replace("{org_uuid}", org_uuid)
+ return path
+
+
+def _request_params(
+ config: AutomoxEndpointConfig,
+ page: int,
+ org_id: int | None,
+ org_uuid: str | None,
+ incremental_value: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.paginated:
+ params["page"] = page
+ params["limit"] = config.page_size
+ params.update(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
+ return params
+
+
+@frozen
+class _EndpointPage:
+ number: int
+ # `True` when this is the resource's last page, so the caller stops instead of advancing.
+ is_last: bool
+ rows: list[dict[str, Any]]
+
+
+def _iter_pages(
+ session: requests.Session,
+ config: AutomoxEndpointConfig,
+ path: str,
+ logger: FilteringBoundLogger,
+ start_page: int,
+ org_id: int | None,
+ org_uuid: str | None,
+ incremental_value: str | None = None,
+ transform: Optional[PayloadTransform] = None,
+) -> Iterator[_EndpointPage]:
+ """Walk one endpoint path, yielding a page at a time until the resource is exhausted."""
+ page = start_page
+ while True:
+ url = _build_url(path, _request_params(config, page, org_id, org_uuid, incremental_value))
+ rows = _fetch_page(session, config, url, logger, transform)
+ if not rows:
+ return
+
+ # Decide on the raw page length: the caller's filtering can shrink a page without meaning
+ # the resource is exhausted.
+ is_last = not config.paginated or len(rows) < config.page_size
+ yield _EndpointPage(number=page, is_last=is_last, rows=rows)
+ if is_last:
+ return
+ page += 1
+
+
+def _sanitize_rows(
+ config: AutomoxEndpointConfig, rows: list[dict[str, Any]], org_id: int | None
+) -> list[dict[str, Any]]:
+ 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]
+ return rows
+
+
+def _iter_fan_out_rows(
+ session: requests.Session,
+ config: AutomoxEndpointConfig,
+ fan_out: AutomoxFanOutConfig,
+ path: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AutomoxResumeConfig],
+ resume: AutomoxResumeConfig | None,
+ org_id: int | None,
+ org_uuid: str | None,
+ transform: Optional[PayloadTransform] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the parent list and call the child endpoint once per parent row."""
+ parent_path = _resolve_path(fan_out.parent.path, org_id, org_uuid)
+ parent_page, skip_parents, child_page = 0, 0, 0
+ if resume is not None and resume.parent_page is not None:
+ parent_page, skip_parents, child_page = resume.parent_page, resume.parent_index, resume.page
+
+ for parent_batch in _iter_pages(session, fan_out.parent, parent_path, logger, parent_page, org_id, org_uuid):
+ # Resuming re-reads the parent page and skips the parents already walked. Automox does not
+ # promise a stable order across requests, so a parent added mid-sync can shift the page;
+ # the merge dedupes whatever is re-read, and the next full sync picks up anything shifted.
+ for index in range(skip_parents, len(parent_batch.rows)):
+ start_child_page, child_page = child_page, 0
+ parent = parent_batch.rows[index]
+ parent_value = parent.get(fan_out.parent_field)
+ if parent_value is None:
+ continue
+
+ child_path = path.replace(fan_out.placeholder, str(parent_value))
+ parent_columns = {column: parent.get(field) for field, column in fan_out.include_from_parent.items()}
+
+ for child_batch in _iter_pages(
+ session, config, child_path, logger, start_child_page, org_id, org_uuid, transform=transform
+ ):
+ rows = [{**parent_columns, **row} for row in _sanitize_rows(config, child_batch.rows, org_id)]
+ if rows:
+ yield rows
+ # Save AFTER yielding so a crash re-runs the last batch rather than skipping it.
+ if not child_batch.is_last:
+ resumable_source_manager.save_state(
+ AutomoxResumeConfig(
+ page=child_batch.number + 1, parent_page=parent_batch.number, parent_index=index
+ )
+ )
+
+ resumable_source_manager.save_state(
+ AutomoxResumeConfig(page=0, parent_page=parent_batch.number, parent_index=index + 1)
+ )
+ skip_parents = 0
+
+
def get_rows(
api_key: str,
organization_id: str | None,
@@ -241,15 +465,14 @@ def get_rows(
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:
+ if _needs_organization(config):
org_id, org_uuid = resolve_organization(session, organization_id, logger)
- if config.org_uuid_param and not org_uuid:
+ if _requires_org_uuid(config) 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:
@@ -258,48 +481,47 @@ def get_rows(
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
+ logger.debug(f"Automox: resuming {endpoint} from page={resume.page}")
- 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)]
+ path = _resolve_path(config.path, org_id, org_uuid)
+ transform = PAYLOAD_TRANSFORMS.get(endpoint)
- 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 config.fan_out is not None:
+ yield from _iter_fan_out_rows(
+ session=session,
+ config=config,
+ fan_out=config.fan_out,
+ path=path,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ resume=resume,
+ org_id=org_id,
+ org_uuid=org_uuid,
+ transform=transform,
+ )
+ return
+
+ for batch in _iter_pages(
+ session,
+ config,
+ path,
+ logger,
+ resume.page if resume else 0,
+ org_id,
+ org_uuid,
+ incremental_value,
+ transform,
+ ):
+ rows = _sanitize_rows(config, batch.rows, org_id)
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))
+ if not batch.is_last:
+ resumable_source_manager.save_state(
+ AutomoxResumeConfig(page=batch.number + 1, incremental_param_value=incremental_value)
+ )
def automox_source(
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
index 6635efddc47d..2c03eaaa5f79 100644
--- 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
@@ -4,6 +4,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
# Sourced from the official Automox Console API reference (https://console.automox.com/api/docs).
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "device_inventory": {
+ "description": "One collected inventory reading for a device, flattened out of Automox's per-device category tree. Covers hardware, health, network, security, services, system and user detail beyond the base device record.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "device_uuid": "UUID of the device the reading was collected from.",
+ "device_id": "ID of the device the reading was collected from, joining to the devices table.",
+ "category": "Inventory category the reading belongs to (Hardware, Health, Network, Security, Services, Summary, System, or Users).",
+ "sub_category": "Sub-category the reading belongs to within its category.",
+ "name": "Machine name of the reading (e.g. board_serial, cpu_info).",
+ "friendly_name": "Display name of the reading shown in the Automox console.",
+ "description": "What the reading measures.",
+ "type": "Type Automox reports for the reading's value (e.g. string, data_records).",
+ "value": "The collected value, stored as text. Readings that carry a list of records are stored as JSON.",
+ "tags": "Tags Automox assigns to the reading.",
+ "collected_at": "Date and time when the agent collected the reading.",
+ },
+ },
"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",
@@ -139,6 +156,29 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"remediation_not_applicable": "Number of devices where remediation was not applicable.",
},
},
+ "policy_stats": {
+ "description": "Device compliance counts for a policy: how many devices are compliant, non-compliant, or still pending.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "organization_id": "ID of the organization the policy belongs to.",
+ "policy_id": "ID of the policy these counts describe, joining to the policies table.",
+ "policy_name": "Name of the policy.",
+ "policy_type_name": "Type of the policy (patch, custom for a worklet policy, or required_software).",
+ "compliant": "Number of devices compliant with the policy.",
+ "noncompliant": "Number of devices not compliant with the policy.",
+ "pending": "Number of devices whose compliance with the policy is still pending.",
+ },
+ },
+ "remediation_issues": {
+ "description": "A problem Automox hit while ingesting an uploaded vulnerability report into a remediation action set, such as a hostname in the report that matches no managed device.",
+ "docs_url": "https://console.automox.com/api/docs#console-api",
+ "columns": {
+ "action_set_id": "ID of the remediation action set the issue was found in.",
+ "id": "Unique identifier for the issue within its action set.",
+ "issue_type": "Type of problem found (currently unknown-host).",
+ "issue_details": "Details of the problem, such as the hostname that could not be matched.",
+ },
+ },
"server_groups": {
"description": "A server group used to organize devices and target policies.",
"docs_url": "https://console.automox.com/api/docs#console-api",
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
index 743ff60f108a..52b4200edcee 100644
--- 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
@@ -20,7 +20,7 @@ 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.
+[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, software packages, and per-policy compliance counts into the PostHog Data warehouse, so you can trend remediation coverage and device compliance across your fleet alongside your product data.
## Prerequisites
@@ -43,7 +43,12 @@ To connect Automox, you need:
<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.
+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 remaining tables 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.
+
+Two tables are gathered per device or per report rather than from a single list endpoint, so they make one request per parent record and take longer to sync than the rest:
+
+- `device_inventory` reads hardware, health, network, security and system detail for every device in the organization. Expect one request per device.
+- `remediation_issues` reads the problems found while ingesting each uploaded vulnerability report, such as a hostname in the report that matches no managed device.
## Configuration
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
index 4cc4458430c2..71f5e90ece09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/automox/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/automox/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from datetime import timedelta
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -14,7 +16,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
-@dataclass
+@frozen
class AutomoxEndpointConfig:
# Console API path, relative to https://console.automox.com/api. May contain an
# `{org_id}` placeholder resolved at sync time.
@@ -28,6 +30,9 @@ class AutomoxEndpointConfig:
# Automox caps `limit` at 500 for Console API list endpoints (policy_runs allows more, but
# 500 keeps response sizes bounded).
page_size: int = 500
+ # `False` for endpoints that answer with the whole collection and take no page/limit params.
+ # Sending them anyway risks looping on the same rows if the API ignores them.
+ paginated: bool = True
# 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
@@ -55,15 +60,57 @@ class AutomoxEndpointConfig:
# 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)
+ # Set when the endpoint is only reachable per parent resource, so the sync walks the parent
+ # list first and calls this endpoint once per parent row.
+ fan_out: "AutomoxFanOutConfig | None" = None
+
+
+@frozen
+class AutomoxFanOutConfig:
+ # List endpoint walked to enumerate the parents. It does not have to be a synced table.
+ parent: AutomoxEndpointConfig
+ # Field on each parent row substituted into the child path.
+ parent_field: str
+ # Placeholder in the child path replaced with `parent_field`'s value.
+ placeholder: str
+ # Parent field -> column added to every child row. Child rows aggregate across all parents, so
+ # the parent identifier both joins the table back to its parent and completes the primary key.
+ include_from_parent: dict[str, str]
+
+
+# Parent of a fan-out endpoint that is not itself a synced table: an action set is one ingestion of
+# a vulnerability report, only useful here to reach its issues.
+_ACTION_SETS_PARENT = AutomoxEndpointConfig(
+ path="/orgs/{org_id}/remediations/action-sets",
+ data_selector="data",
+)
+
+# The devices endpoint doubles as the fan-out parent for per-device detail endpoints, so both walk
+# exactly the same device list.
+_DEVICES_ENDPOINT = AutomoxEndpointConfig(
+ path="/servers",
+ partition_key="create_time",
+ needs_org_id_param=True,
+)
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,
+ # Per-device hardware, health, network, security and system inventory, one row per collected
+ # attribute. Automox answers with a nested category tree per device and the categories present
+ # vary by OS and by the customer's Automox tier, so the tree is flattened into attribute rows.
+ "device_inventory": AutomoxEndpointConfig(
+ path="/device-details/orgs/{org_uuid}/devices/{device_uuid}/inventory",
+ primary_keys=["device_uuid", "category", "sub_category", "name"],
+ paginated=False,
+ fan_out=AutomoxFanOutConfig(
+ parent=_DEVICES_ENDPOINT,
+ parent_field="uuid",
+ placeholder="{device_uuid}",
+ include_from_parent={"uuid": "device_uuid", "id": "device_id"},
+ ),
),
+ # Core device inventory. No server-side updated-since filter exists, so full refresh only.
+ "devices": _DEVICES_ENDPOINT,
# 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
@@ -117,6 +164,27 @@ AUTOMOX_ENDPOINTS: dict[str, AutomoxEndpointConfig] = {
extra_params={"sort": "run_time:asc"},
sort_mode="asc",
),
+ # Per-policy device compliance counts, the headline number on the Automox dashboard. The
+ # endpoint answers with every policy's stats in one array and takes no pagination params.
+ "policy_stats": AutomoxEndpointConfig(
+ path="/policystats",
+ primary_keys=["organization_id", "policy_id"],
+ needs_org_id_param=True,
+ paginated=False,
+ ),
+ # Hosts named in an uploaded vulnerability report that Automox could not match to a managed
+ # device, per remediation action set.
+ "remediation_issues": AutomoxEndpointConfig(
+ path="/orgs/{org_id}/remediations/action-sets/{action_set_id}/issues",
+ primary_keys=["action_set_id", "id"],
+ data_selector="data",
+ fan_out=AutomoxFanOutConfig(
+ parent=_ACTION_SETS_PARENT,
+ parent_field="id",
+ placeholder="{action_set_id}",
+ include_from_parent={"id": "action_set_id"},
+ ),
+ ),
"server_groups": AutomoxEndpointConfig(
path="/servergroups",
needs_org_id_param=True,
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
index 9934123c061a..2bfbe73a45f2 100644
--- 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
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.automox.au
AutomoxResumeConfig,
AutomoxRetryableError,
_build_url,
+ _flatten_device_inventory,
_incremental_param_value,
automox_source,
get_rows,
@@ -417,6 +418,213 @@ class TestGetRows:
)
+def _inventory_reading(name: str, value: Any, reading_type: str = "string") -> dict[str, Any]:
+ return {
+ "name": name,
+ "friendly_name": name.replace("_", " ").title(),
+ "description": f"{name} reading",
+ "collected_at": "2026-02-13T19:33:40+00:00",
+ "type": reading_type,
+ "value": value,
+ "tags": ["system"],
+ }
+
+
+INVENTORY_BODY = {
+ "categories": {
+ "Hardware": {
+ "sub_categories": {
+ "Hardware": {"data": [_inventory_reading("board_serial", "SN-1")]},
+ "CPU": {"data": [_inventory_reading("cpu_info", [{"model": "amd64"}], "data_records")]},
+ }
+ }
+ }
+}
+
+
+class TestFlattenDeviceInventory:
+ def test_emits_a_row_per_reading(self) -> None:
+ rows = _flatten_device_inventory(INVENTORY_BODY)
+ assert [(r["category"], r["sub_category"], r["name"]) for r in rows] == [
+ ("Hardware", "Hardware", "board_serial"),
+ ("Hardware", "CPU", "cpu_info"),
+ ]
+ assert rows[0]["value"] == "SN-1"
+ assert rows[0]["collected_at"] == "2026-02-13T19:33:40+00:00"
+
+ def test_record_values_are_stored_as_json(self) -> None:
+ # A reading's value is a string on most attributes and a list of records on others, so a
+ # raw value would give the column a different type depending on which devices synced.
+ rows = _flatten_device_inventory(INVENTORY_BODY)
+ assert rows[1]["value"] == json.dumps([{"model": "amd64"}])
+
+ def test_accepts_the_documented_nested_categories_level(self) -> None:
+ # The API reference nests a second `Categories` level that the example responses omit.
+ payload = {"categories": {"Categories": INVENTORY_BODY["categories"]}}
+ assert len(_flatten_device_inventory(payload)) == 2
+
+ def test_accepts_a_list_payload(self) -> None:
+ assert len(_flatten_device_inventory([INVENTORY_BODY])) == 2
+
+ @parameterized.expand(
+ [
+ ("empty_body", {}),
+ ("null_categories", {"categories": None}),
+ ("category_without_sub_categories", {"categories": {"Hardware": {}}}),
+ ("sub_category_without_data", {"categories": {"Hardware": {"sub_categories": {"CPU": {}}}}}),
+ (
+ "reading_without_name",
+ {"categories": {"Hardware": {"sub_categories": {"CPU": {"data": [{"value": "x"}]}}}}},
+ ),
+ ]
+ )
+ def test_unusable_payloads_yield_no_rows(self, _name: str, payload: Any) -> None:
+ # Automox varies which categories a device reports by OS and by the customer's tier, so an
+ # absent branch must be skipped rather than crash the sync.
+ assert _flatten_device_inventory(payload) == []
+
+
+class TestFanOutAndUnpaginatedEndpoints:
+ @staticmethod
+ def _drive(
+ endpoint: str,
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ routes: dict[str, list[Any]],
+ organization_id: str | None = "123",
+ orgs_body: list[dict] | None = None,
+ ) -> tuple[list[dict], list[str]]:
+ """Drive ``get_rows`` with canned page bodies routed by URL path."""
+ requested: list[str] = []
+
+ def fake_fetch_json(session: Any, url: str, logger: Any) -> Any:
+ requested.append(url)
+ parsed = urlparse(url)
+ if parsed.path == "/api/orgs":
+ return orgs_body if orgs_body is not None else ORGS_BODY
+ pages = routes.get(parsed.path)
+ if pages is None:
+ raise AssertionError(f"unexpected request: {url}")
+ index = int(parse_qs(parsed.query).get("page", ["0"])[0])
+ if index < len(pages):
+ return pages[index]
+ # Past the last canned page, answer in the same shape the endpoint uses.
+ return {"data": []} if pages and isinstance(pages[0], dict) and "data" in pages[0] else []
+
+ 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]
+ ):
+ rows.extend(page)
+ return rows, requested
+
+ @staticmethod
+ def _inventory_routes(*device_uuids: str) -> dict[str, list[Any]]:
+ routes: dict[str, list[Any]] = {
+ "/api/servers": [[{"id": index, "uuid": uuid} for index, uuid in enumerate(device_uuids, start=1)]]
+ }
+ for uuid in device_uuids:
+ routes[f"/api/device-details/orgs/uuid-123/devices/{uuid}/inventory"] = [INVENTORY_BODY]
+ return routes
+
+ def test_device_inventory_calls_each_device_and_injects_parent_columns(self, monkeypatch: Any) -> None:
+ # Readings aggregate across every device, so each row needs the device identifiers: they
+ # join the table back to devices and complete the primary key.
+ manager = _FakeResumableManager()
+ rows, urls = self._drive("device_inventory", manager, monkeypatch, self._inventory_routes("dev-1", "dev-2"))
+
+ inventory_urls = [u for u in urls if "/inventory" in u]
+ assert [urlparse(u).path for u in inventory_urls] == [
+ "/api/device-details/orgs/uuid-123/devices/dev-1/inventory",
+ "/api/device-details/orgs/uuid-123/devices/dev-2/inventory",
+ ]
+ assert len(rows) == 4
+ assert {(r["device_uuid"], r["device_id"]) for r in rows} == {("dev-1", 1), ("dev-2", 2)}
+
+ def test_device_inventory_sends_no_pagination_params(self, monkeypatch: Any) -> None:
+ # The endpoint returns the whole tree and documents no page/limit params; sending them and
+ # paging on a short page would re-request the same payload forever.
+ manager = _FakeResumableManager()
+ _, urls = self._drive("device_inventory", manager, monkeypatch, self._inventory_routes("dev-1"))
+ inventory_urls = [u for u in urls if "/inventory" in u]
+ assert len(inventory_urls) == 1
+ assert _query(inventory_urls[0]) == {}
+
+ def test_device_inventory_requires_an_org_uuid(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ with pytest.raises(AutomoxOrganizationError, match=ORG_NOT_FOUND_ERROR):
+ self._drive(
+ "device_inventory",
+ manager,
+ monkeypatch,
+ self._inventory_routes("dev-1"),
+ orgs_body=[{"id": 123, "name": "Org A"}],
+ )
+
+ def test_fan_out_state_advances_past_each_finished_parent(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ self._drive("device_inventory", manager, monkeypatch, self._inventory_routes("dev-1", "dev-2"))
+ assert manager.saved == [
+ AutomoxResumeConfig(page=0, parent_page=0, parent_index=1),
+ AutomoxResumeConfig(page=0, parent_page=0, parent_index=2),
+ ]
+
+ def test_fan_out_resume_skips_parents_already_walked(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(AutomoxResumeConfig(page=0, parent_page=0, parent_index=1))
+ rows, urls = self._drive("device_inventory", manager, monkeypatch, self._inventory_routes("dev-1", "dev-2"))
+ assert [urlparse(u).path for u in urls if "/inventory" in u] == [
+ "/api/device-details/orgs/uuid-123/devices/dev-2/inventory"
+ ]
+ assert {r["device_uuid"] for r in rows} == {"dev-2"}
+
+ def test_remediation_issues_paginate_per_action_set(self, monkeypatch: Any) -> None:
+ page_size = AUTOMOX_ENDPOINTS["remediation_issues"].page_size
+ full_page = {"data": [{"id": i, "issue_type": "unknown-host"} for i in range(page_size)]}
+ last_page = {"data": [{"id": page_size, "issue_type": "unknown-host"}]}
+ manager = _FakeResumableManager()
+ rows, urls = self._drive(
+ "remediation_issues",
+ manager,
+ monkeypatch,
+ {
+ "/api/orgs/123/remediations/action-sets": [{"data": [{"id": 17194}]}],
+ "/api/orgs/123/remediations/action-sets/17194/issues": [full_page, last_page],
+ },
+ )
+
+ issue_urls = [u for u in urls if u.endswith("issues") or "/issues?" in u]
+ assert [_query(u)["page"] for u in issue_urls] == [["0"], ["1"]]
+ assert len(rows) == page_size + 1
+ # The issue id is only unique within its action set, so the action set id completes the key.
+ assert all(row["action_set_id"] == 17194 for row in rows)
+ # Mid-parent state points at the next child page, then advances past the finished parent.
+ assert manager.saved == [
+ AutomoxResumeConfig(page=1, parent_page=0, parent_index=0),
+ AutomoxResumeConfig(page=0, parent_page=0, parent_index=1),
+ ]
+
+ def test_policy_stats_sends_the_org_param_and_no_pagination(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, urls = self._drive(
+ "policy_stats",
+ manager,
+ monkeypatch,
+ {"/api/policystats": [[{"organization_id": 123, "policy_id": 270658, "compliant": 2}]]},
+ )
+ stats_urls = [u for u in urls if "/policystats" in u]
+ assert len(stats_urls) == 1
+ assert _query(stats_urls[0]) == {"o": ["123"]}
+ assert rows == [{"organization_id": 123, "policy_id": 270658, "compliant": 2}]
+ assert manager.saved == []
+
+
class TestAutomoxSourceResponse:
@parameterized.expand([(name,) for name in ENDPOINTS])
def test_source_response_shape(self, name: str) -> None: