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 cisco_duo import source (#71218)

Tom Owers88d6be4ff4dd
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 ff98b5b95e04..edca1f67c248 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -128,6 +128,7 @@ the row lists both.
| chartmogul | HTTP | requests | ✅ |
| circleci | HTTP | requests | ✅ |
| cimis | HTTP | requests | ✅ |
+| cisco_duo | HTTP | requests (hand-rolled HMAC-SHA1 request signing) | ✅ |
| cloudflare | HTTP | requests | ✅ |
| clari | HTTP | requests | ✅ |
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -601,7 +602,6 @@ doesn't conflict with concurrent PRs.
- chorus
- cin7
- circleci_insights
-- cisco_duo
- cisco_meraki
- clarifai
- clazar
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
new file mode 100644
index 000000000000..21038121829e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/canonical_descriptions.py
@@ -0,0 +1,128 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "authentication_logs": {
+ "description": "One record per authentication attempt (success or failure), including the user, factor, application, access device, and result.",
+ "docs_url": "https://duo.com/docs/adminapi#authentication-logs",
+ "columns": {
+ "txid": "Unique identifier of the authentication transaction.",
+ "timestamp": "Unix timestamp (seconds) of the event.",
+ "isotimestamp": "ISO 8601 timestamp of the event.",
+ "user": "The user who attempted to authenticate (name, key, groups).",
+ "application": "The application (integration) accessed (name, key).",
+ "auth_device": "The device used to approve or deny the authentication.",
+ "access_device": "Browser, OS, and location of the device the user authenticated from.",
+ "factor": "The authentication factor used, such as duo_push, sms_passcode, or phone_call.",
+ "reason": "Why the authentication succeeded or was denied, such as user_approved or deny_unenrolled_user.",
+ "result": "Outcome of the attempt: success, denied, error, or fraud.",
+ "event_type": "The type of event recorded: authentication or enrollment.",
+ "email": "Email address of the user, when known.",
+ "ood_software": "Out-of-date software detected on the access device, if any.",
+ },
+ },
+ "administrator_logs": {
+ "description": "Actions taken by administrators in the Duo Admin Panel, such as logins, user updates, and policy changes. Events have no unique id, so this table is append-only.",
+ "docs_url": "https://duo.com/docs/adminapi#administrator-logs",
+ "columns": {
+ "timestamp": "Unix timestamp (seconds) of the action.",
+ "isotimestamp": "ISO 8601 timestamp of the action.",
+ "username": "The full name of the administrator who performed the action, or 'API' for Admin API actions.",
+ "action": "The action performed, such as admin_login, user_update, or integration_create.",
+ "object": "The object the action was applied to, such as a username or integration name.",
+ "description": "JSON string describing the changed attributes.",
+ },
+ },
+ "telephony_logs": {
+ "description": "Phone call and SMS events sent by Duo, with the telephony credits each used.",
+ "docs_url": "https://duo.com/docs/adminapi#telephony-logs",
+ "columns": {
+ "telephony_id": "Unique identifier of the telephony event.",
+ "ts": "ISO 8601 timestamp of the event.",
+ "txid": "The authentication transaction that triggered the call or SMS, when applicable.",
+ "context": "How the call or SMS was used: authentication, enrollment, or verify.",
+ "credits": "Number of telephony credits the event used.",
+ "phone": "The phone number that received the call or SMS.",
+ "type": "The event type: phone or sms.",
+ },
+ },
+ "activity_logs": {
+ "description": "A unified stream of account activity events across users, devices, applications, and admin actions.",
+ "docs_url": "https://duo.com/docs/adminapi#activity-logs",
+ "columns": {
+ "activity_id": "Unique identifier of the activity event.",
+ "ts": "ISO 8601 timestamp of the event.",
+ "action": "The activity performed (name and details).",
+ "actor": "The user, admin, or system that performed the activity.",
+ "target": "The object the activity was performed on.",
+ "application": "The application involved in the activity, when applicable.",
+ "akey": "Identifier of the account the activity belongs to.",
+ },
+ },
+ "users": {
+ "description": "Users enrolled in Duo, with their status, contact details, associated phones, and group memberships.",
+ "docs_url": "https://duo.com/docs/adminapi#users",
+ "columns": {
+ "user_id": "Unique identifier of the user.",
+ "username": "The user's login name.",
+ "created": "Unix timestamp (seconds) when the user was created.",
+ "last_login": "Unix timestamp (seconds) of the user's most recent authentication, if any.",
+ "email": "The user's email address.",
+ "status": "Enrollment/access status: active, bypass, disabled, locked out, or pending deletion.",
+ "realname": "The user's real name.",
+ "is_enrolled": "Whether the user has enrolled an MFA device.",
+ "groups": "Groups the user belongs to.",
+ "phones": "Phones attached to the user.",
+ "notes": "Free-form notes about the user.",
+ },
+ },
+ "groups": {
+ "description": "Duo groups used to organize users and scope policies.",
+ "docs_url": "https://duo.com/docs/adminapi#groups",
+ "columns": {
+ "group_id": "Unique identifier of the group.",
+ "name": "The group's name.",
+ "desc": "The group's description.",
+ "status": "Authentication status applied to the group's users: active, bypass, or disabled.",
+ },
+ },
+ "phones": {
+ "description": "Phones and tablets registered with Duo, including platform, capabilities, and attached users.",
+ "docs_url": "https://duo.com/docs/adminapi#phones",
+ "columns": {
+ "phone_id": "Unique identifier of the phone.",
+ "number": "The phone number.",
+ "name": "Free-form label for the phone.",
+ "type": "The phone type: mobile, landline, or unknown.",
+ "platform": "The phone's platform, such as apple ios or google android.",
+ "activated": "Whether Duo Mobile has been activated on the phone.",
+ "capabilities": "Authentication methods the phone can use, such as push or sms.",
+ "last_seen": "ISO 8601 timestamp of the last contact from Duo Mobile on this phone.",
+ "users": "Users the phone is attached to.",
+ },
+ },
+ "admins": {
+ "description": "Administrators of the Duo account, with their role and status.",
+ "docs_url": "https://duo.com/docs/adminapi#administrators",
+ "columns": {
+ "admin_id": "Unique identifier of the administrator.",
+ "email": "The administrator's email address (their login).",
+ "name": "The administrator's name.",
+ "role": "The administrator's role, such as Owner or Read-only.",
+ "status": "The administrator's account status, such as Active or Disabled.",
+ "last_login": "Unix timestamp (seconds) of the administrator's most recent login, if any.",
+ },
+ },
+ "integrations": {
+ "description": "Applications (integrations) protected by Duo, one per integration key.",
+ "docs_url": "https://duo.com/docs/adminapi#integrations",
+ "columns": {
+ "integration_key": "Unique identifier (ikey) of the integration.",
+ "name": "The integration's name.",
+ "type": "The integration type, such as websdk, adminapi, or authapi.",
+ "greeting": "Voice greeting read at the start of authentication calls.",
+ "notes": "Free-form notes about the integration.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..530349eaa59c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/cisco_duo.py
@@ -0,0 +1,533 @@
+import re
+import hmac
+import base64
+import hashlib
+import dataclasses
+import email.utils
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote
+
+import requests
+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 products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.settings import (
+ CISCO_DUO_ENDPOINTS,
+ DEFAULT_LOOKBACK_DAYS,
+ CiscoDuoEndpointConfig,
+)
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 60
+
+# Duo caps the v2 log endpoints at 1000 records per request; the v1 log endpoints return a
+# fixed maximum of 1000 records with no limit param. The v1 resource lists default to 100.
+LOG_V2_PAGE_SIZE = 1000
+LOG_V1_PAGE_SIZE = 1000
+LIST_V1_PAGE_SIZE = 100
+
+# Duo Admin API hostnames are always vendor-issued (api-XXXXXXXX on one of these zones), so
+# anything else is a mistyped or hostile host — reject rather than send signed requests to it.
+ALLOWED_HOST_SUFFIXES = (".duosecurity.com", ".duofederal.com")
+
+HOST_NOT_ALLOWED_ERROR = "Cisco Duo API hostname is not allowed"
+
+
+class CiscoDuoRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class CiscoDuoHostNotAllowedError(Exception):
+ pass
+
+
+class CiscoDuoLogSaturationError(Exception):
+ """More events share a single second than the v1 log API can page through, so the sync
+ cannot advance without silently dropping audit records."""
+
+ pass
+
+
+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.
+ offset: int | None = None
+
+
+def normalize_hostname(hostname: str) -> str:
+ """Turn whatever the user typed into a bare Duo API host.
+
+ Accepts values like ``api-xxxxxxxx.duosecurity.com``, ``https://api-xxxxxxxx.duosecurity.com/``,
+ or ``api-xxxxxxxx.duosecurity.com/admin/v1`` and returns ``api-xxxxxxxx.duosecurity.com``.
+ """
+ hostname = hostname.strip()
+ hostname = re.sub(r"^https?://", "", hostname, flags=re.IGNORECASE)
+ hostname = hostname.split("/")[0]
+ return hostname.strip().rstrip(".").lower()
+
+
+def is_allowed_hostname(hostname: str) -> bool:
+ return bool(re.match(r"^[a-z0-9.\-]+$", hostname)) and hostname.endswith(ALLOWED_HOST_SUFFIXES)
+
+
+def _canonicalize_params(params: dict[str, str]) -> str:
+ """Sort and percent-encode params exactly as Duo's signature scheme requires (RFC 3986,
+ only unreserved characters left bare). The same string doubles as the request query string
+ so what we sign is byte-for-byte what we send."""
+ return "&".join(
+ f"{quote(str(key), safe='~')}={quote(str(value), safe='~')}" for key, value in sorted(params.items())
+ )
+
+
+def sign_request(
+ method: str, hostname: str, path: str, params: dict[str, str], integration_key: str, secret_key: str, date_str: str
+) -> 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.
+ """
+ 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()
+ basic = base64.b64encode(f"{integration_key}:{signature}".encode()).decode()
+ return {"Date": date_str, "Authorization": f"Basic {basic}", "Accept": "application/json"}
+
+
+def _build_url(hostname: str, path: str, params: dict[str, str]) -> str:
+ canon = _canonicalize_params(params)
+ return f"https://{hostname}{path}" + (f"?{canon}" if canon else "")
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ raw = response.headers.get("Retry-After")
+ if raw and raw.strip().isdigit():
+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Honor a server-provided Retry-After when present, else exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, CiscoDuoRetryableError) and exc.retry_after is not None:
+ return exc.retry_after
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+def _fetch_json_once(
+ session: requests.Session,
+ hostname: str,
+ path: str,
+ params: dict[str, str],
+ integration_key: str,
+ secret_key: str,
+ logger: FilteringBoundLogger,
+) -> 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())
+ url = _build_url(hostname, path, params)
+
+ # Don't follow redirects: the customer-controlled host could 3xx at an internal address,
+ # defeating the host validation done before the request (SSRF).
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None
+ raise CiscoDuoRetryableError(
+ f"Cisco Duo API error (retryable): status={response.status_code}, path={path}", retry_after=retry_after
+ )
+
+ if response.is_redirect or response.is_permanent_redirect:
+ raise CiscoDuoHostNotAllowedError(
+ f"Cisco Duo API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ if not response.ok:
+ logger.error(f"Cisco Duo API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+_fetch_json = retry(
+ retry=retry_if_exception_type((CiscoDuoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+)(_fetch_json_once)
+
+
+def _to_epoch_seconds(value: Any) -> int:
+ if isinstance(value, bool):
+ raise ValueError(f"Cannot interpret incremental value as a timestamp: {value!r}")
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, str) and value.strip():
+ stripped = value.strip()
+ if stripped.isdigit():
+ return int(stripped)
+ parsed = dateutil_parser.parse(stripped)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return int(parsed.timestamp())
+ raise ValueError(f"Cannot interpret incremental value as a timestamp: {value!r}")
+
+
+def _to_epoch_ms(value: Any) -> int:
+ # Second-precision inputs (the common case: a `timestamp` watermark) land on the start of
+ # their second, so the boundary second is re-pulled inclusively and merge dedupes it.
+ return _to_epoch_seconds(value) * 1000
+
+
+def _normalize_next_offset(raw: Any) -> str | None:
+ """Duo's v2 `metadata.next_offset` is opaque: a two-element list on the authentication log,
+ a string elsewhere. It is passed back verbatim as a comma-joined query param."""
+ if raw is None:
+ return None
+ if isinstance(raw, list):
+ return ",".join(str(part) for part in raw) if raw else None
+ text = str(raw)
+ return text or None
+
+
+def _now_ms() -> int:
+ return int(datetime.now(UTC).timestamp() * 1000)
+
+
+def _get_log_v2_rows(
+ session: requests.Session,
+ hostname: str,
+ integration_key: str,
+ secret_key: str,
+ config: CiscoDuoEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CiscoDuoResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page a v2 log endpoint over a fixed [mintime, maxtime] window with the opaque
+ next_offset cursor. The window is pinned at sync start (and preserved across resumes) so
+ pagination stays deterministic while new events keep arriving."""
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if resume is not None and resume.mintime is not None and resume.maxtime is not None:
+ mintime, maxtime, next_offset = resume.mintime, resume.maxtime, resume.next_offset
+ logger.debug(f"Cisco Duo: resuming {config.name} window=[{mintime}, {maxtime}] next_offset={next_offset}")
+ else:
+ maxtime = _now_ms()
+ if db_incremental_field_last_value is not None:
+ # mintime is inclusive (>=): the boundary rows are re-fetched and merge dedupes
+ # them on the primary key.
+ mintime = min(_to_epoch_ms(db_incremental_field_last_value), maxtime)
+ else:
+ mintime = maxtime - DEFAULT_LOOKBACK_DAYS * 24 * 60 * 60 * 1000
+ next_offset = None
+
+ while True:
+ params: dict[str, str] = {
+ "mintime": str(mintime),
+ "maxtime": str(maxtime),
+ "limit": str(LOG_V2_PAGE_SIZE),
+ "sort": "ts:asc",
+ }
+ if next_offset:
+ params["next_offset"] = next_offset
+
+ data = _fetch_json(session, hostname, config.path, params, integration_key, secret_key, logger)
+ wrapped = data.get("response") or {}
+ items = wrapped.get(config.data_key) or []
+ metadata = wrapped.get("metadata") or {}
+
+ if items:
+ yield items
+
+ next_offset = _normalize_next_offset(metadata.get("next_offset"))
+ if not next_offset:
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page instead of skipping it.
+ resumable_source_manager.save_state(
+ CiscoDuoResumeConfig(next_offset=next_offset, mintime=mintime, maxtime=maxtime)
+ )
+
+
+def _row_timestamp(item: dict[str, Any]) -> int:
+ try:
+ return int(item.get("timestamp") or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _get_log_v1_rows(
+ session: requests.Session,
+ hostname: str,
+ integration_key: str,
+ secret_key: str,
+ config: CiscoDuoEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CiscoDuoResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page the v1 administrator log by advancing `mintime` (seconds) past the last yielded row.
+
+ The endpoint returns up to 1000 records ascending with no other cursor, and rows carry no
+ unique id (the table is append-only), so boundary rows already yielded are dropped
+ client-side instead of being re-merged. On a full page the trailing rows that share the
+ final second are held back and re-fetched on the next page, so a page cut inside one second
+ cannot skip that second's remaining events.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ cursor: int | None
+ if resume is not None and resume.mintime is not None:
+ cursor = resume.mintime
+ logger.debug(f"Cisco Duo: resuming {config.name} from mintime={cursor}")
+ elif db_incremental_field_last_value is not None:
+ cursor = _to_epoch_seconds(db_incremental_field_last_value)
+ else:
+ cursor = None
+
+ while True:
+ params = {"mintime": str(cursor if cursor is not None else 0)}
+ data = _fetch_json(session, hostname, config.path, params, integration_key, secret_key, logger)
+ items = data.get("response") or []
+ full_page = len(items) >= LOG_V1_PAGE_SIZE
+
+ # Duo's docs are ambiguous on whether mintime is inclusive, so drop already-yielded
+ # boundary rows here — harmless if the server already excluded them.
+ fresh = [item for item in items if cursor is None or _row_timestamp(item) > cursor]
+
+ if not fresh:
+ if full_page:
+ # A full page with no rows past the cursor second means more than one page of
+ # events share that second. The v1 admin log can only page by mintime (seconds),
+ # so advancing would silently drop the remaining same-second audit records.
+ # Fail loudly instead — for an audit table, a missing record is worse than a
+ # stalled sync.
+ raise CiscoDuoLogSaturationError(
+ f"Cisco Duo {config.name}: more than {LOG_V1_PAGE_SIZE} events at timestamp {cursor}. "
+ f"The v1 log API cannot paginate within a single second, so the sync cannot advance "
+ f"without dropping audit records."
+ )
+ break
+
+ if full_page:
+ last_timestamp = _row_timestamp(fresh[-1])
+ kept = [item for item in fresh if _row_timestamp(item) < last_timestamp]
+ # If the whole fresh page shares one second there is nothing safe to hold back;
+ # yield it all. The next iteration re-fetches from that second and either finishes
+ # (fewer than a full page there) or raises the saturation error above.
+ to_yield = kept or fresh
+ else:
+ to_yield = fresh
+
+ yield to_yield
+ cursor = _row_timestamp(to_yield[-1])
+ resumable_source_manager.save_state(CiscoDuoResumeConfig(mintime=cursor))
+
+ if not full_page:
+ break
+
+
+def _get_list_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 v1 resource list with limit/offset, following the integer `next_offset` from the
+ top-level response metadata until it is absent."""
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume is not None and resume.offset is not None else 0
+ if offset:
+ logger.debug(f"Cisco Duo: resuming {config.name} from offset={offset}")
+
+ 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)
+ 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
+
+ raw_next_offset = metadata.get("next_offset")
+ if raw_next_offset is None or raw_next_offset in ("", []):
+ break
+ offset = int(raw_next_offset)
+ resumable_source_manager.save_state(CiscoDuoResumeConfig(offset=offset))
+
+
+def get_rows(
+ api_hostname: str,
+ integration_key: str,
+ secret_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CiscoDuoResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = CISCO_DUO_ENDPOINTS[endpoint]
+ hostname = normalize_hostname(api_hostname)
+
+ if not is_allowed_hostname(hostname):
+ raise CiscoDuoHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)
+
+ # Re-check at run time (not just at source-create) in case the hostname was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ raise CiscoDuoHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ last_value = db_incremental_field_last_value if should_use_incremental_field else None
+
+ # One session reused across every page so urllib3 keeps the connection alive instead of
+ # re-handshaking per request. HTTP sample capture records the raw response before
+ # redact_fields is applied, so disable it for endpoints whose responses carry secrets the
+ # name-based sample scrubbers can't recognise (e.g. an integration's secret_key).
+ session = make_tracked_session(capture=not bool(config.redact_fields))
+
+ if config.api_style == "log_v2":
+ yield from _get_log_v2_rows(
+ session, hostname, integration_key, secret_key, config, logger, resumable_source_manager, last_value
+ )
+ elif config.api_style == "log_v1":
+ yield from _get_log_v1_rows(
+ session, hostname, integration_key, secret_key, config, logger, resumable_source_manager, last_value
+ )
+ else:
+ yield from _get_list_v1_rows(
+ session, hostname, integration_key, secret_key, config, logger, resumable_source_manager
+ )
+
+
+def validate_credentials(
+ api_hostname: str,
+ integration_key: str,
+ secret_key: str,
+ schema_name: Optional[str] = None,
+ team_id: Optional[int] = None,
+) -> tuple[bool, str | None]:
+ """Probe a cheap signed request to confirm the integration + secret key pair is genuine.
+
+ At source-create (``schema_name is None``) a 403 is accepted: Duo Admin API permissions are
+ granular (read information / read log / read resource), so a valid key pair may lack the
+ permission for this particular probe. A scoped probe (``schema_name`` set) treats 403 as a
+ hard failure.
+ """
+ hostname = normalize_hostname(api_hostname)
+ if not hostname or not is_allowed_hostname(hostname):
+ return False, "Invalid Cisco Duo API hostname — it should look like api-XXXXXXXX.duosecurity.com"
+
+ # The hostname is customer-controlled, so block hosts that resolve to private/internal
+ # addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ path = "/admin/v1/users"
+ params = {"limit": "1"}
+ headers = sign_request("GET", hostname, path, params, integration_key, secret_key, email.utils.formatdate())
+ try:
+ # Don't follow redirects: the validated host could 3xx at an internal address,
+ # defeating the host check above (SSRF).
+ response = make_tracked_session().get(
+ _build_url(hostname, path, params), headers=headers, timeout=10, allow_redirects=False
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, (
+ "Invalid Cisco Duo credentials. Check the integration key, secret key, and API hostname "
+ "of your Admin API application — a large clock skew can also cause this."
+ )
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid key pair, missing permission for this probe — let source creation through.
+ return True, None
+ return False, "Your Duo Admin API application lacks the required permission for this endpoint"
+
+ try:
+ body = response.json()
+ return False, str(body.get("message", response.text))
+ except Exception:
+ return False, response.text
+
+
+def cisco_duo_source(
+ api_hostname: str,
+ integration_key: str,
+ secret_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CiscoDuoResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = CISCO_DUO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_hostname=api_hostname,
+ integration_key=integration_key,
+ secret_key=secret_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # The v2 log endpoints are requested with sort=ts:asc and the v1 admin log returns
+ # ascending from mintime. The resource lists aren't time-ordered, but they are
+ # full-refresh only so no watermark depends on their ordering.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format=endpoint_config.partition_format if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
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
new file mode 100644
index 000000000000..75dec1ac52de
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/settings.py
@@ -0,0 +1,147 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Duo Admin API endpoints come in three shapes:
+# "log_v2" -> /admin/v2/logs/* : mintime/maxtime window (ms) + opaque `next_offset` cursor,
+# 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"]
+
+
+def _integer_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.Integer,
+ "field": name,
+ "field_type": IncrementalFieldType.Integer,
+ }
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class CiscoDuoEndpointConfig:
+ name: str
+ path: str
+ api_style: ApiStyle
+ # None for administrator_logs: the v1 admin log has no unique event id, so it is
+ # append-only and never merged.
+ primary_keys: Optional[list[str]] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # The timestamp field on returned rows that maps to the mintime/maxtime request params.
+ # "timestamp" is unix seconds (int); "ts" is an ISO-8601 string.
+ timestamp_field: Optional[str] = None
+ # Key holding the row list inside the v2 wrapped response ("authlogs" or "items").
+ data_key: Optional[str] = None
+ # Stable, immutable field to partition by (log timestamps and `created` never mutate).
+ partition_key: Optional[str] = None
+ partition_format: Literal["month", "week", "day", "hour"] = "week"
+ # 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
+ description: Optional[str] = None
+
+
+# First-sync window for the v2 log endpoints: Duo rejects a mintime older than its
+# retention horizon (about 180 days on most editions), so reach back exactly that far.
+DEFAULT_LOOKBACK_DAYS = 180
+
+CISCO_DUO_ENDPOINTS: dict[str, CiscoDuoEndpointConfig] = {
+ "authentication_logs": CiscoDuoEndpointConfig(
+ name="authentication_logs",
+ path="/admin/v2/logs/authentication",
+ api_style="log_v2",
+ primary_keys=["txid"],
+ incremental_fields=[_integer_incremental_field("timestamp")],
+ timestamp_field="timestamp",
+ data_key="authlogs",
+ partition_key="timestamp",
+ description=f"Only syncs the last {DEFAULT_LOOKBACK_DAYS} days on initial sync",
+ ),
+ "administrator_logs": CiscoDuoEndpointConfig(
+ name="administrator_logs",
+ path="/admin/v1/logs/administrator",
+ api_style="log_v1",
+ primary_keys=None,
+ incremental_fields=[_integer_incremental_field("timestamp")],
+ timestamp_field="timestamp",
+ partition_key="timestamp",
+ description="Administrator log events have no unique id, so this table is append-only",
+ ),
+ "telephony_logs": CiscoDuoEndpointConfig(
+ name="telephony_logs",
+ path="/admin/v2/logs/telephony",
+ api_style="log_v2",
+ primary_keys=["telephony_id"],
+ incremental_fields=[_datetime_incremental_field("ts")],
+ timestamp_field="ts",
+ data_key="items",
+ partition_key="ts",
+ description=f"Only syncs the last {DEFAULT_LOOKBACK_DAYS} days on initial sync",
+ ),
+ "activity_logs": CiscoDuoEndpointConfig(
+ name="activity_logs",
+ path="/admin/v2/logs/activity",
+ api_style="log_v2",
+ primary_keys=["activity_id"],
+ incremental_fields=[_datetime_incremental_field("ts")],
+ timestamp_field="ts",
+ data_key="items",
+ 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.
+ "users": CiscoDuoEndpointConfig(
+ name="users",
+ path="/admin/v1/users",
+ api_style="list_v1",
+ primary_keys=["user_id"],
+ partition_key="created",
+ partition_format="month",
+ ),
+ "groups": CiscoDuoEndpointConfig(
+ name="groups",
+ path="/admin/v1/groups",
+ api_style="list_v1",
+ primary_keys=["group_id"],
+ ),
+ "phones": CiscoDuoEndpointConfig(
+ name="phones",
+ path="/admin/v1/phones",
+ api_style="list_v1",
+ primary_keys=["phone_id"],
+ ),
+ "admins": CiscoDuoEndpointConfig(
+ name="admins",
+ path="/admin/v1/admins",
+ api_style="list_v1",
+ primary_keys=["admin_id"],
+ ),
+ "integrations": CiscoDuoEndpointConfig(
+ name="integrations",
+ path="/admin/v1/integrations",
+ api_style="list_v1",
+ primary_keys=["integration_key"],
+ # The integrations list returns each integration's secret_key; never persist it — a
+ # project member who can read this table could otherwise sign requests as any integration.
+ redact_fields=["secret_key"],
+ ),
+}
+
+ENDPOINTS = tuple(CISCO_DUO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CISCO_DUO_ENDPOINTS.items()
+}
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 6eb3f5a48f20..f9b4644cd3e7 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
@@ -1,30 +1,184 @@
-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.cisco_duo.cisco_duo import (
+ HOST_NOT_ALLOWED_ERROR,
+ CiscoDuoResumeConfig,
+ cisco_duo_source,
+ validate_credentials as validate_cisco_duo_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.settings import (
+ CISCO_DUO_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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 CiscoDuoSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CiscoDuoSource(SimpleSource[CiscoDuoSourceConfig]):
+class CiscoDuoSource(ResumableSource[CiscoDuoSourceConfig, CiscoDuoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CISCODUO
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `api_hostname` is where the stored secret key is sent; retargeting it must re-require the keys.
+ return ["api_hostname"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CISCO_DUO,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Cisco Duo (Duo Security)",
+ 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.
+
+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
+""",
iconPath="/static/services/cisco_duo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/cisco-duo",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_hostname",
+ label="API hostname",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="api-XXXXXXXX.duosecurity.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="integration_key",
+ label="Integration key",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="DIXXXXXXXXXXXXXXXXXX",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="secret_key",
+ label="Secret key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": (
+ "Invalid Cisco Duo credentials. Check the integration key, secret key, and API hostname "
+ "of your Admin API application, then reconnect."
+ ),
+ "403 Client Error": (
+ "Your Duo Admin API application lacks the permission needed to sync this data. Grant the "
+ "required permission (read log, read resource, administrators, or applications) in the "
+ "Duo Admin Panel and try again."
+ ),
+ HOST_NOT_ALLOWED_ERROR: (
+ "The Cisco Duo API hostname is not allowed. Use the API hostname shown on your Admin API "
+ "application, e.g. api-XXXXXXXX.duosecurity.com."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: CiscoDuoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The v1 administrator log has no unique event id, so it can only be appended, never
+ # merged. The v2 logs re-pull the boundary second inclusively on each incremental run,
+ # so only merge (which dedupes on the primary key) is safe for them.
+ append_only_endpoints = {"administrator_logs"}
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ is_append_only = endpoint in append_only_endpoints
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental and not is_append_only,
+ supports_append=has_incremental and is_append_only,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=CISCO_DUO_ENDPOINTS[endpoint].description,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: CiscoDuoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_cisco_duo_credentials(
+ config.api_hostname, config.integration_key, config.secret_key, schema_name, team_id
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CiscoDuoResumeConfig]:
+ return ResumableSourceManager[CiscoDuoResumeConfig](inputs, CiscoDuoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CiscoDuoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CiscoDuoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return cisco_duo_source(
+ api_hostname=config.api_hostname,
+ integration_key=config.integration_key,
+ secret_key=config.secret_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ 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/cisco_duo/tests/test_cisco_duo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo.py
new file mode 100644
index 000000000000..033e9ed41be8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo.py
@@ -0,0 +1,470 @@
+import base64
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.cisco_duo import (
+ CiscoDuoHostNotAllowedError,
+ CiscoDuoLogSaturationError,
+ CiscoDuoResumeConfig,
+ CiscoDuoRetryableError,
+ _canonicalize_params,
+ _fetch_json_once,
+ _normalize_next_offset,
+ _to_epoch_ms,
+ _to_epoch_seconds,
+ cisco_duo_source,
+ get_rows,
+ is_allowed_hostname,
+ normalize_hostname,
+ sign_request,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.settings import CISCO_DUO_ENDPOINTS
+
+HOST = "api-xxxxxxxx.duosecurity.com"
+IKEY = "DIWJ8X6AEYOR5OMC6TQ1"
+SKEY = "Zh5eGmUq9zpfQnyUIu5OL9iWoMMv5ZNmk3zLJ4Ep"
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.cisco_duo"
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, headers: Optional[dict] = None) -> mock.MagicMock:
+ response = mock.MagicMock(spec=requests.Response)
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = ""
+ response.json.return_value = json_data
+ response.headers = headers or {}
+ if status_code >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=response)
+ return response
+
+
+class _FakeSession:
+ """Returns canned responses in order and records every requested URL."""
+
+ def __init__(self, responses: list[mock.MagicMock]) -> None:
+ self._responses = list(responses)
+ self.urls: list[str] = []
+
+ def get(self, url: str, **kwargs: Any) -> mock.MagicMock:
+ self.urls.append(url)
+ return self._responses.pop(0)
+
+
+def _manager(resume: CiscoDuoResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _query(url: str) -> dict[str, str]:
+ return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}
+
+
[email protected](autouse=True)
+def _safe_host():
+ with mock.patch(f"{MODULE}._is_host_safe", return_value=(True, None)):
+ yield
+
+
+def _run(endpoint: str, session: _FakeSession, manager: mock.MagicMock, **kwargs: Any) -> list[list[dict]]:
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ return list(
+ get_rows(
+ api_hostname=kwargs.pop("api_hostname", HOST),
+ integration_key=IKEY,
+ secret_key=SKEY,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ **kwargs,
+ )
+ )
+
+
+class TestHostnameValidation:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("api-xxxxxxxx.duosecurity.com", "api-xxxxxxxx.duosecurity.com"),
+ ("https://api-xxxxxxxx.duosecurity.com/", "api-xxxxxxxx.duosecurity.com"),
+ ("API-XXXXXXXX.DUOSECURITY.COM", "api-xxxxxxxx.duosecurity.com"),
+ (" api-xxxxxxxx.duosecurity.com/admin/v1 ", "api-xxxxxxxx.duosecurity.com"),
+ ],
+ )
+ def test_normalize_hostname(self, raw, expected):
+ assert normalize_hostname(raw) == expected
+
+ @pytest.mark.parametrize(
+ "hostname, allowed",
+ [
+ ("api-xxxxxxxx.duosecurity.com", True),
+ ("api-xxxxxxxx.duofederal.com", True),
+ ("api-xxxxxxxx.evil.com", False),
+ ("duosecurity.com.evil.com", False),
+ ("[email protected]", False),
+ ("", False),
+ ],
+ )
+ def test_is_allowed_hostname(self, hostname, allowed):
+ assert is_allowed_hostname(hostname) is allowed
+
+ def test_get_rows_rejects_disallowed_hostname(self):
+ with pytest.raises(CiscoDuoHostNotAllowedError):
+ _run("users", _FakeSession([]), _manager(), api_hostname="api.evil.com")
+
+
+class TestSigning:
+ def test_canonicalize_sorts_and_percent_encodes(self):
+ # Duo signs the RFC 3986-encoded, key-sorted param string; urlencode's default
+ # '+'-for-space or unsorted params would produce an invalid signature.
+ canon = _canonicalize_params({"realname": "First Last", "username": "root", "limit": "10/20"})
+ assert canon == "limit=10%2F20&realname=First%20Last&username=root"
+
+ def test_sign_request_builds_basic_auth_over_canonical_string(self):
+ date_str = "Tue, 21 Aug 2012 17:29:18 -0000"
+ headers = sign_request("GET", HOST, "/admin/v1/users", {"limit": "1"}, IKEY, SKEY, date_str)
+
+ assert headers["Date"] == date_str
+ decoded = base64.b64decode(headers["Authorization"].removeprefix("Basic ")).decode()
+ username, _, signature = decoded.partition(":")
+ assert username == IKEY
+ assert len(signature) == 40
+ int(signature, 16) # HMAC-SHA1 hex digest
+
+ 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)
+ two = sign_request("GET", HOST, "/admin/v1/users", {"limit": "2"}, IKEY, SKEY, date_str)
+ assert one["Authorization"] != two["Authorization"]
+
+
+class TestFetchJson:
+ def _fetch_once(self, response: mock.MagicMock) -> dict[str, Any]:
+ session = cast(requests.Session, _FakeSession([response]))
+ return _fetch_json_once(session, HOST, "/admin/v1/users", {}, IKEY, SKEY, mock.MagicMock())
+
+ def test_429_raises_retryable_with_retry_after(self):
+ with pytest.raises(CiscoDuoRetryableError) as exc:
+ self._fetch_once(_response(status_code=429, headers={"Retry-After": "7"}))
+ assert exc.value.retry_after == 7.0
+
+ @pytest.mark.parametrize("status_code", [500, 502, 503])
+ def test_5xx_raises_retryable(self, status_code):
+ with pytest.raises(CiscoDuoRetryableError):
+ self._fetch_once(_response(status_code=status_code))
+
+ @pytest.mark.parametrize("status_code", [401, 403])
+ def test_4xx_raises_http_error(self, status_code):
+ with pytest.raises(requests.HTTPError):
+ self._fetch_once(_response(status_code=status_code))
+
+ def test_redirect_is_rejected_not_followed(self):
+ with pytest.raises(CiscoDuoHostNotAllowedError):
+ self._fetch_once(_response(status_code=302))
+
+
+class TestIncrementalValueConversion:
+ @pytest.mark.parametrize(
+ "value, expected_seconds",
+ [
+ (1700000000, 1700000000),
+ (1700000000.9, 1700000000),
+ ("1700000000", 1700000000),
+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),
+ ("2023-11-14T22:13:20Z", 1700000000),
+ ],
+ )
+ def test_to_epoch(self, value, expected_seconds):
+ assert _to_epoch_seconds(value) == expected_seconds
+ assert _to_epoch_ms(value) == expected_seconds * 1000
+
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ (None, None),
+ ("", None),
+ ([], None),
+ ("abc123", "abc123"),
+ (["1532951895000", "af0ba235"], "1532951895000,af0ba235"),
+ ],
+ )
+ def test_normalize_next_offset(self, raw, expected):
+ assert _normalize_next_offset(raw) == expected
+
+
+class TestLogV2Rows:
+ def _page(self, items: list[dict], next_offset: Any = None) -> mock.MagicMock:
+ return _response(
+ json_data={
+ "stat": "OK",
+ "response": {"authlogs": items, "metadata": {"next_offset": next_offset} if next_offset else {}},
+ }
+ )
+
+ def test_paginates_with_fixed_window_and_saves_state_after_yield(self):
+ first = [{"txid": "a", "timestamp": 1700000001}]
+ second = [{"txid": "b", "timestamp": 1700000002}]
+ session = _FakeSession([self._page(first, next_offset=["1700000001000", "a"]), self._page(second)])
+ manager = _manager()
+
+ batches = _run(
+ "authentication_logs",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ )
+
+ assert batches == [first, second]
+
+ first_params = _query(session.urls[0])
+ assert first_params["mintime"] == "1700000000000"
+ assert first_params["sort"] == "ts:asc"
+ assert first_params["limit"] == "1000"
+ assert "next_offset" not in first_params
+
+ second_params = _query(session.urls[1])
+ assert second_params["next_offset"] == "1700000001000,a"
+ # The window must stay pinned across pages, or pagination is non-deterministic.
+ assert second_params["mintime"] == first_params["mintime"]
+ assert second_params["maxtime"] == first_params["maxtime"]
+
+ manager.save_state.assert_called_once_with(
+ CiscoDuoResumeConfig(
+ next_offset="1700000001000,a", mintime=1700000000000, maxtime=int(first_params["maxtime"])
+ )
+ )
+
+ def test_first_sync_uses_lookback_window(self):
+ session = _FakeSession([self._page([])])
+ _run("authentication_logs", session, _manager())
+
+ params = _query(session.urls[0])
+ window_days = (int(params["maxtime"]) - int(params["mintime"])) / (24 * 60 * 60 * 1000)
+ assert window_days == 180
+
+ def test_resume_restores_window_and_cursor(self):
+ session = _FakeSession([self._page([{"txid": "c", "timestamp": 3}])])
+ resume = CiscoDuoResumeConfig(next_offset="cursor123", mintime=1000, maxtime=2000)
+
+ batches = _run("authentication_logs", session, _manager(resume))
+
+ assert len(batches) == 1
+ params = _query(session.urls[0])
+ assert params == {
+ "mintime": "1000",
+ "maxtime": "2000",
+ "limit": "1000",
+ "sort": "ts:asc",
+ "next_offset": "cursor123",
+ }
+
+ def test_future_watermark_clamped_to_window_end(self):
+ session = _FakeSession([self._page([])])
+ _run(
+ "authentication_logs",
+ session,
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=99999999999, # far future
+ )
+ params = _query(session.urls[0])
+ assert int(params["mintime"]) <= int(params["maxtime"])
+
+ def test_telephony_uses_items_data_key_and_iso_watermark(self):
+ items = [{"telephony_id": "t1", "ts": "2024-01-01T00:00:05+00:00"}]
+ session = _FakeSession([_response(json_data={"stat": "OK", "response": {"items": items, "metadata": {}}})])
+
+ batches = _run(
+ "telephony_logs",
+ session,
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00+00:00",
+ )
+
+ assert batches == [items]
+ assert _query(session.urls[0])["mintime"] == str(1704067200 * 1000)
+
+
+class TestLogV1Rows:
+ def _page(self, items: list[dict]) -> mock.MagicMock:
+ return _response(json_data={"stat": "OK", "response": items})
+
+ def test_advances_mintime_and_stops_on_short_page(self):
+ with mock.patch(f"{MODULE}.LOG_V1_PAGE_SIZE", 3):
+ page_one = [{"timestamp": ts, "action": "a"} for ts in (1, 2, 3)]
+ page_two = [{"timestamp": 4, "action": "b"}]
+ session = _FakeSession([self._page(page_one), self._page(page_two)])
+ manager = _manager()
+
+ batches = _run("administrator_logs", session, manager)
+
+ # Page one is full, so its trailing row (timestamp 3) is held back and re-fetched.
+ assert batches == [[{"timestamp": 1, "action": "a"}, {"timestamp": 2, "action": "a"}], page_two]
+ assert _query(session.urls[0])["mintime"] == "0"
+ assert _query(session.urls[1])["mintime"] == "2"
+ manager.save_state.assert_any_call(CiscoDuoResumeConfig(mintime=2))
+
+ def test_watermark_rows_are_dropped_client_side(self):
+ # Duo's docs are ambiguous on mintime inclusivity; boundary rows already synced in
+ # append mode must not be yielded again or they'd be duplicated.
+ items = [{"timestamp": 100}, {"timestamp": 101}]
+ session = _FakeSession([self._page(items)])
+
+ batches = _run(
+ "administrator_logs",
+ session,
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=100,
+ )
+
+ assert batches == [[{"timestamp": 101}]]
+ assert _query(session.urls[0])["mintime"] == "100"
+
+ def test_saturated_second_raises_instead_of_dropping_records(self):
+ # A full page whose rows all share one second means more events exist at that second
+ # than one page can return. Because the v1 log API only pages by mintime (seconds),
+ # advancing would silently drop the remaining same-second audit records — so the sync
+ # must fail loudly rather than skip them.
+ with mock.patch(f"{MODULE}.LOG_V1_PAGE_SIZE", 2):
+ same_second = [{"timestamp": 7, "object": "x"}, {"timestamp": 7, "object": "y"}]
+ session = _FakeSession([self._page(same_second), self._page(same_second)])
+
+ with pytest.raises(CiscoDuoLogSaturationError):
+ _run("administrator_logs", session, _manager())
+
+ def test_resume_starts_from_saved_mintime(self):
+ session = _FakeSession([self._page([{"timestamp": 51}])])
+
+ batches = _run("administrator_logs", session, _manager(CiscoDuoResumeConfig(mintime=50)))
+
+ assert batches == [[{"timestamp": 51}]]
+ assert _query(session.urls[0])["mintime"] == "50"
+
+
+class TestListV1Rows:
+ 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 test_follows_next_offset_until_absent(self):
+ first = [{"user_id": "u1"}]
+ second = [{"user_id": "u2"}]
+ session = _FakeSession([self._page(first, next_offset=100), self._page(second)])
+ manager = _manager()
+
+ batches = _run("users", session, manager)
+
+ assert batches == [first, second]
+ assert _query(session.urls[0])["offset"] == "0"
+ assert _query(session.urls[1])["offset"] == "100"
+ manager.save_state.assert_called_once_with(CiscoDuoResumeConfig(offset=100))
+
+ def test_resume_starts_from_saved_offset(self):
+ session = _FakeSession([self._page([{"user_id": "u3"}])])
+
+ _run("users", session, _manager(CiscoDuoResumeConfig(offset=200)))
+
+ assert _query(session.urls[0])["offset"] == "200"
+
+ def test_integrations_secret_key_is_redacted(self):
+ # The integrations endpoint returns each integration's secret_key; persisting it would
+ # leak Duo application secrets into the warehouse table, so it must be stripped.
+ session = _FakeSession(
+ [self._page([{"integration_key": "DI123", "name": "web sdk", "secret_key": "supersecret"}])]
+ )
+
+ batches = _run("integrations", session, _manager())
+
+ assert batches == [[{"integration_key": "DI123", "name": "web sdk"}]]
+
+ @parameterized.expand([("integrations", False), ("users", True)])
+ def test_http_capture_disabled_when_response_needs_redaction(self, endpoint: str, expected_capture: bool):
+ # Sample capture records the raw response before redaction, so it must be off for
+ # endpoints whose responses carry secrets (integrations), and left on otherwise.
+ session = _FakeSession([self._page([])])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:
+ list(
+ get_rows(
+ api_hostname=HOST,
+ integration_key=IKEY,
+ secret_key=SKEY,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ team_id=1,
+ )
+ )
+
+ assert make_session.call_args.kwargs["capture"] is expected_capture
+
+
+class TestValidateCredentials:
+ def _validate(self, response: mock.MagicMock, schema_name: str | None = None) -> tuple[bool, str | None]:
+ session = _FakeSession([response])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ return validate_credentials(HOST, IKEY, SKEY, schema_name=schema_name, team_id=1)
+
+ def test_200_is_valid(self):
+ assert self._validate(_response(json_data={"stat": "OK", "response": []})) == (True, None)
+
+ def test_401_is_invalid(self):
+ ok, message = self._validate(_response(status_code=401))
+ assert ok is False
+ assert "Invalid Cisco Duo credentials" in (message or "")
+
+ def test_403_accepted_at_source_create(self):
+ # Duo Admin API permissions are granular; a log-only key must still connect.
+ assert self._validate(_response(status_code=403)) == (True, None)
+
+ def test_403_fails_for_scoped_probe(self):
+ ok, _ = self._validate(_response(status_code=403), schema_name="users")
+ assert ok is False
+
+ def test_redirect_fails(self):
+ ok, _ = self._validate(_response(status_code=302))
+ assert ok is False
+
+ def test_disallowed_hostname_fails_without_request(self):
+ ok, message = validate_credentials("api.evil.com", IKEY, SKEY, team_id=1)
+ assert ok is False
+ assert "hostname" in (message or "")
+
+
+class TestCiscoDuoSource:
+ @pytest.mark.parametrize("endpoint", list(CISCO_DUO_ENDPOINTS.keys()))
+ def test_source_response_shape(self, endpoint):
+ config = CISCO_DUO_ENDPOINTS[endpoint]
+ response = cisco_duo_source(
+ api_hostname=HOST,
+ integration_key=IKEY,
+ secret_key=SKEY,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ team_id=1,
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
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
new file mode 100644
index 000000000000..76f6981eaf03
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_duo/tests/test_cisco_duo_source.py
@@ -0,0 +1,139 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.cisco_duo import CiscoDuoResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.source import CiscoDuoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CiscoDuoSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCiscoDuoSource:
+ def setup_method(self):
+ self.source = CiscoDuoSource()
+ self.team_id = 123
+ self.config = CiscoDuoSourceConfig(
+ api_hostname="api-xxxxxxxx.duosecurity.com",
+ integration_key="DIWJ8X6AEYOR5OMC6TQ1",
+ secret_key="secret",
+ )
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.CISCODUO
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "CiscoDuo"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/cisco_duo.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_hostname", "integration_key", "secret_key"]
+
+ hostname_field, ikey_field, skey_field = config.fields
+ assert isinstance(hostname_field, SourceFieldInputConfig)
+ assert hostname_field.secret is False
+
+ assert isinstance(ikey_field, SourceFieldInputConfig)
+ assert ikey_field.secret is False
+
+ assert isinstance(skey_field, SourceFieldInputConfig)
+ assert skey_field.type == SourceFieldInputConfigType.PASSWORD
+ assert skey_field.secret is True
+ assert skey_field.required is True
+
+ def test_connection_host_fields_covers_api_hostname(self):
+ # Retargeting api_hostname must re-require the secret key, or a member could point
+ # the stored credential at a host they control.
+ assert self.source.connection_host_fields == ["api_hostname"]
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, incremental, append",
+ [
+ ("authentication_logs", True, False),
+ # No unique event id: merging would multi-match, so the admin log is append-only.
+ ("administrator_logs", False, True),
+ ("telephony_logs", True, False),
+ ("activity_logs", True, False),
+ ("users", False, False),
+ ("groups", False, False),
+ ("phones", False, False),
+ ("admins", False, False),
+ ("integrations", False, False),
+ ],
+ )
+ def test_schema_sync_modes(self, endpoint, incremental, append):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[endpoint].supports_incremental is incremental
+ assert schemas[endpoint].supports_append is append
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users", "nope"])
+ assert [s.name for s in schemas] == ["users"]
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [(True, None), (False, "Invalid Cisco Duo credentials")],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.source.validate_cisco_duo_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="users")
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with(
+ self.config.api_hostname, self.config.integration_key, self.config.secret_key, "users", self.team_id
+ )
+
+ def test_get_resumable_source_manager(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CiscoDuoResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.source.cisco_duo_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_cisco_duo_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "authentication_logs"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_cisco_duo_source.call_args.kwargs
+ assert kwargs["api_hostname"] == "api-xxxxxxxx.duosecurity.com"
+ assert kwargs["integration_key"] == "DIWJ8X6AEYOR5OMC6TQ1"
+ assert kwargs["secret_key"] == "secret"
+ assert kwargs["endpoint"] == "authentication_logs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cisco_duo.source.cisco_duo_source")
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_cisco_duo_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_cisco_duo_source.call_args.kwargs["db_incremental_field_last_value"] is None
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 cd1fa6153b3f..9c495712fc8c 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
@@ -817,7 +817,9 @@ class CircleciInsightsSourceConfig(config.Config):
@config.config
class CiscoDuoSourceConfig(config.Config):
- pass
+ api_hostname: str
+ integration_key: str
+ secret_key: str
@config.config