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): add Omni Analytics source (#73200)

Tom Owersb32a3acf52d2
diff --git a/frontend/public/services/omni.png b/frontend/public/services/omni.png
index c6b5319ad3a3..81560d07a167 100644
Binary files a/frontend/public/services/omni.png and b/frontend/public/services/omni.png differ
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 bc64ce4fb826..afdd7a81f42b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -390,6 +390,7 @@ the row lists both.
| northpass_lms | HTTP | requests | ✅ |
| notion | HTTP | requests | ✅ |
| nuget | HTTP | requests | ✅ |
+| omni | HTTP | requests + `rest_source.RESTClient` | ✅ |
| omnisend | HTTP | requests | ✅ |
| octopus_deploy | HTTP | requests | ✅ |
| oncehub | HTTP | requests | ✅ |
@@ -1126,7 +1127,6 @@ doesn't conflict with concurrent PRs.
- octolens
- oecd
- okendo
-- omni
- onedrive
- onehundredms
- onelogin
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/omni.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/omni.py
index 28f2f584ce3f..8c30d46a6249 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/omni.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/omni.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class OmniSourceConfig(config.Config):
- pass
+ host: str
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/canonical_descriptions.py
new file mode 100644
index 000000000000..a10ec5a9ddc7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/canonical_descriptions.py
@@ -0,0 +1,97 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Documents": {
+ "description": "Dashboards and workbooks in your Omni instance, with their owner, folder, and access scope.",
+ "docs_url": "https://docs.omni.co/api/documents/list-documents",
+ "columns": {
+ "identifier": "Unique identifier for the document, used in its URL. Omni documents have no separate `id` field.",
+ "name": "Document name.",
+ "description": "Description of the document.",
+ "connectionId": "ID of the database connection the document is built on.",
+ "deleted": "Whether the document is deleted (archived).",
+ "hasDashboard": "Whether the document has an associated dashboard.",
+ "scope": "Document access scope: `restricted` or `organization`.",
+ "type": "Content type, always `document`.",
+ "updatedAt": "Timestamp the document was last updated.",
+ "url": "URL to view the document (dashboard URL if it has one, otherwise workbook URL).",
+ "owner": "Owner of the document (membership id and display name).",
+ "folder": "Folder containing the document (id, name, path, scope), or null if not in a folder.",
+ "labels": "Labels applied to the document.",
+ },
+ },
+ "Folders": {
+ "description": "Folders organizing documents in your Omni instance.",
+ "docs_url": "https://docs.omni.co/api/folders/list-folders",
+ "columns": {
+ "id": "Unique identifier for the folder.",
+ "name": "Display name of the folder.",
+ "path": "Full path to the folder.",
+ "scope": "Folder access scope: `organization` or `restricted`.",
+ "url": "Direct link to the folder in the Omni UI.",
+ "owner": "Owner of the folder (id and display name).",
+ "labels": "Labels associated with the folder.",
+ },
+ },
+ "Connections": {
+ "description": "Database connections configured in your Omni instance.",
+ "docs_url": "https://docs.omni.co/api/connections/list-connections",
+ "columns": {
+ "id": "The connection's unique ID.",
+ "name": "A descriptive name for the connection.",
+ "dialect": "The type of database (e.g. postgres, snowflake, bigquery).",
+ "database": "The default database/catalog the connection connects to.",
+ "baseRole": "The default role for users accessing the connection.",
+ "defaultSchema": "The default schema used by the connection.",
+ "createdAt": "The time the connection was created.",
+ "updatedAt": "The time the connection was last updated.",
+ "deletedAt": "The time the connection was deleted, if applicable.",
+ },
+ },
+ "Schedules": {
+ "description": "Scheduled deliveries and alerts configured for dashboards in your Omni instance.",
+ "docs_url": "https://docs.omni.co/api/schedules/list-schedules",
+ "columns": {
+ "id": "The schedule's unique ID.",
+ "name": "The name of the schedule.",
+ "schedule": "The cron expression defining when the schedule runs.",
+ "timezone": "The IANA timezone the schedule runs in.",
+ "identifier": "The ID of the dashboard associated with the schedule.",
+ "dashboardName": "The name of the dashboard associated with the schedule.",
+ "ownerId": "The membership ID of the schedule owner.",
+ "ownerName": "The name of the schedule owner.",
+ "destinationType": "The delivery destination: `email`, `slack`, `webhook`, `sftp`, or `s3`.",
+ "format": "The output format of the schedule (e.g. `csv`, `pdf`, `xlsx`).",
+ "content": "Content type: `dashboard` or `single tile`.",
+ "recipientCount": "Number of recipients. Returns `-1` for webhook destinations.",
+ "lastCompletedAt": "Timestamp of the last completed run.",
+ "lastStatus": "Status of the last run (e.g. `COMPLETE`, `ERROR_DELIVERED`).",
+ "disabledAt": "Timestamp when the schedule was paused, if applicable.",
+ },
+ },
+ "Users": {
+ "description": "Users provisioned in your Omni organization (SCIM).",
+ "docs_url": "https://docs.omni.co/api/users/list-users",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "userName": "The user's email address.",
+ "displayName": "The user's display name.",
+ "active": "Whether the user is active.",
+ "emails": "The user's email addresses.",
+ "groups": "User groups the user belongs to.",
+ "meta": "Resource metadata, including `created` and `lastModified` timestamps.",
+ },
+ },
+ "UserGroups": {
+ "description": "User groups provisioned in your Omni organization (SCIM).",
+ "docs_url": "https://docs.omni.co/api/user-groups/list-user-groups",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "displayName": "The name of the group.",
+ "members": "The list of users in the group.",
+ "meta": "Resource metadata, including `created` and `lastModified` timestamps.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/omni.py b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/omni.py
new file mode 100644
index 000000000000..ec43748db5f4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/omni.py
@@ -0,0 +1,460 @@
+import re
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.settings import (
+ DEFAULT_PAGE_SIZE,
+ PARTITION_KEYS,
+ PRIMARY_KEYS,
+ SCIM_ENDPOINTS,
+)
+
+# Loopback hosts where plaintext HTTP carries no network-exposure risk (local dev). Every other
+# host is forced to HTTPS since credentials must never traverse a network in cleartext.
+LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
+
+HOST_NOT_ALLOWED_ERROR = "Omni host is not allowed"
+
+
+class OmniResumeConfig:
+ # Documents/Folders/Schedules resume via an opaque `nextCursor`; the SCIM Users/UserGroups
+ # endpoints resume via a numeric `startIndex`. Only one is ever populated for a given endpoint.
+ cursor: Optional[str] = None
+ start_index: Optional[int] = None
+
+
+def normalize_host(host: str) -> str:
+ """Turn whatever the user typed into a bare instance base URL (scheme + host, no path).
+
+ Accepts ``https://acme.omniapp.co``, ``acme.omniapp.co``, and ``https://acme.omniapp.co/api``,
+ returning ``https://acme.omniapp.co``. Defaults to https when no scheme is given, and forces a
+ plaintext ``http://`` host to ``https://`` except for loopback hosts (local dev).
+ """
+ host = host.strip()
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ parsed = urlparse(host)
+ scheme = parsed.scheme.lower()
+ if scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS:
+ scheme = "https"
+ return f"{scheme}://{parsed.netloc}"
+
+
+def _hostname(host: str) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def _base_api_url(host: str) -> str:
+ return f"{normalize_host(host)}/api"
+
+
+def _format_watermark(value: Any) -> Optional[str]:
+ """Format an incremental cursor value as an Omni-shaped UTC timestamp (millisecond precision,
+ e.g. ``2026-06-01T14:30:00.000Z``) so lexicographic comparison against Omni's ``updatedAt``
+ strings is chronological."""
+ if isinstance(value, date) and not isinstance(value, datetime):
+ value = datetime.combine(value, datetime.min.time())
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+class OmniPageInfoPaginator(BasePaginator):
+ """Paginator for Omni's shared ``{pageInfo, records}`` list shape (documents, folders,
+ schedules): a ``pageSize``/``cursor`` query param pair, with the response's
+ ``pageInfo.hasNextPage`` / ``pageInfo.nextCursor`` driving the next page."""
+
+ def __init__(self, page_size: int = DEFAULT_PAGE_SIZE) -> None:
+ super().__init__()
+ self._page_size = page_size
+ self._cursor: Optional[str] = None
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["pageSize"] = self._page_size
+ if self._cursor is not None:
+ request.params["cursor"] = self._cursor
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ page_info = response.json().get("pageInfo") or {}
+ except Exception:
+ page_info = {}
+ next_cursor = page_info.get("nextCursor")
+ self._has_next_page = bool(page_info.get("hasNextPage")) and bool(next_cursor)
+ self._cursor = next_cursor if self._has_next_page else None
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["pageSize"] = self._page_size
+ if self._cursor is not None:
+ request.params["cursor"] = self._cursor
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"cursor": self._cursor} if self._has_next_page and self._cursor else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ cursor = state.get("cursor")
+ if cursor:
+ self._cursor = str(cursor)
+ self._has_next_page = True
+
+
+class OmniDocumentsPaginator(OmniPageInfoPaginator):
+ """Documents has no server-side ``updatedAt``-since filter, so incremental sync sorts newest
+ first (``sortDirection=desc``) and stops paginating once an entire page predates the stored
+ watermark — an incremental run only fetches pages of changed/new documents instead of walking
+ the whole catalog on every sync. Full syncs (``stop_when_older_than=None``) walk every page."""
+
+ def __init__(self, page_size: int = DEFAULT_PAGE_SIZE, stop_when_older_than: Optional[str] = None) -> None:
+ super().__init__(page_size)
+ self._stop_when_older_than = stop_when_older_than
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if self._has_next_page and self._stop_when_older_than is not None and data:
+ # `updatedAt` is nullable. A page with no comparable (non-null) values can't be
+ # judged against the watermark, so it's skipped rather than risk an early stop that
+ # loses not-yet-synced rows.
+ updated_ats: list[str] = []
+ for row in data:
+ if not isinstance(row, dict):
+ continue
+ updated_at = row.get("updatedAt")
+ if isinstance(updated_at, str) and updated_at:
+ updated_ats.append(updated_at)
+ if updated_ats and max(updated_ats) < self._stop_when_older_than:
+ self._has_next_page = False
+
+
+class OmniScimPaginator(BasePaginator):
+ """Paginator for the SCIM ``{Resources, itemsPerPage, totalResults, startIndex}`` shape used by
+ the Users and UserGroups endpoints. ``startIndex`` is 1-based."""
+
+ def __init__(self, count: int = DEFAULT_PAGE_SIZE) -> None:
+ super().__init__()
+ self._count = count
+ self._start_index = 1
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["count"] = self._count
+ request.params["startIndex"] = self._start_index
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ body = response.json()
+ except Exception:
+ body = {}
+ items_per_page = body.get("itemsPerPage") or 0
+ total_results = body.get("totalResults")
+ if not items_per_page:
+ self._has_next_page = False
+ return
+ self._start_index += items_per_page
+ self._has_next_page = total_results is None or self._start_index <= total_results
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["count"] = self._count
+ request.params["startIndex"] = self._start_index
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"start_index": self._start_index} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ start_index = state.get("start_index")
+ if start_index:
+ self._start_index = int(start_index)
+ self._has_next_page = True
+
+
+def get_resource(
+ name: str,
+ should_use_incremental_field: bool,
+ stop_when_older_than: Optional[str],
+) -> EndpointResource:
+ # Declared once so each branch's dict literal is checked against `Endpoint` (a re-annotation
+ # per branch trips mypy's no-redef).
+ endpoint: Endpoint
+ if name == "Documents":
+ write_disposition = (
+ {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"
+ )
+ endpoint = {
+ "path": "/v1/documents",
+ "params": {"sortField": "updatedAt", "sortDirection": "desc"},
+ "paginator": OmniDocumentsPaginator(
+ stop_when_older_than=stop_when_older_than if should_use_incremental_field else None
+ ),
+ "data_selector": "records",
+ }
+ return {
+ "name": name,
+ "table_name": "documents",
+ "write_disposition": write_disposition,
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+ if name == "Folders":
+ endpoint = {
+ "path": "/v1/folders",
+ "params": {"sortField": "name", "sortDirection": "asc"},
+ "paginator": OmniPageInfoPaginator(),
+ "data_selector": "records",
+ }
+ return {
+ "name": name,
+ "table_name": "folders",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+ if name == "Connections":
+ endpoint = {
+ "path": "/v1/connections",
+ "paginator": SinglePagePaginator(),
+ "data_selector": "connections",
+ }
+ return {
+ "name": name,
+ "table_name": "connections",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+ if name == "Schedules":
+ endpoint = {
+ "path": "/v1/schedules",
+ "params": {"sortField": "scheduleName", "sortDirection": "asc"},
+ "paginator": OmniPageInfoPaginator(),
+ "data_selector": "records",
+ }
+ return {
+ "name": name,
+ "table_name": "schedules",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+ if name == "Users":
+ endpoint = {
+ "path": "/scim/v2/users",
+ "paginator": OmniScimPaginator(),
+ "data_selector": "Resources",
+ }
+ return {
+ "name": name,
+ "table_name": "users",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+ if name == "UserGroups":
+ endpoint = {
+ "path": "/scim/v2/groups",
+ "paginator": OmniScimPaginator(),
+ "data_selector": "Resources",
+ }
+ return {
+ "name": name,
+ "table_name": "user_groups",
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+ raise ValueError(f"Unknown Omni endpoint: {name}")
+
+
+def validate_credentials(
+ host: str, api_key: str, team_id: int, schema_name: Optional[str] = None
+) -> tuple[bool, str | None]:
+ """Confirm the credentials are genuine with a cheap ``/v1/whoami`` probe.
+
+ The host is customer-controlled, so we block internal/private addresses (SSRF, cloud only)
+ and refuse to follow redirects.
+ """
+ try:
+ base_api_url = _base_api_url(host)
+ except Exception:
+ return False, "Invalid Omni instance URL"
+
+ hostname = _hostname(host)
+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):
+ return False, "Invalid Omni instance URL"
+
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ is_ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,), allow_redirects=False),
+ f"{base_api_url}/v1/whoami",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ allow_redirects=False,
+ )
+
+ if is_ok:
+ return True, None
+ if status == 401:
+ return False, "Invalid Omni API key"
+ if status == 403:
+ # Valid credentials, missing permission for this probe — let source creation through.
+ if schema_name is None:
+ return True, None
+ return False, "Your Omni API key does not have access to this data"
+ if status is None:
+ return False, "Could not reach your Omni instance. Check the Instance URL and try again."
+ return (
+ False,
+ f"Omni returned an unexpected response (HTTP {status}). Check that the Instance URL points to your Omni instance.",
+ )
+
+
+def get_key_scope(host: str, api_key: str) -> Optional[str]:
+ """Return the caller's API key scope (``"organization"`` or ``"user"``) via ``/v1/whoami``, or
+ ``None`` if it can't be determined (used to warn that SCIM endpoints need an Organization key,
+ since Personal Access Tokens are documented as unsupported for them)."""
+ try:
+ base_api_url = _base_api_url(host)
+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(
+ f"{base_api_url}/v1/whoami",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=10,
+ allow_redirects=False,
+ )
+ if response.status_code != 200:
+ return None
+ key_scope = response.json().get("keyScope")
+ return key_scope if isinstance(key_scope, str) else None
+ except Exception:
+ return None
+
+
+def get_endpoint_permissions(host: str, api_key: str, endpoints: list[str]) -> dict[str, str | None]:
+ result: dict[str, str | None] = dict.fromkeys(endpoints)
+ scim_requested = [name for name in endpoints if name in SCIM_ENDPOINTS]
+ if not scim_requested:
+ return result
+
+ key_scope = get_key_scope(host, api_key)
+ if key_scope == "user":
+ reason = "Requires an Organization API key — Personal Access Tokens can't access SCIM user/group endpoints."
+ for name in scim_requested:
+ result[name] = reason
+ return result
+
+
+def omni_source(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[OmniResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ # Re-validate the host at sync time, not just at credential-save time: the stored hostname
+ # could have been DNS-rebound to a private/internal address since it was validated, so a
+ # scheduled import must re-check before sending the bearer-authenticated request (SSRF).
+ hostname = _hostname(host)
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ raise ValueError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ stop_when_older_than = _format_watermark(db_incremental_field_last_value) if should_use_incremental_field else None
+ resource_config = get_resource(endpoint, should_use_incremental_field, stop_when_older_than)
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": _base_api_url(host),
+ "auth": {"type": "bearer", "token": api_key},
+ "headers": {"Accept": "application/json"},
+ # SSRF defense in depth: pin every request to the validated host and never follow a
+ # 3xx, so a redirect can't bounce the bearer token to a private/metadata address.
+ "allowed_hosts": [hostname],
+ "allow_redirects": False,
+ },
+ "resources": [resource_config],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ if resume_config.cursor:
+ initial_paginator_state = {"cursor": resume_config.cursor}
+ elif resume_config.start_index:
+ initial_paginator_state = {"start_index": resume_config.start_index}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only Documents/Folders/Schedules/Users/UserGroups paginate; Connections uses
+ # SinglePagePaginator and never reports a resume state, so this is a no-op for it.
+ if not state:
+ return
+ cursor = state.get("cursor")
+ start_index = state.get("start_index")
+ if cursor:
+ resumable_source_manager.save_state(OmniResumeConfig(cursor=str(cursor)))
+ elif start_index:
+ resumable_source_manager.save_state(OmniResumeConfig(start_index=int(start_index)))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ # Incremental filtering is applied via the custom paginator's `stop_when_older_than`
+ # above, not the framework's declarative `incremental` param — no endpoint here declares
+ # one, so the framework has nothing to inject this into.
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ partition_key = PARTITION_KEYS.get(endpoint)
+
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS[endpoint],
+ sort_mode="desc" if endpoint == "Documents" else "asc",
+ partition_mode="datetime" if partition_key else None,
+ partition_format="week" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/settings.py
new file mode 100644
index 000000000000..a21ead4d0ba4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/settings.py
@@ -0,0 +1,55 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+ENDPOINTS = (
+ "Documents",
+ "Folders",
+ "Connections",
+ "Schedules",
+ "Users",
+ "UserGroups",
+)
+
+# Only Documents exposes anything close to a timestamp cursor (`sortField=updatedAt`, no
+# server-side `updatedAt`-since filter). Folders/Schedules only sort by name/path/favorites;
+# Connections and the SCIM Users/UserGroups endpoints return their full result unpaginated or
+# sorted purely by creation order, with no timestamp filter at all — full refresh only.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "Documents": [
+ {
+ "label": "updatedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+}
+
+# Documents has no `id` field in the API response — only `identifier`, which is unique
+# per-organization and used in the document's URL.
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "Documents": ["identifier"],
+ "Folders": ["id"],
+ "Connections": ["id"],
+ "Schedules": ["id"],
+ "Users": ["id"],
+ "UserGroups": ["id"],
+}
+
+# A stable field to partition on — never the incremental cursor (`updatedAt` changes on every
+# edit and would rewrite partitions on every sync). Only Connections exposes a stable top-level
+# `createdAt`; the rest either have no creation timestamp (Folders/Schedules) or nest it under
+# `meta.created` (Users/UserGroups), which isn't worth partitioning on.
+PARTITION_KEYS: dict[str, str | None] = {
+ "Documents": None,
+ "Folders": None,
+ "Connections": "createdAt",
+ "Schedules": None,
+ "Users": None,
+ "UserGroups": None,
+}
+
+DEFAULT_PAGE_SIZE = 100
+
+# SCIM users/groups endpoints require an Organization API key (Personal Access Tokens are
+# explicitly documented as unsupported for them).
+SCIM_ENDPOINTS = frozenset({"Users", "UserGroups"})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/source.py
index 4b307a1a7b85..93ce0e22ce0b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/source.py
@@ -1,30 +1,138 @@
-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.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,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.omni import OmniSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.omni import (
+ OmniResumeConfig,
+ get_endpoint_permissions as get_omni_endpoint_permissions,
+ omni_source,
+ validate_credentials as validate_omni_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OmniSource(SimpleSource[OmniSourceConfig]):
+class OmniSource(ResumableSource[OmniSourceConfig, OmniResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.omni.co/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OMNI
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Omni API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error": "Your Omni API key does not have the required permissions. Please check the key's access and try again.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.omni.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: OmniSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: OmniSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_omni_credentials(config.host, config.api_key, team_id, schema_name)
+
+ def get_endpoint_permissions(
+ self, config: OmniSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
+ ) -> dict[str, str | None]:
+ return get_omni_endpoint_permissions(config.host, config.api_key, endpoints)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OmniResumeConfig]:
+ return ResumableSourceManager[OmniResumeConfig](inputs, OmniResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OmniSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OmniResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return omni_source(
+ host=config.host,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.OMNI,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Omni Analytics",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="Sync documents, folders, connections, schedules, users, and user groups from your Omni instance.\n\nUse an **Organization API key** for full coverage (**Settings > API access**) — Personal Access Tokens only see content the token owner can access, and can't read the Users or User groups tables at all.",
+ docsUrl="https://posthog.com/docs/cdp/sources/omni",
iconPath="/static/services/omni.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["bi", "business intelligence"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://your-company.omniapp.co",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/tests/test_omni.py b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/tests/test_omni.py
new file mode 100644
index 000000000000..68324b96c13e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/tests/test_omni.py
@@ -0,0 +1,518 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni import omni as omni_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.omni import (
+ OmniDocumentsPaginator,
+ OmniPageInfoPaginator,
+ OmniResumeConfig,
+ OmniScimPaginator,
+ _base_api_url,
+ _format_watermark,
+ _hostname,
+ get_endpoint_permissions,
+ get_key_scope,
+ get_resource,
+ normalize_host,
+ omni_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.settings import PARTITION_KEYS, PRIMARY_KEYS
+
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+OMNI_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.omni.omni.make_tracked_session"
+
+
+def _make_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _make_manager(resume_state: OmniResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("https://acme.omniapp.co", "https://acme.omniapp.co"),
+ ("acme.omniapp.co", "https://acme.omniapp.co"),
+ ("https://acme.omniapp.co/api", "https://acme.omniapp.co"),
+ ("http://acme.omniapp.co", "https://acme.omniapp.co"),
+ ("http://localhost:8080", "http://localhost:8080"),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+ def test_hostname_extracts_bare_host(self):
+ assert _hostname("https://acme.omniapp.co/api") == "acme.omniapp.co"
+
+ def test_base_api_url_appends_api_path(self):
+ assert _base_api_url("acme.omniapp.co") == "https://acme.omniapp.co/api"
+
+
+class TestFormatWatermark:
+ def test_formats_datetime_with_millisecond_precision(self):
+ import datetime
+
+ value = datetime.datetime(2026, 6, 1, 14, 30, 0, 500000, tzinfo=datetime.UTC)
+ assert _format_watermark(value) == "2026-06-01T14:30:00.500Z"
+
+ def test_naive_datetime_assumed_utc(self):
+ import datetime
+
+ value = datetime.datetime(2026, 6, 1, 14, 30, 0)
+ assert _format_watermark(value) == "2026-06-01T14:30:00.000Z"
+
+ def test_string_value_passed_through(self):
+ assert _format_watermark("2026-06-01T14:30:00.000Z") == "2026-06-01T14:30:00.000Z"
+
+ @pytest.mark.parametrize("value", [None, "", 123])
+ def test_unsupported_values_return_none(self, value):
+ assert _format_watermark(value) is None
+
+
+class TestOmniPageInfoPaginator:
+ def test_initial_request_has_no_cursor(self):
+ paginator = OmniPageInfoPaginator(page_size=50)
+ request = Request(method="GET", url="https://acme.omniapp.co/api/v1/documents")
+ paginator.init_request(request)
+
+ assert request.params["pageSize"] == 50
+ assert "cursor" not in request.params
+
+ def test_update_state_has_next_page(self):
+ paginator = OmniPageInfoPaginator()
+ response = _make_response({"pageInfo": {"hasNextPage": True, "nextCursor": "abc"}, "records": []})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is True
+ assert paginator.get_resume_state() == {"cursor": "abc"}
+
+ def test_update_state_terminal_page(self):
+ paginator = OmniPageInfoPaginator()
+ response = _make_response({"pageInfo": {"hasNextPage": False, "nextCursor": None}, "records": []})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+ assert paginator.get_resume_state() is None
+
+ def test_has_next_page_true_but_no_cursor_treated_as_terminal(self):
+ # Defensive: hasNextPage=True with a missing nextCursor shouldn't spin forever.
+ paginator = OmniPageInfoPaginator()
+ response = _make_response({"pageInfo": {"hasNextPage": True, "nextCursor": None}, "records": []})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+
+ def test_malformed_body_treated_as_terminal(self):
+ paginator = OmniPageInfoPaginator()
+ response = _make_response({})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+
+ def test_set_resume_state_seeds_cursor(self):
+ paginator = OmniPageInfoPaginator()
+ paginator.set_resume_state({"cursor": "resumed-cursor"})
+
+ request = Request(method="GET", url="https://acme.omniapp.co/api/v1/documents")
+ paginator.init_request(request)
+ assert request.params["cursor"] == "resumed-cursor"
+
+ def test_set_resume_state_ignores_missing_cursor(self):
+ paginator = OmniPageInfoPaginator()
+ paginator.set_resume_state({})
+ assert paginator.get_resume_state() is None
+
+
+class TestOmniDocumentsPaginator:
+ def test_full_sync_never_stops_early(self):
+ paginator = OmniDocumentsPaginator(stop_when_older_than=None)
+ response = _make_response({"pageInfo": {"hasNextPage": True, "nextCursor": "c1"}, "records": []})
+ data = [{"updatedAt": "2020-01-01T00:00:00.000Z"}]
+ paginator.update_state(response, data)
+
+ assert paginator.has_next_page is True
+
+ def test_incremental_stops_once_page_predates_watermark(self):
+ paginator = OmniDocumentsPaginator(stop_when_older_than="2026-01-01T00:00:00.000Z")
+ response = _make_response({"pageInfo": {"hasNextPage": True, "nextCursor": "c1"}, "records": []})
+ data = [
+ {"updatedAt": "2025-06-01T00:00:00.000Z"},
+ {"updatedAt": "2025-05-01T00:00:00.000Z"},
+ ]
+ paginator.update_state(response, data)
+
+ assert paginator.has_next_page is False
+
+ def test_incremental_keeps_paginating_when_page_has_newer_rows(self):
+ paginator = OmniDocumentsPaginator(stop_when_older_than="2026-01-01T00:00:00.000Z")
+ response = _make_response({"pageInfo": {"hasNextPage": True, "nextCursor": "c1"}, "records": []})
+ data = [
+ {"updatedAt": "2026-06-01T00:00:00.000Z"},
+ {"updatedAt": "2025-05-01T00:00:00.000Z"},
+ ]
+ paginator.update_state(response, data)
+
+ assert paginator.has_next_page is True
+
+ def test_null_updated_at_does_not_force_early_stop(self):
+ # A page with only null `updatedAt` values can't be judged against the watermark, so
+ # pagination continues rather than risk skipping unsynced rows.
+ paginator = OmniDocumentsPaginator(stop_when_older_than="2026-01-01T00:00:00.000Z")
+ response = _make_response({"pageInfo": {"hasNextPage": True, "nextCursor": "c1"}, "records": []})
+ data = [{"updatedAt": None}, {"identifier": "no-updated-at-key"}]
+ paginator.update_state(response, data)
+
+ assert paginator.has_next_page is True
+
+
+class TestOmniScimPaginator:
+ def test_initial_request_starts_at_index_one(self):
+ paginator = OmniScimPaginator(count=50)
+ request = Request(method="GET", url="https://acme.omniapp.co/api/scim/v2/users")
+ paginator.init_request(request)
+
+ assert request.params == {"count": 50, "startIndex": 1}
+
+ def test_advances_start_index_when_more_results_remain(self):
+ paginator = OmniScimPaginator(count=100)
+ response = _make_response({"Resources": [], "itemsPerPage": 100, "totalResults": 250, "startIndex": 1})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is True
+ assert paginator.get_resume_state() == {"start_index": 101}
+
+ def test_stops_when_all_results_returned(self):
+ paginator = OmniScimPaginator(count=100)
+ response = _make_response({"Resources": [], "itemsPerPage": 50, "totalResults": 50, "startIndex": 1})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+
+ def test_stops_on_empty_page(self):
+ paginator = OmniScimPaginator(count=100)
+ response = _make_response({"Resources": [], "itemsPerPage": 0, "totalResults": 0, "startIndex": 1})
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+
+ def test_set_resume_state_seeds_start_index(self):
+ paginator = OmniScimPaginator()
+ paginator.set_resume_state({"start_index": 201})
+
+ request = Request(method="GET", url="https://acme.omniapp.co/api/scim/v2/users")
+ paginator.init_request(request)
+ assert request.params["startIndex"] == 201
+
+
+class TestGetResource:
+ @pytest.mark.parametrize(
+ "endpoint, expected_path, expected_selector",
+ [
+ ("Documents", "/v1/documents", "records"),
+ ("Folders", "/v1/folders", "records"),
+ ("Connections", "/v1/connections", "connections"),
+ ("Schedules", "/v1/schedules", "records"),
+ ("Users", "/scim/v2/users", "Resources"),
+ ("UserGroups", "/scim/v2/groups", "Resources"),
+ ],
+ )
+ def test_endpoint_shape(self, endpoint, expected_path, expected_selector):
+ resource = get_resource(endpoint, should_use_incremental_field=False, stop_when_older_than=None)
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+
+ assert endpoint_config["path"] == expected_path
+ assert endpoint_config["data_selector"] == expected_selector
+
+ def test_unknown_endpoint_raises(self):
+ with pytest.raises(ValueError):
+ get_resource("Nope", should_use_incremental_field=False, stop_when_older_than=None)
+
+ def test_documents_incremental_uses_merge(self):
+ resource = get_resource("Documents", should_use_incremental_field=True, stop_when_older_than="x")
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+ def test_documents_full_refresh_uses_replace(self):
+ resource = get_resource("Documents", should_use_incremental_field=False, stop_when_older_than=None)
+ assert resource["write_disposition"] == "replace"
+
+ @pytest.mark.parametrize("endpoint", ["Folders", "Connections", "Schedules", "Users", "UserGroups"])
+ def test_non_incremental_endpoints_always_replace(self, endpoint):
+ resource = get_resource(endpoint, should_use_incremental_field=True, stop_when_older_than=None)
+ assert resource["write_disposition"] == "replace"
+
+ def test_documents_sorts_newest_first(self):
+ resource = get_resource("Documents", should_use_incremental_field=False, stop_when_older_than=None)
+ endpoint_config = resource["endpoint"]
+ assert isinstance(endpoint_config, dict)
+ assert endpoint_config["params"] == {"sortField": "updatedAt", "sortDirection": "desc"}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, schema_name, expected_valid",
+ [
+ (200, None, True),
+ (200, "Documents", True),
+ (401, None, False),
+ (401, "Documents", False),
+ (403, None, True),
+ (403, "Documents", False),
+ (500, None, False),
+ ],
+ )
+ @mock.patch.object(omni_module, "_is_host_safe", return_value=(True, None))
+ @mock.patch(OMNI_SESSION_PATCH)
+ def test_validate_credentials_status_mapping(
+ self, mock_session, _mock_host_safe, status_code, schema_name, expected_valid
+ ):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+
+ is_valid, error = validate_credentials("acme.omniapp.co", "test-key", team_id=1, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert error
+
+ @mock.patch.object(omni_module, "_is_host_safe", return_value=(False, "internal address"))
+ def test_validate_credentials_blocks_unsafe_host(self, _mock_host_safe):
+ is_valid, error = validate_credentials("169.254.169.254", "test-key", team_id=1)
+
+ assert is_valid is False
+ assert error == "internal address"
+
+ def test_validate_credentials_rejects_invalid_hostname(self):
+ is_valid, error = validate_credentials("not a host!!", "test-key", team_id=1)
+ assert is_valid is False
+ assert error
+
+ @mock.patch.object(omni_module, "_is_host_safe", return_value=(True, None))
+ @mock.patch(OMNI_SESSION_PATCH)
+ def test_sends_bearer_token(self, mock_session, _mock_host_safe):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+
+ validate_credentials("acme.omniapp.co", "test-key", team_id=1)
+
+ _, kwargs = mock_session.return_value.get.call_args
+ assert kwargs["headers"]["Authorization"] == "Bearer test-key"
+
+
+class TestGetKeyScope:
+ @mock.patch(OMNI_SESSION_PATCH)
+ def test_returns_key_scope_on_success(self, mock_session):
+ response = mock.MagicMock(status_code=200)
+ response.json.return_value = {"keyScope": "organization"}
+ mock_session.return_value.get.return_value = response
+
+ assert get_key_scope("acme.omniapp.co", "test-key") == "organization"
+
+ @mock.patch(OMNI_SESSION_PATCH)
+ def test_returns_none_on_error_status(self, mock_session):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)
+ assert get_key_scope("acme.omniapp.co", "test-key") is None
+
+ @mock.patch(OMNI_SESSION_PATCH)
+ def test_returns_none_on_request_exception(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert get_key_scope("acme.omniapp.co", "test-key") is None
+
+
+class TestGetEndpointPermissions:
+ def test_no_scim_endpoints_requested_returns_all_reachable(self):
+ result = get_endpoint_permissions("acme.omniapp.co", "test-key", ["Documents", "Folders"])
+ assert result == {"Documents": None, "Folders": None}
+
+ @mock.patch.object(omni_module, "get_key_scope", return_value="user")
+ def test_pat_scope_blocks_scim_endpoints(self, _mock_scope):
+ result = get_endpoint_permissions("acme.omniapp.co", "test-key", ["Documents", "Users", "UserGroups"])
+
+ assert result["Documents"] is None
+ assert result["Users"] is not None
+ assert result["UserGroups"] is not None
+
+ @mock.patch.object(omni_module, "get_key_scope", return_value="organization")
+ def test_org_scope_allows_scim_endpoints(self, _mock_scope):
+ result = get_endpoint_permissions("acme.omniapp.co", "test-key", ["Users", "UserGroups"])
+ assert result == {"Users": None, "UserGroups": None}
+
+ @mock.patch.object(omni_module, "get_key_scope", return_value=None)
+ def test_unknown_scope_allows_scim_endpoints(self, _mock_scope):
+ # Can't confirm the scope (probe failed) — don't block on a guess; sync-time errors are
+ # handled separately by get_non_retryable_errors.
+ result = get_endpoint_permissions("acme.omniapp.co", "test-key", ["Users"])
+ assert result == {"Users": None}
+
+
+class TestOmniSourceEndToEnd:
+ def _drive(self, endpoint: str, manager: mock.MagicMock, responses: list[Response], **kwargs: Any):
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = omni_source(
+ host="acme.omniapp.co",
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ rows = [row for page in cast(Iterable[Any], response.items()) for row in page]
+ return response, rows, sent_params
+
+ def test_documents_pagination_and_checkpointing(self):
+ manager = _make_manager()
+ responses = [
+ _make_response(
+ {
+ "pageInfo": {"hasNextPage": True, "nextCursor": "cursor-1"},
+ "records": [{"identifier": "d1", "updatedAt": "2026-01-02T00:00:00.000Z"}],
+ }
+ ),
+ _make_response(
+ {
+ "pageInfo": {"hasNextPage": False, "nextCursor": None},
+ "records": [{"identifier": "d2", "updatedAt": "2026-01-01T00:00:00.000Z"}],
+ }
+ ),
+ ]
+ _, rows, sent_params = self._drive("Documents", manager, responses)
+
+ assert len(rows) == 2
+ assert sent_params[0].get("sortField") == "updatedAt"
+ assert sent_params[0].get("sortDirection") == "desc"
+ assert "cursor" not in sent_params[0]
+ assert sent_params[1]["cursor"] == "cursor-1"
+ manager.save_state.assert_called_once_with(OmniResumeConfig(cursor="cursor-1"))
+
+ def test_documents_resumes_from_saved_cursor(self):
+ manager = _make_manager(OmniResumeConfig(cursor="resumed-cursor"))
+ responses = [_make_response({"pageInfo": {"hasNextPage": False, "nextCursor": None}, "records": []})]
+
+ _, _rows, sent_params = self._drive("Documents", manager, responses)
+
+ assert sent_params[0]["cursor"] == "resumed-cursor"
+ manager.load_state.assert_called_once()
+
+ def test_connections_single_page_never_checkpoints(self):
+ manager = _make_manager()
+ responses = [_make_response({"connections": [{"id": "c1"}, {"id": "c2"}]})]
+
+ _, rows, _sent_params = self._drive("Connections", manager, responses)
+
+ assert rows == [{"id": "c1"}, {"id": "c2"}]
+ manager.save_state.assert_not_called()
+
+ def test_users_scim_pagination_checkpoints_start_index(self):
+ manager = _make_manager()
+ responses = [
+ _make_response(
+ {"Resources": [{"id": "u1"}], "itemsPerPage": 1, "totalResults": 2, "startIndex": 1},
+ ),
+ _make_response(
+ {"Resources": [{"id": "u2"}], "itemsPerPage": 1, "totalResults": 2, "startIndex": 2},
+ ),
+ ]
+ _, rows, _sent_params = self._drive("Users", manager, responses)
+
+ assert rows == [{"id": "u1"}, {"id": "u2"}]
+ manager.save_state.assert_called_once_with(OmniResumeConfig(start_index=2))
+
+ @pytest.mark.parametrize("endpoint", list(PRIMARY_KEYS.keys()))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ manager = _make_manager()
+ selector = {
+ "Documents": "records",
+ "Folders": "records",
+ "Connections": "connections",
+ "Schedules": "records",
+ "Users": "Resources",
+ "UserGroups": "Resources",
+ }[endpoint]
+ responses = [
+ _make_response({"pageInfo": {"hasNextPage": False, "nextCursor": None}, selector: []})
+ if selector != "connections"
+ else _make_response({selector: []})
+ ]
+
+ response, _rows, _sent_params = self._drive(endpoint, manager, responses)
+
+ assert response.primary_keys == PRIMARY_KEYS[endpoint]
+ assert response.sort_mode == ("desc" if endpoint == "Documents" else "asc")
+ partition_key = PARTITION_KEYS[endpoint]
+ if partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestOmniSourceSsrfGuards:
+ @mock.patch.object(omni_module, "_is_host_safe", return_value=(False, "internal address"))
+ def test_sync_rejects_unsafe_host(self, _mock_host_safe):
+ # A hostname that validated publicly can be DNS-rebound to a private address before a
+ # scheduled import runs; the sync must re-check rather than trust the stored host.
+ with pytest.raises(ValueError, match="internal address"):
+ omni_source(
+ host="acme.omniapp.co",
+ api_key="test-key",
+ endpoint="Connections",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ @mock.patch.object(omni_module, "_is_host_safe", return_value=(True, None))
+ def test_sync_pins_host_and_disables_redirects(self, _mock_host_safe):
+ send_kwargs: list[dict[str, Any]] = []
+
+ def fake_send(request: Any, *_args: Any, **kwargs: Any) -> Response:
+ send_kwargs.append(kwargs)
+ return _make_response({"connections": []})
+
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = omni_source(
+ host="acme.omniapp.co",
+ api_key="test-key",
+ endpoint="Connections",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ # Redirects are never followed, so a 3xx can't bounce the bearer token off-host.
+ assert send_kwargs and all(kw.get("allow_redirects") is False for kw in send_kwargs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/omni/tests/test_omni_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/tests/test_omni_source.py
new file mode 100644
index 000000000000..d28ba3120815
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/omni/tests/test_omni_source.py
@@ -0,0 +1,168 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.omni import OmniSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.omni import OmniResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.omni.source import OmniSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestOmniSource:
+ def setup_method(self):
+ self.source = OmniSource()
+ self.team_id = 123
+ self.config = OmniSourceConfig(host="https://acme.omniapp.co", api_key="omni-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.OMNI
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Omni"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/omni.png"
+ assert config.category is not None
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["host", "api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_host_field_is_not_secret(self):
+ config = self.source.get_source_config
+ host_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "host")
+ assert host_field.type == SourceFieldInputConfigType.TEXT
+ assert host_field.secret is False
+ assert host_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.omniapp.co/api/v1/whoami",
+ "403 Client Error: Forbidden for url: https://acme.omniapp.co/api/v1/documents",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ def test_non_retryable_errors_does_not_match_unrelated_server_error(self):
+ # Omni's host is customer-controlled (no fixed domain to anchor on), so the auth-failure
+ # keys are necessarily generic status-line substrings — this only guards against a key so
+ # broad it would also swallow a transient 5xx.
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ other_error = "500 Server Error for url: https://acme.omniapp.co/api/v1/documents"
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_incremental, expected_fields",
+ [
+ ("Documents", True, ["updatedAt"]),
+ ("Folders", False, []),
+ ("Connections", False, []),
+ ("Schedules", False, []),
+ ("Users", False, []),
+ ("UserGroups", False, []),
+ ],
+ )
+ def test_schemas_advertise_expected_incremental_fields(self, endpoint, expected_incremental, expected_fields):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].supports_incremental is expected_incremental
+ assert schemas[endpoint].incremental_fields == INCREMENTAL_FIELDS.get(endpoint, [])
+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == expected_fields
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Documents"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Documents"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid",
+ [
+ ((True, None), True),
+ ((False, "Invalid Omni API key"), False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.omni.source.validate_omni_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert error_message
+ mock_validate.assert_called_once_with(self.config.host, self.config.api_key, self.team_id, None)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.omni.source.get_omni_endpoint_permissions"
+ )
+ def test_get_endpoint_permissions_delegates(self, mock_get_permissions):
+ mock_get_permissions.return_value = {"Users": "some reason", "Documents": None}
+
+ result = self.source.get_endpoint_permissions(self.config, self.team_id, ["Users", "Documents"])
+
+ assert result == {"Users": "some reason", "Documents": None}
+ mock_get_permissions.assert_called_once_with(self.config.host, self.config.api_key, ["Users", "Documents"])
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OmniResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.omni.source.omni_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_omni_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Documents"
+ inputs.team_id = 123
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_omni_source.assert_called_once()
+ kwargs = mock_omni_source.call_args.kwargs
+ assert kwargs["host"] == "https://acme.omniapp.co"
+ assert kwargs["api_key"] == "omni-key"
+ assert kwargs["endpoint"] == "Documents"
+ assert kwargs["team_id"] == 123
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.omni.source.omni_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_omni_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Documents"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_omni_source.call_args.kwargs["db_incremental_field_last_value"] is None