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(cisco-duo): add endpoints, policies and group membership tables (#102945)

Tom Owers62a0b4643abe
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 fb74b61efa4d..0f97f44f4dd5 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
@@ -1517,14 +1517,14 @@ Note: All nine Insights tables map cleanly onto spec paths; the gap is the remai
## CiscoDuo — gaps
-Today (9): `activity_logs`, `administrator_logs`, `admins`, `authentication_logs`, `groups`, `integrations`, `phones`, `telephony_logs`, `users`
+Today (12): `activity_logs`, `administrator_logs`, `admins`, `authentication_logs`, `endpoints`, `group_users`, `groups`, `integrations`, `phones`, `policies`, `telephony_logs`, `users`
Diffed against: <https://duo.com/docs/adminapi>
-- [ ] `/admin/v2/policies` — policy lookup resolving the policy keys referenced by authentication and activity logs (high)
-- [ ] `/admin/v2/groups/{group_id}/users (and /admin/v1/users/{user_id}/groups)` — user-to-group membership join table - we sync users and groups but not the link between them (high)
+- [x] `/admin/v2/policies` — policy lookup resolving the policy keys referenced by authentication and activity logs (high)
+- [x] `/admin/v2/groups/{group_id}/users (and /admin/v1/users/{user_id}/groups)` — user-to-group membership join table - we sync users and groups but not the link between them (high)
- [ ] `/admin/v1/trust_monitor/events` — Duo Trust Monitor security events, the vendor's flagged-risk feed (high)
-- [ ] `/admin/v1/endpoints` — managed endpoint/device inventory with OS, browser and plugin versions - resolves device IDs in auth logs (high)
+- [x] `/admin/v1/endpoints` — managed endpoint/device inventory with OS, browser and plugin versions - resolves device IDs in auth logs (high)
- [ ] `/admin/v1/tokens` — hardware token inventory, the second-factor dimension missing next to phones (medium)
- [ ] `/admin/v1/webauthncredentials` — WebAuthn/security-key enrollment inventory for MFA method coverage reporting (medium)
- [ ] `/admin/v1/registered_devices` — registered and blocked device records for device-trust analysis (medium)
@@ -1535,6 +1535,13 @@ Diffed against: <https://duo.com/docs/adminapi>
- [ ] `/admin/v1/administrative_units` — administrative unit scoping that segments admins, groups and integrations (low)
Note: Static endpoint config, no dynamic table discovery. Excluded settings, branding, bulk operations, activation links and directory-sync trigger endpoints as config/plumbing.
+Trust Monitor is deliberately not wired up: Duo removed it from the Admin Panel in July 2026, it is
+unavailable to accounts created after 29 September 2025, and the API endpoint reaches end of support
+on 31 January 2027. Its replacement, Cisco Identity Intelligence, is a separate Graph API and webhook
+surface rather than an Admin API endpoint, so it is not a gap in this source.
+`group_users` fans out over `/admin/v1/groups` rather than over users, which is the cheaper side of
+the same join; `/admin/v1/users/{user_id}/groups` therefore needs no separate table.
+The two `/admin/v2` additions sign with Duo's v5 scheme, since some v2 handlers reject legacy v2 signing.
## Clari — gaps
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 b969929f8177..29433c030120 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -192,7 +192,7 @@ the row lists both.
| circleci | HTTP | requests | ✅ |
| circleci_insights | HTTP | requests | ✅ |
| cimis | HTTP | requests | ✅ |
-| cisco_duo | HTTP | requests (hand-rolled HMAC-SHA1 request signing) | ✅ |
+| cisco_duo | HTTP | requests (hand-rolled HMAC-SHA1/SHA-512 request signing) | ✅ |
| cloudflare | HTTP | requests | ✅ |
| clari | HTTP | requests | ✅ |
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/canonical_descriptions.py
index 21038121829e..c069491261de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/canonical_descriptions.py
@@ -87,6 +87,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"status": "Authentication status applied to the group's users: active, bypass, or disabled.",
},
},
+ "group_users": {
+ "description": "One row per user-to-group membership: the group, plus the user object Duo returns for it. A user appears once for every group they belong to.",
+ "docs_url": "https://duo.com/docs/adminapi#retrieve-users-by-group-id",
+ "columns": {
+ "group_id": "Unique identifier of the group the membership is for.",
+ "user_id": "Unique identifier of the member.",
+ "username": "The member's login name.",
+ "email": "The member's email address.",
+ "realname": "The member's real name.",
+ "status": "Enrollment/access status: active, bypass, disabled, locked out, or pending deletion.",
+ },
+ },
"phones": {
"description": "Phones and tablets registered with Duo, including platform, capabilities, and attached users.",
"docs_url": "https://duo.com/docs/adminapi#phones",
@@ -102,6 +114,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"users": "Users the phone is attached to.",
},
},
+ "endpoints": {
+ "description": "Managed endpoints (computers and devices) seen authenticating to Duo, with their operating system and browser versions. Duo purges a record after 30 days of inactivity.",
+ "docs_url": "https://duo.com/docs/adminapi#endpoints",
+ "columns": {
+ "epkey": "Unique identifier of the endpoint. Also appears as the access device key on authentication log rows.",
+ "username": "The Duo username the endpoint authenticated as.",
+ "email": "Email address of the user the endpoint belongs to.",
+ "os_family": "The endpoint's operating system family, such as Windows or Mac OS X.",
+ "os_version": "The endpoint's operating system version.",
+ "model": "The endpoint's hardware model.",
+ "type": "The endpoint type, such as computer or phone.",
+ "browsers": "Browsers seen on the endpoint, each with its browser family, browser version, flash version, and java version.",
+ },
+ },
"admins": {
"description": "Administrators of the Duo account, with their role and status.",
"docs_url": "https://duo.com/docs/adminapi#administrators",
@@ -125,4 +151,12 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"notes": "Free-form notes about the integration.",
},
},
+ "policies": {
+ "description": "Policies defining the access and authentication requirements Duo applies, and the settings each one overrides.",
+ "docs_url": "https://duo.com/docs/adminapi#policies",
+ "columns": {
+ "policy_key": "Unique identifier of the policy. Authentication and activity log rows reference these keys.",
+ "sections": "The policy settings this policy sets, grouped by section, such as browsers or authentication methods.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/cisco_duo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/cisco_duo.py
index 06e6c2a222b2..6275e347ad61 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/cisco_duo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/cisco_duo.py
@@ -2,7 +2,6 @@ import re
import hmac
import base64
import hashlib
-import dataclasses
import email.utils
from collections.abc import Iterator
from datetime import UTC, date, datetime
@@ -14,10 +13,13 @@ from dateutil import parser as dateutil_parser
from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, 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.cisco_duo.settings import (
CISCO_DUO_ENDPOINTS,
DEFAULT_LOOKBACK_DAYS,
CiscoDuoEndpointConfig,
+ SigVersion,
)
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.mixins import _is_host_safe
@@ -40,6 +42,10 @@ ALLOWED_HOST_SUFFIXES = (".duosecurity.com", ".duofederal.com")
HOST_NOT_ALLOWED_ERROR = "Cisco Duo API hostname is not allowed"
+# v5 signing covers a hash of the request body and of the signed X-Duo-* headers. Every request
+# this source makes is a GET with neither, so both slots are the hash of the empty string.
+_EMPTY_SHA512 = hashlib.sha512(b"").hexdigest()
+
class CiscoDuoRetryableError(Exception):
def __init__(self, message: str, retry_after: float | None = None) -> None:
@@ -58,15 +64,20 @@ class CiscoDuoLogSaturationError(Exception):
pass
+@frozen
class CiscoDuoResumeConfig:
# v2 logs: opaque cursor within a fixed [mintime, maxtime] window (both ms).
next_offset: str | None = None
# v2 logs: window bounds (ms). v1 admin log: advancing mintime cursor (seconds).
mintime: int | None = None
maxtime: int | None = None
- # v1 resource lists: integer pagination offset.
+ # Resource lists: integer pagination offset. For a fan-out endpoint this is the offset
+ # within the parent named by `parent_id`.
offset: int | None = None
+ # Fan-out only: offset of the parent page being walked, and the parent whose children are
+ # next. `parent_id` of None means start at the top of that parent page.
+ parent_offset: int | None = None
+ parent_id: str | None = None
def normalize_hostname(hostname: str) -> str:
@@ -95,18 +106,31 @@ def _canonicalize_params(params: dict[str, str]) -> str:
def sign_request(
- method: str, hostname: str, path: str, params: dict[str, str], integration_key: str, secret_key: str, date_str: str
+ method: str,
+ hostname: str,
+ path: str,
+ params: dict[str, str],
+ integration_key: str,
+ secret_key: str,
+ date_str: str,
+ sig_version: SigVersion = 2,
) -> dict[str, str]:
"""Build the Date + Authorization headers for a Duo Admin API request.
- Duo authenticates every request with an HMAC-SHA1 signature over a canonical string of the
- date, method, host, path, and sorted params, sent as HTTP Basic auth with the integration
- key as the username.
+ Duo authenticates every request with an HMAC signature over a canonical string of the date,
+ method, host, path, and sorted params, sent as HTTP Basic auth with the integration key as
+ the username. v2 signs that string with SHA-1; v5 appends the body and signed-header hashes
+ and signs with SHA-512. Both carry the same two headers, so only the digest differs.
"""
- canon = "\n".join([date_str, method.upper(), hostname.lower(), path, _canonicalize_params(params)])
- # Duo's Admin API mandates HMAC-SHA1 request signing — not used for secrecy or collision resistance.
- # nosemgrep: python.lang.security.insecure-hash-algorithms-sha1.insecure-hash-algorithm-sha1
- signature = hmac.new(secret_key.encode("utf-8"), canon.encode("utf-8"), hashlib.sha1).hexdigest()
+ canon_parts = [date_str, method.upper(), hostname.lower(), path, _canonicalize_params(params)]
+ if sig_version == 5:
+ canon_parts += [_EMPTY_SHA512, _EMPTY_SHA512]
+ digestmod = hashlib.sha512
+ else:
+ # Duo's v2 signing mandates HMAC-SHA1 — not used for secrecy or collision resistance.
+ # nosemgrep: python.lang.security.insecure-hash-algorithms-sha1.insecure-hash-algorithm-sha1
+ digestmod = hashlib.sha1
+ signature = hmac.new(secret_key.encode("utf-8"), "\n".join(canon_parts).encode("utf-8"), digestmod).hexdigest()
basic = base64.b64encode(f"{integration_key}:{signature}".encode()).decode()
return {"Date": date_str, "Authorization": f"Basic {basic}", "Accept": "application/json"}
@@ -139,10 +163,13 @@ def _fetch_json_once(
integration_key: str,
secret_key: str,
logger: FilteringBoundLogger,
+ sig_version: SigVersion = 2,
) -> dict[str, Any]:
# The Date header is part of the signature and Duo rejects requests with too much clock
# skew, so re-sign with a fresh date on every attempt (retries can back off for minutes).
- headers = sign_request("GET", hostname, path, params, integration_key, secret_key, email.utils.formatdate())
+ headers = sign_request(
+ "GET", hostname, path, params, integration_key, secret_key, email.utils.formatdate(), sig_version
+ )
url = _build_url(hostname, path, params)
# Don't follow redirects: the customer-controlled host could 3xx at an internal address,
@@ -351,6 +378,13 @@ def _get_log_v1_rows(
break
+def _redact(items: list[dict[str, Any]], config: CiscoDuoEndpointConfig) -> list[dict[str, Any]]:
+ for field_name in config.redact_fields or ():
+ for item in items:
+ item.pop(field_name, None)
+ return items
+
+
def _get_list_v1_rows(
session: requests.Session,
hostname: str,
@@ -369,16 +403,14 @@ def _get_list_v1_rows(
while True:
params = {"limit": str(LIST_V1_PAGE_SIZE), "offset": str(offset)}
- data = _fetch_json(session, hostname, config.path, params, integration_key, secret_key, logger)
+ data = _fetch_json(
+ session, hostname, config.path, params, integration_key, secret_key, logger, config.sig_version
+ )
items = data.get("response") or []
metadata = data.get("metadata") or {}
if items:
- if config.redact_fields:
- for item in items:
- for field_name in config.redact_fields:
- item.pop(field_name, None)
- yield items
+ yield _redact(items, config)
raw_next_offset = metadata.get("next_offset")
if raw_next_offset is None or raw_next_offset in ("", []):
@@ -387,6 +419,114 @@ def _get_list_v1_rows(
resumable_source_manager.save_state(CiscoDuoResumeConfig(offset=offset))
+def _first_parent_id(parents: list[dict[str, Any]], id_field: str) -> str | None:
+ for parent in parents:
+ parent_id = parent.get(id_field)
+ if parent_id:
+ return str(parent_id)
+ return None
+
+
+def _get_fanout_v1_rows(
+ session: requests.Session,
+ hostname: str,
+ integration_key: str,
+ secret_key: str,
+ config: CiscoDuoEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CiscoDuoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Page a child resource list once per parent, writing the parent id onto every child row.
+
+ Both levels use limit/offset paging. Each checkpoint names the work still to do — the parent
+ page, the parent within it, and the child offset — rather than the work just done, because
+ fan-out tables are full-refresh only: a resume that re-yielded a page would duplicate those
+ rows instead of merging over them.
+ """
+ if config.parent_endpoint is None or config.parent_id_field is None:
+ raise ValueError(f"Cisco Duo {config.name}: fan-out endpoint is missing its parent configuration")
+
+ parent_config = CISCO_DUO_ENDPOINTS[config.parent_endpoint]
+ id_field = config.parent_id_field
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ parent_offset = resume.parent_offset if resume is not None and resume.parent_offset is not None else 0
+ pending_parent_id = resume.parent_id if resume is not None else None
+ pending_child_offset = resume.offset if resume is not None and resume.offset is not None else 0
+ if resume is not None:
+ logger.debug(
+ f"Cisco Duo: resuming {config.name} from parent_offset={parent_offset} "
+ f"{id_field}={pending_parent_id} offset={pending_child_offset}"
+ )
+
+ while True:
+ parent_params = {"limit": str(LIST_V1_PAGE_SIZE), "offset": str(parent_offset)}
+ parent_data = _fetch_json(
+ session,
+ hostname,
+ parent_config.path,
+ parent_params,
+ integration_key,
+ secret_key,
+ logger,
+ parent_config.sig_version,
+ )
+ parents = parent_data.get("response") or []
+ parent_metadata = parent_data.get("metadata") or {}
+
+ if pending_parent_id is not None:
+ ids = [str(parent.get(id_field) or "") for parent in parents]
+ if pending_parent_id in ids:
+ parents = parents[ids.index(pending_parent_id) :]
+ else:
+ # The checkpointed parent is gone, so every offset behind it in this page has
+ # shifted and there is no safe place to pick up mid-parent. Start the page over.
+ pending_child_offset = 0
+ pending_parent_id = None
+
+ for index, parent in enumerate(parents):
+ parent_id = parent.get(id_field)
+ if not parent_id:
+ continue
+
+ path = config.path.format(parent_id=quote(str(parent_id), safe=""))
+ child_offset = pending_child_offset
+ pending_child_offset = 0
+
+ while True:
+ child_params = {"limit": str(LIST_V1_PAGE_SIZE), "offset": str(child_offset)}
+ child_data = _fetch_json(
+ session, hostname, path, child_params, integration_key, secret_key, logger, config.sig_version
+ )
+ items = child_data.get("response") or []
+ child_metadata = child_data.get("metadata") or {}
+
+ if items:
+ for item in items:
+ item[id_field] = parent_id
+ yield _redact(items, config)
+
+ raw_next_offset = child_metadata.get("next_offset")
+ if raw_next_offset is None or raw_next_offset in ("", []):
+ break
+ child_offset = int(raw_next_offset)
+ resumable_source_manager.save_state(
+ CiscoDuoResumeConfig(parent_offset=parent_offset, parent_id=str(parent_id), offset=child_offset)
+ )
+
+ next_parent_id = _first_parent_id(parents[index + 1 :], id_field)
+ if next_parent_id is not None:
+ resumable_source_manager.save_state(
+ CiscoDuoResumeConfig(parent_offset=parent_offset, parent_id=next_parent_id, offset=0)
+ )
+
+ raw_next_parent_offset = parent_metadata.get("next_offset")
+ if raw_next_parent_offset is None or raw_next_parent_offset in ("", []):
+ break
+ parent_offset = int(raw_next_parent_offset)
+ resumable_source_manager.save_state(CiscoDuoResumeConfig(parent_offset=parent_offset))
+
+
def get_rows(
api_hostname: str,
integration_key: str,
@@ -426,6 +566,10 @@ def get_rows(
yield from _get_log_v1_rows(
session, hostname, integration_key, secret_key, config, logger, resumable_source_manager, last_value
)
+ elif config.api_style == "fanout_v1":
+ yield from _get_fanout_v1_rows(
+ session, hostname, integration_key, secret_key, config, logger, resumable_source_manager
+ )
else:
yield from _get_list_v1_rows(
session, hostname, integration_key, secret_key, config, logger, resumable_source_manager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/settings.py
index 75dec1ac52de..b4a8454b6b48 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Duo Admin API endpoints come in three shapes:
@@ -8,9 +10,16 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# wrapped response ({"response": {<data_key>: [...], "metadata": {...}}}).
# "log_v1" -> /admin/v1/logs/* : `mintime` (seconds) only, plain list response capped at
# 1000 records per call; paginate by advancing mintime.
-# "list_v1" -> /admin/v1/* resource lists: limit/offset pagination with an integer
-# `next_offset` in the top-level response metadata.
-ApiStyle = Literal["log_v2", "log_v1", "list_v1"]
+# "list_v1" -> /admin/v1/* and /admin/v2/* resource lists: limit/offset pagination with an
+# integer `next_offset` in the top-level response metadata.
+# "fanout_v1" -> a "list_v1" child list nested under a parent resource list, paged per
+# parent (e.g. the users of each group).
+ApiStyle = Literal["log_v2", "log_v1", "list_v1", "fanout_v1"]
+
+# Duo's legacy v2 request signing (HMAC-SHA1) is accepted by every /admin/v1 handler, but some
+# /admin/v2 handlers reject it and require v5 signing (HMAC-SHA512). v5 works on both, so it is
+# declared per endpoint rather than guessed at request time.
+SigVersion = Literal[2, 5]
def _integer_incremental_field(name: str) -> IncrementalField:
@@ -31,7 +40,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
-@dataclass
+@frozen
class CiscoDuoEndpointConfig:
name: str
path: str
@@ -51,6 +60,12 @@ class CiscoDuoEndpointConfig:
# Fields stripped from every row before it is yielded — used to keep credentials the API
# returns (e.g. an integration's secret_key) out of the warehouse table.
redact_fields: Optional[list[str]] = None
+ sig_version: SigVersion = 2
+ # "fanout_v1" only: the endpoint whose rows supply the parent id, and the field on those
+ # rows holding it. The id is substituted into `{parent_id}` in `path` and written onto
+ # every child row so the membership is queryable without a join back to the parent.
+ parent_endpoint: Optional[str] = None
+ parent_id_field: Optional[str] = None
description: Optional[str] = None
@@ -102,7 +117,7 @@ CISCO_DUO_ENDPOINTS: dict[str, CiscoDuoEndpointConfig] = {
partition_key="ts",
description=f"Only syncs the last {DEFAULT_LOOKBACK_DAYS} days on initial sync",
),
- # The v1 resource lists have no server-side time filter, so they are full-refresh only.
+ # The resource lists have no server-side time filter, so they are full-refresh only.
"users": CiscoDuoEndpointConfig(
name="users",
path="/admin/v1/users",
@@ -117,12 +132,30 @@ CISCO_DUO_ENDPOINTS: dict[str, CiscoDuoEndpointConfig] = {
api_style="list_v1",
primary_keys=["group_id"],
),
+ "group_users": CiscoDuoEndpointConfig(
+ name="group_users",
+ path="/admin/v2/groups/{parent_id}/users",
+ api_style="fanout_v1",
+ # A user object repeats across every group it belongs to, so the group is part of the key.
+ primary_keys=["group_id", "user_id"],
+ parent_endpoint="groups",
+ parent_id_field="group_id",
+ sig_version=5,
+ description="One row per user-to-group membership",
+ ),
"phones": CiscoDuoEndpointConfig(
name="phones",
path="/admin/v1/phones",
api_style="list_v1",
primary_keys=["phone_id"],
),
+ "endpoints": CiscoDuoEndpointConfig(
+ name="endpoints",
+ path="/admin/v1/endpoints",
+ api_style="list_v1",
+ primary_keys=["epkey"],
+ description="Duo purges an endpoint record after 30 days of inactivity",
+ ),
"admins": CiscoDuoEndpointConfig(
name="admins",
path="/admin/v1/admins",
@@ -138,6 +171,13 @@ CISCO_DUO_ENDPOINTS: dict[str, CiscoDuoEndpointConfig] = {
# project member who can read this table could otherwise sign requests as any integration.
redact_fields=["secret_key"],
),
+ "policies": CiscoDuoEndpointConfig(
+ name="policies",
+ path="/admin/v2/policies",
+ api_style="list_v1",
+ primary_keys=["policy_key"],
+ sig_version=5,
+ ),
}
ENDPOINTS = tuple(CISCO_DUO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/source.py
index a2ce9abdff74..4fb9b61281be 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/source.py
@@ -53,15 +53,15 @@ class CiscoDuoSource(ResumableSource[CiscoDuoSourceConfig, CiscoDuoResumeConfig]
label="Cisco Duo",
releaseStatus=ReleaseStatus.ALPHA,
keywords=["duo", "duo security", "mfa", "2fa"],
- caption="""Enter your Duo Admin API credentials to pull your Cisco Duo authentication, administrator, telephony, and activity logs — plus users, groups, phones, admins, and integrations — into the PostHog Data warehouse.
+ caption="""Enter your Duo Admin API credentials to pull your Cisco Duo authentication, administrator, telephony, and activity logs into the PostHog Data warehouse, along with users, groups, group memberships, phones, endpoints, admins, integrations, and policies.
In the [Duo Admin Panel](https://admin.duosecurity.com/), go to **Applications**, click **Protect an Application**, and protect the **Admin API** application. That gives you the integration key, secret key, and API hostname.
Grant the application the permissions matching the tables you want to sync:
-- **Grant read log** — authentication, administrator, telephony, and activity logs
-- **Grant read resource** — users, groups, phones
-- **Grant administrators** — admins
-- **Grant applications** — integrations
+- **Grant read log**: authentication, administrator, telephony, and activity logs
+- **Grant read resource**: users, groups, group memberships, phones, endpoints, policies
+- **Grant administrators**: admins
+- **Grant applications**: integrations
""",
iconPath="/static/services/cisco_duo.png",
docsUrl="https://posthog.com/docs/cdp/sources/cisco-duo",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo.py
index 033e9ed41be8..7ba5411ef0a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo.py
@@ -1,4 +1,6 @@
+import hmac
import base64
+import hashlib
from datetime import UTC, datetime
from typing import Any, Optional, cast
from urllib.parse import parse_qs, urlparse
@@ -55,9 +57,11 @@ class _FakeSession:
def __init__(self, responses: list[mock.MagicMock]) -> None:
self._responses = list(responses)
self.urls: list[str] = []
+ self.headers: list[dict[str, str]] = []
def get(self, url: str, **kwargs: Any) -> mock.MagicMock:
self.urls.append(url)
+ self.headers.append(kwargs.get("headers") or {})
return self._responses.pop(0)
@@ -72,6 +76,11 @@ def _query(url: str) -> dict[str, str]:
return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}
+def _signature(headers: dict[str, str]) -> str:
+ decoded = base64.b64decode(headers["Authorization"].removeprefix("Basic ")).decode()
+ return decoded.partition(":")[2]
+
+
@pytest.fixture(autouse=True)
def _safe_host():
with mock.patch(f"{MODULE}._is_host_safe", return_value=(True, None)):
@@ -144,6 +153,19 @@ class TestSigning:
assert len(signature) == 40
int(signature, 16) # HMAC-SHA1 hex digest
+ def test_v5_signature_appends_body_and_header_hashes(self):
+ # Some /admin/v2 handlers reject Duo's legacy v2 signing. v5 signs two extra canonical
+ # lines — the request body and the signed X-Duo-* headers — with SHA-512 instead of
+ # SHA-1. A GET carries neither, so both are the hash of the empty string.
+ date_str = "Tue, 21 Aug 2012 17:29:18 -0000"
+ empty = hashlib.sha512(b"").hexdigest()
+ canon = "\n".join([date_str, "GET", HOST, "/admin/v2/policies", "limit=100", empty, empty])
+ expected = hmac.new(SKEY.encode("utf-8"), canon.encode("utf-8"), hashlib.sha512).hexdigest()
+
+ headers = sign_request("GET", HOST, "/admin/v2/policies", {"limit": "100"}, IKEY, SKEY, date_str, 5)
+
+ assert _signature(headers) == expected
+
def test_signature_changes_with_params(self):
date_str = "Tue, 21 Aug 2012 17:29:18 -0000"
one = sign_request("GET", HOST, "/admin/v1/users", {"limit": "1"}, IKEY, SKEY, date_str)
@@ -375,6 +397,19 @@ class TestListV1Rows:
assert _query(session.urls[1])["offset"] == "100"
manager.save_state.assert_called_once_with(CiscoDuoResumeConfig(offset=100))
+ @pytest.mark.parametrize(
+ "endpoint, signature_length",
+ [("users", 40), ("endpoints", 40), ("policies", 128)],
+ )
+ def test_endpoint_signs_with_its_configured_version(self, endpoint: str, signature_length: int):
+ # A /admin/v2 handler can reject legacy v2 signing, so the endpoint's signing version has
+ # to reach the request instead of only sitting in settings.
+ session = _FakeSession([self._page([])])
+
+ _run(endpoint, session, _manager())
+
+ assert len(_signature(session.headers[0])) == signature_length
+
def test_resume_starts_from_saved_offset(self):
session = _FakeSession([self._page([{"user_id": "u3"}])])
@@ -414,6 +449,118 @@ class TestListV1Rows:
assert make_session.call_args.kwargs["capture"] is expected_capture
+class TestFanoutV1Rows:
+ def _page(self, items: list[dict], next_offset: Any = None) -> mock.MagicMock:
+ metadata = {"next_offset": next_offset} if next_offset is not None else {}
+ return _response(json_data={"stat": "OK", "response": items, "metadata": metadata})
+
+ def _group(self, group_id: str) -> dict:
+ return {"group_id": group_id, "name": group_id}
+
+ def test_fans_out_over_parents_and_stamps_the_parent_id(self):
+ session = _FakeSession(
+ [
+ self._page([self._group("DG1"), self._group("DG2")]),
+ self._page([{"user_id": "u1"}]),
+ self._page([{"user_id": "u2"}]),
+ ]
+ )
+
+ batches = _run("group_users", session, _manager())
+
+ # Without the parent id on the row the membership is unattributable and the composite
+ # primary key collapses to the user, dropping every group but one.
+ assert batches == [
+ [{"user_id": "u1", "group_id": "DG1"}],
+ [{"user_id": "u2", "group_id": "DG2"}],
+ ]
+ assert [urlparse(url).path for url in session.urls] == [
+ "/admin/v1/groups",
+ "/admin/v2/groups/DG1/users",
+ "/admin/v2/groups/DG2/users",
+ ]
+
+ def test_parent_and_child_sign_with_their_own_versions(self):
+ # The parent list is a v1 handler that takes legacy v2 signing; the child is a v2 handler
+ # that can reject it.
+ session = _FakeSession([self._page([self._group("DG1")]), self._page([])])
+
+ _run("group_users", session, _manager())
+
+ assert len(_signature(session.headers[0])) == 40
+ assert len(_signature(session.headers[1])) == 128
+
+ def test_checkpoints_the_next_child_page_then_the_next_parent(self):
+ session = _FakeSession(
+ [
+ self._page([self._group("DG1"), self._group("DG2")]),
+ self._page([{"user_id": "u1"}], next_offset=100),
+ self._page([{"user_id": "u2"}]),
+ self._page([{"user_id": "u3"}]),
+ ]
+ )
+ manager = _manager()
+
+ _run("group_users", session, manager)
+
+ assert _query(session.urls[1])["offset"] == "0"
+ assert _query(session.urls[2])["offset"] == "100"
+ # Each checkpoint names the work still to do. Naming the work just done would re-yield
+ # it on resume, and these tables are full-refresh, so the rows would duplicate.
+ assert manager.save_state.call_args_list == [
+ mock.call(CiscoDuoResumeConfig(parent_offset=0, parent_id="DG1", offset=100)),
+ mock.call(CiscoDuoResumeConfig(parent_offset=0, parent_id="DG2", offset=0)),
+ ]
+
+ def test_resume_skips_finished_parents_and_continues_mid_parent(self):
+ session = _FakeSession(
+ [
+ self._page([self._group("DG1"), self._group("DG2")]),
+ self._page([{"user_id": "u9"}]),
+ ]
+ )
+ resume = CiscoDuoResumeConfig(parent_offset=0, parent_id="DG2", offset=100)
+
+ batches = _run("group_users", session, _manager(resume))
+
+ assert batches == [[{"user_id": "u9", "group_id": "DG2"}]]
+ assert urlparse(session.urls[1]).path == "/admin/v2/groups/DG2/users"
+ assert _query(session.urls[1])["offset"] == "100"
+
+ def test_restarts_the_page_when_the_checkpointed_parent_is_gone(self):
+ # The group was deleted since the checkpoint, so every offset behind it has shifted and
+ # there is no safe place to pick up inside the page.
+ session = _FakeSession(
+ [
+ self._page([self._group("DG1")]),
+ self._page([{"user_id": "u1"}]),
+ ]
+ )
+ resume = CiscoDuoResumeConfig(parent_offset=0, parent_id="DGGONE", offset=100)
+
+ batches = _run("group_users", session, _manager(resume))
+
+ assert batches == [[{"user_id": "u1", "group_id": "DG1"}]]
+ assert _query(session.urls[1])["offset"] == "0"
+
+ def test_follows_the_parent_next_offset(self):
+ session = _FakeSession(
+ [
+ self._page([self._group("DG1")], next_offset=100),
+ self._page([{"user_id": "u1"}]),
+ self._page([self._group("DG2")]),
+ self._page([{"user_id": "u2"}]),
+ ]
+ )
+ manager = _manager()
+
+ _run("group_users", session, manager)
+
+ assert _query(session.urls[0])["offset"] == "0"
+ assert _query(session.urls[2])["offset"] == "100"
+ assert mock.call(CiscoDuoResumeConfig(parent_offset=100)) in manager.save_state.call_args_list
+
+
class TestValidateCredentials:
def _validate(self, response: mock.MagicMock, schema_name: str | None = None) -> tuple[bool, str | None]:
session = _FakeSession([response])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo_source.py
index 362e7597e7cc..706303de5ba8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo_source.py
@@ -36,9 +36,12 @@ class TestCiscoDuoSource:
("activity_logs", True, False),
("users", False, False),
("groups", False, False),
+ ("group_users", False, False),
("phones", False, False),
+ ("endpoints", False, False),
("admins", False, False),
("integrations", False, False),
+ ("policies", False, False),
],
)
def test_schema_sync_modes(self, endpoint, incremental, append):