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 the auth0 import source (#112591)

Tom Owers80da7117a4da
diff --git a/frontend/public/services/auth0.png b/frontend/public/services/auth0.png
index 303985e4aae5..9a28800dfdec 100644
Binary files a/frontend/public/services/auth0.png and b/frontend/public/services/auth0.png differ
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 50181758d223..f6ca91e2fb8e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10117,7 +10117,7 @@ snapshots:
scenes-app-experiments--experiment-with-multi-step-funnel-metric--dark:
hash: v1.k794b7964.7b12a04f5d1e928cfdeb7717d48f1ccf4f482ffa84b7c90bfb73408a30d99747.AD3c204Kl_c8mJC1Fnw9k13ltR47mG_4N0mPFAM-wmE
scenes-app-experiments--experiment-with-multi-step-funnel-metric--light:
- hash: v1.k794b7964.373ad4997e53fff920eae240f3636692f9c44d506c24415ef97d6f21641db835._bJ-yH3SuhklRTdrwETWgsDKJH8mhf-tkQTTxqPsn6s
+ hash: v1.k794b7964.c830e3700a91c55de1933858fdd9e6d4ce3b72430ae64b13520388a3dc408e1f._yDfyFB1juNKCfrVqkA-nhYPNRK9VrizCtJ58Fg9XdM
scenes-app-experiments--experiment-with-multiple-metrics--dark:
hash: v1.k794b7964.abaf9111cbf345951d9d7e9e68574d57df522c42fff4991f1dc30993e5c253f6.D8J9SH5TXG4g5JuFg8yW7BIjN8WqqOkS-efa9T4GsBk
scenes-app-experiments--experiment-with-multiple-metrics--light:
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 b9ee48affcfc..535c75dde72d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -100,6 +100,7 @@ the row lists both.
| astronomer | HTTP | requests | ✅ |
| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| auth0 | HTTP | requests | ✅ |
| automox | HTTP | requests | ✅ |
| autumn | HTTP | requests + `rest_source.RESTClient` | ✅ |
| avalara | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -983,7 +984,6 @@ doesn't conflict with concurrent PRs.
- athenahealth
- atlan
- audiogo
-- auth0
- autodesk_construction_cloud
- automox
- aws_athena
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/auth0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/auth0.py
new file mode 100644
index 000000000000..ccdc62e03aba
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/auth0.py
@@ -0,0 +1,633 @@
+import re
+import json
+import time
+import threading
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.settings import (
+ AUTH0_ENDPOINTS,
+ MAX_PAGE_SIZE,
+ SEARCH_RESULT_CAP,
+ Auth0EndpointConfig,
+)
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# The tenant domain is customer-supplied, so a hostile or misconfigured server could stream an
+# arbitrarily large body. `requests` buffers a non-streamed response whole into a shared worker's
+# memory before `.json()` runs, so every response is read with `stream=True` and capped here. A
+# 100-row page of Auth0 users with large `app_metadata` is a few MiB, so this leaves headroom.
+MAX_RESPONSE_BYTES = 100 * 1024 * 1024
+_RESPONSE_CHUNK_BYTES = 64 * 1024
+_ERROR_BODY_PREVIEW_BYTES = 2 * 1024
+# `requests`' timeout only bounds each individual socket read, so a host that dribbles a body
+# under that timeout could hold a worker open indefinitely. This bounds the whole transfer.
+MAX_DOWNLOAD_SECONDS = 300
+
+# A server that keeps returning full pages while omitting or inflating `total` would otherwise
+# pin the (up to week-long) resumable activity in an endless fetch loop. At 100 rows per page
+# this is far more than any real tenant holds.
+MAX_PAGES = 100_000
+
+# Access tokens are minted per run and are valid for 24h by default; re-mint this many seconds
+# before the deadline so no request rides a token that expires mid-flight.
+TOKEN_REFRESH_MARGIN_SECONDS = 60
+DEFAULT_TOKEN_LIFETIME_SECONDS = 24 * 60 * 60
+
+HOST_NOT_ALLOWED_ERROR = "Auth0 domain is not allowed"
+PAGINATION_STALLED_ERROR = "Auth0 pagination could not advance past the 1000-result window"
+
+
+class Auth0HostNotAllowedError(Exception):
+ pass
+
+
+class Auth0RetryableError(Exception):
+ pass
+
+
+class Auth0ResponseTooLargeError(Exception):
+ pass
+
+
+class Auth0ResponseTooSlowError(Exception):
+ pass
+
+
+class Auth0PaginationLimitError(Exception):
+ pass
+
+
+class Auth0PaginationStalledError(Exception):
+ pass
+
+
[email protected](frozen=True)
+class Auth0ResumeConfig:
+ # Zero-based page index within the current window. Query params are rebuilt
+ # deterministically from the schema inputs, so page + window start is all we need.
+ page: int
+ # Lower bound of the Lucene date window currently being paged, or None while the run is
+ # still inside the first (unfiltered) window.
+ window_start: Optional[str] = None
+
+
+def normalize_domain(domain: str) -> str:
+ """Turn whatever the user typed into a bare Auth0 tenant domain.
+
+ Accepts ``tenant.us.auth0.com``, ``https://tenant.us.auth0.com/`` or
+ ``tenant.us.auth0.com/api/v2`` and returns ``tenant.us.auth0.com``.
+ """
+ domain = domain.strip()
+ domain = re.sub(r"^https?://", "", domain, flags=re.IGNORECASE)
+ domain = domain.split("/")[0]
+ return domain.strip().rstrip("/")
+
+
+def _base_url(domain: str) -> str:
+ return f"https://{normalize_domain(domain)}"
+
+
+def management_audience(domain: str, api_version: str) -> str:
+ """The Management API's audience identifier — always the canonical tenant domain."""
+ return f"{_base_url(domain)}/api/{api_version}/"
+
+
+def _reject_redirect_response(response: requests.Response, *args: Any, **kwargs: Any) -> requests.Response:
+ """Reject redirects in the response hook, before Requests can consume their bodies."""
+ if response.is_redirect or response.is_permanent_redirect:
+ response.close()
+ raise Auth0HostNotAllowedError(
+ f"Auth0 returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+ return response
+
+
+def _iter_response_content(response: requests.Response) -> Iterator[bytes]:
+ """Read response chunks while a watchdog enforces the total download deadline."""
+ expired = threading.Event()
+
+ def close_expired_response() -> None:
+ expired.set()
+ response.close()
+
+ watchdog = threading.Timer(MAX_DOWNLOAD_SECONDS, close_expired_response)
+ watchdog.daemon = True
+ watchdog.start()
+ try:
+ try:
+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):
+ if expired.is_set():
+ raise Auth0ResponseTooSlowError(
+ f"Auth0 response exceeded the {MAX_DOWNLOAD_SECONDS}s download budget; aborting"
+ )
+ yield chunk
+ except (requests.exceptions.RequestException, OSError) as error:
+ if expired.is_set():
+ raise Auth0ResponseTooSlowError(
+ f"Auth0 response exceeded the {MAX_DOWNLOAD_SECONDS}s download budget; aborting"
+ ) from error
+ raise
+ if expired.is_set():
+ raise Auth0ResponseTooSlowError(
+ f"Auth0 response exceeded the {MAX_DOWNLOAD_SECONDS}s download budget; aborting"
+ )
+ finally:
+ watchdog.cancel()
+
+
+def _read_capped_json(response: requests.Response) -> Any:
+ """Parse a streamed JSON response, refusing a body past the size or time budget.
+
+ The domain is customer-supplied, so a body must never be buffered unbounded. ``iter_content``
+ decodes any content-encoding, so the size cap bounds the decompressed body. A watchdog closes
+ the response when the total deadline expires, including while a chunk read is blocked.
+ """
+ chunks: list[bytes] = []
+ total = 0
+ try:
+ for chunk in _iter_response_content(response):
+ if not chunk:
+ continue
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise Auth0ResponseTooLargeError(
+ f"Auth0 response exceeded the {MAX_RESPONSE_BYTES}-byte limit; refusing to buffer it"
+ )
+ chunks.append(chunk)
+ finally:
+ response.close()
+ return json.loads(b"".join(chunks))
+
+
+def _read_body_preview(response: requests.Response) -> str:
+ """Read a bounded prefix of a streamed body for error logging, never buffering it whole."""
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in _iter_response_content(response):
+ if not chunk:
+ continue
+ chunks.append(chunk)
+ total += len(chunk)
+ if total >= _ERROR_BODY_PREVIEW_BYTES:
+ break
+ return b"".join(chunks)[:_ERROR_BODY_PREVIEW_BYTES].decode("utf-8", errors="replace")
+
+
+class Auth0TokenManager:
+ """Mints and caches the Management API access token, re-minting before it expires.
+
+ Auth0 has no interactive step for this: the customer registers a machine-to-machine
+ application in their own tenant and we exchange its client credentials for a token scoped to
+ the Management API audience.
+ """
+
+ def __init__(
+ self, session: requests.Session, domain: str, client_id: str, client_secret: str, api_version: str
+ ) -> None:
+ self._session = session
+ self._domain = normalize_domain(domain)
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._api_version = api_version
+ self._token: Optional[str] = None
+ self._deadline: float = 0.0
+
+ def get_token(self) -> str:
+ if self._token is None or time.monotonic() >= self._deadline - TOKEN_REFRESH_MARGIN_SECONDS:
+ self._mint()
+ assert self._token is not None
+ return self._token
+
+ def _mint(self) -> None:
+ response = self._session.post(
+ f"{_base_url(self._domain)}/oauth/token",
+ json={
+ "grant_type": "client_credentials",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ "audience": management_audience(self._domain, self._api_version),
+ },
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ stream=True,
+ hooks={"response": _reject_redirect_response},
+ )
+
+ try:
+ if response.status_code == 429 or response.status_code >= 500:
+ raise Auth0RetryableError(f"Auth0 token request failed (retryable): status={response.status_code}")
+
+ # A 3xx is not an error status, so reject it explicitly rather than following it to a
+ # potentially internal Location (SSRF).
+ if response.is_redirect or response.is_permanent_redirect:
+ raise Auth0HostNotAllowedError(
+ f"Auth0 returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ response.raise_for_status()
+ payload = _read_capped_json(response)
+ finally:
+ response.close()
+
+ self._token = payload["access_token"]
+ self._deadline = time.monotonic() + float(payload.get("expires_in") or DEFAULT_TOKEN_LIFETIME_SECONDS)
+
+
+def _format_window_value(value: Any) -> str:
+ """Render an incremental watermark as the ISO-8601 instant Auth0's query syntax expects."""
+ if isinstance(value, datetime):
+ instant = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return instant.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return _format_window_value(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ # Double quotes would terminate the quoted Lucene term and let the rest of the value be read
+ # as query syntax, so they never reach the query string.
+ return str(value).replace('"', "")
+
+
+def resolve_window_field(
+ config: Auth0EndpointConfig, should_use_incremental_field: bool, incremental_field: Optional[str]
+) -> Optional[str]:
+ """The field the collection is sorted by and the Lucene window slides on.
+
+ On an incremental run this is the cursor the user picked in the schema settings; on a full
+ refresh it falls back to the endpoint's immutable timestamp so page boundaries stay stable.
+ """
+ if config.window_field is None:
+ return None
+ if not should_use_incremental_field:
+ return config.full_refresh_window_field or config.window_field
+ advertised = {f["field"] for f in config.incremental_fields}
+ if incremental_field in advertised:
+ return incremental_field
+ return config.window_field
+
+
+def _build_params(
+ config: Auth0EndpointConfig,
+ page: int,
+ window_field: Optional[str],
+ window_start: Optional[str],
+) -> dict[str, Any]:
+ if not config.paginated:
+ return {}
+
+ params: dict[str, Any] = {"page": page, "per_page": min(config.page_size, MAX_PAGE_SIZE)}
+ if config.supports_include_totals:
+ params["include_totals"] = "true"
+ if config.search_engine:
+ params["search_engine"] = config.search_engine
+ if window_field:
+ # `:1` is Auth0's ascending sort order. Rows must arrive oldest-first for the pipeline's
+ # watermark to checkpoint per batch and for the window to slide forward.
+ params["sort"] = f"{window_field}:1"
+ if window_start is not None:
+ # Inclusive lower bound: the boundary row is re-read and deduped by the merge on the
+ # primary key, which is cheaper than risking a skipped row on an exclusive bound.
+ params["q"] = f'{window_field}:["{window_start}" TO *]'
+ return params
+
+
+def _build_url(domain: str, config: Auth0EndpointConfig, api_version: str, params: dict[str, Any]) -> str:
+ url = f"{_base_url(domain)}{config.path_template.format(version=api_version)}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params, doseq=True)}"
+
+
+def _extract_rows(data: Any, config: Auth0EndpointConfig) -> list[dict[str, Any]]:
+ if isinstance(data, list):
+ return data
+ if isinstance(data, dict) and config.data_key:
+ rows = data.get(config.data_key)
+ return rows if isinstance(rows, list) else []
+ return []
+
+
+# Top-level fields Auth0 returns alongside each row that carry provider credentials rather than
+# connector metadata. The Management API scopes that grant read access to these collections can
+# also grant read access to these fields (e.g. `read:clients` with `read:client_keys`), so a token
+# a tenant admin considers read-only can still mint rows a warehouse-table reader could use to
+# forge tokens or reach a connected provider directly. Disabling HTTP sample capture (see
+# `capture_samples`) only keeps raw responses out of the captured-sample store; it does not touch
+# these columns once extracted, so every endpoint that can carry one is listed here instead.
+CREDENTIAL_FIELDS_BY_ENDPOINT: dict[str, tuple[str, ...]] = {
+ # Sink config carries the destination's own credential, e.g. `httpAuthorization`,
+ # `datadogApiKey`, or `splunkToken`.
+ "log_streams": ("sink",),
+ # HS256 APIs return their signing key through this collection.
+ "resource_servers": ("signing_secret",),
+ # `client_secret`/`signing_keys` are the application's own credentials; `addons` carries
+ # per-connector provider credentials (e.g. `addons.azure_blob.storageAccessKey`,
+ # `addons.firebase.private_key`) under keys this connector cannot enumerate in advance, so the
+ # whole object is dropped rather than allowlisting individual providers.
+ "clients": ("client_secret", "signing_keys", "addons"),
+ # `options` carries the identity provider's own credentials (e.g. `clientSecret` for
+ # OIDC/social strategies, SAML signing certs, AD/ADFS `provisioning_secret`) under keys that
+ # vary by strategy, so the whole object is dropped rather than allowlisting individual
+ # providers.
+ "connections": ("options",),
+}
+
+# Credential fields nested inside each item of an array field, keyed by endpoint then array
+# field name. `read:user_idp_tokens` returns the linked identity provider's own access and
+# refresh tokens inside every `users` row's `identities` entries, letting a reader of the synced
+# table call those providers' APIs as the user without the source's own credentials.
+NESTED_CREDENTIAL_FIELDS_BY_ENDPOINT: dict[str, dict[str, tuple[str, ...]]] = {
+ "users": {"identities": ("access_token", "access_token_secret", "refresh_token")},
+}
+
+
+def _strip_nested_credential_fields(row: dict[str, Any], endpoint: str) -> dict[str, Any]:
+ nested = NESTED_CREDENTIAL_FIELDS_BY_ENDPOINT.get(endpoint)
+ if not nested:
+ return row
+ result = dict(row)
+ for array_field, fields in nested.items():
+ items = result.get(array_field)
+ if not isinstance(items, list):
+ continue
+ result[array_field] = [
+ {key: value for key, value in item.items() if key not in fields} if isinstance(item, dict) else item
+ for item in items
+ ]
+ return result
+
+
+def _strip_credential_fields(rows: list[dict[str, Any]], endpoint: str) -> list[dict[str, Any]]:
+ fields = CREDENTIAL_FIELDS_BY_ENDPOINT.get(endpoint)
+ rows = [{key: value for key, value in row.items() if key not in fields} for row in rows] if fields else list(rows)
+ if endpoint in NESTED_CREDENTIAL_FIELDS_BY_ENDPOINT:
+ rows = [_strip_nested_credential_fields(row, endpoint) for row in rows]
+ return rows
+
+
+def _max_window_value(rows: list[dict[str, Any]], window_field: str) -> Optional[str]:
+ """Newest window-field value on a page.
+
+ Auth0 renders both `updated_at` and `date` as fixed-width ISO-8601 UTC instants, so string
+ ordering matches chronological ordering. Rows arrive ascending, but the maximum is taken
+ explicitly rather than trusting the last row.
+ """
+ values = [str(row[window_field]) for row in rows if isinstance(row, dict) and row.get(window_field)]
+ return max(values) if values else None
+
+
+def validate_credentials(
+ domain: str,
+ client_id: str,
+ client_secret: str,
+ api_version: str,
+ schema_name: Optional[str] = None,
+ team_id: Optional[int] = None,
+) -> tuple[bool, str | None]:
+ """Mint a Management API token to confirm the machine-to-machine credentials are genuine.
+
+ Auth0 grants scopes per collection, so an application may legitimately lack access to
+ endpoints the user never intends to sync — at source-create (``schema_name is None``) a
+ successful token exchange is enough. A scoped probe (``schema_name`` set) additionally
+ requests the collection and treats a denial as a hard failure, naming the missing scope.
+ """
+ normalized = normalize_domain(domain)
+ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):
+ return False, "Invalid Auth0 domain"
+
+ # The domain is fully customer-controlled, so block one resolving to a private/internal
+ # address (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(normalized, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ # capture=False keeps the minted token (returned in the body) and any probed row content out
+ # of opt-in HTTP sample capture — the name-based scrubbers cannot recognise either.
+ session = make_tracked_session(capture=False, redact_values=(client_secret,))
+ token_manager = Auth0TokenManager(session, normalized, client_id, client_secret, api_version)
+ try:
+ token = token_manager.get_token()
+ except Auth0HostNotAllowedError:
+ return False, HOST_NOT_ALLOWED_ERROR
+ except requests.HTTPError as e:
+ if e.response is not None and e.response.status_code in (401, 403):
+ return False, "Invalid Auth0 client ID or client secret"
+ return False, str(e)
+ except (Auth0RetryableError, requests.exceptions.RequestException) as e:
+ return False, str(e)
+
+ if schema_name is None:
+ return True, None
+
+ config = AUTH0_ENDPOINTS[schema_name]
+ probe_params = {"page": 0, "per_page": 1} if config.paginated else {}
+ try:
+ # Stream and close without touching the body — the probe only needs the status, and a
+ # customer-controlled server must not get to buffer an unbounded body at source-create.
+ response = session.get(
+ _build_url(normalized, config, api_version, probe_params),
+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
+ timeout=10,
+ allow_redirects=False,
+ stream=True,
+ hooks={"response": _reject_redirect_response},
+ )
+ try:
+ is_redirect = response.is_redirect or response.is_permanent_redirect
+ status_code = response.status_code
+ finally:
+ response.close()
+ except Auth0HostNotAllowedError:
+ return False, HOST_NOT_ALLOWED_ERROR
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if is_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if status_code == 200:
+ return True, None
+
+ if status_code in (401, 403):
+ return False, f"Your Auth0 application is missing the `{config.required_scope}` scope for {schema_name}"
+
+ return False, f"Auth0 returned status {status_code} for {schema_name}"
+
+
+def get_rows(
+ domain: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[Auth0ResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = AUTH0_ENDPOINTS[endpoint]
+
+ # Re-check at run time (not just at source-create) in case the domain was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(normalize_domain(domain), team_id)
+ if not host_ok:
+ raise Auth0HostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ # The token exchange returns the credential in its body, which the name-based sample
+ # scrubbers cannot recognise, so it never enters sample capture. The data session is reused
+ # across pages so urllib3 keeps the connection alive.
+ token_manager = Auth0TokenManager(
+ make_tracked_session(capture=False, redact_values=(client_secret,)),
+ domain,
+ client_id,
+ client_secret,
+ api_version,
+ )
+ session = make_tracked_session(capture=config.capture_samples, redact_values=(client_secret,))
+
+ def fetch(url: str) -> Any:
+ # The tracked session already retries 429 and transient 5xx honoring Retry-After, which
+ # is what Auth0's rate limiter returns — no second retry layer here.
+ headers = {"Authorization": f"Bearer {token_manager.get_token()}", "Accept": "application/json"}
+ response = session.get(
+ url,
+ headers=headers,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ stream=True,
+ hooks={"response": _reject_redirect_response},
+ )
+ try:
+ if response.is_redirect or response.is_permanent_redirect:
+ raise Auth0HostNotAllowedError(
+ f"Auth0 returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+ if not response.ok:
+ logger.error(
+ f"Auth0 API error: status={response.status_code}, body={_read_body_preview(response)}, url={url}"
+ )
+ response.raise_for_status()
+ return _read_capped_json(response)
+ finally:
+ response.close()
+
+ if not config.paginated:
+ data = fetch(_build_url(domain, config, api_version, {}))
+ rows = _strip_credential_fields(_extract_rows(data, config), endpoint)
+ if rows:
+ yield rows
+ return
+
+ window_field = resolve_window_field(config, should_use_incremental_field, incremental_field)
+ window_start: Optional[str] = None
+ if window_field and should_use_incremental_field and db_incremental_field_last_value:
+ window_start = _format_window_value(db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = 0
+ if resume_config is not None:
+ page = resume_config.page
+ window_start = resume_config.window_start
+ logger.debug(f"Auth0: resuming {endpoint} from page {page} of window {window_start}")
+
+ pages_fetched = 0
+ while True:
+ if pages_fetched >= MAX_PAGES:
+ raise Auth0PaginationLimitError(
+ f"Auth0 pagination for {endpoint} exceeded {MAX_PAGES} pages without terminating"
+ )
+
+ data = fetch(_build_url(domain, config, api_version, _build_params(config, page, window_field, window_start)))
+ pages_fetched += 1
+
+ rows = _strip_credential_fields(_extract_rows(data, config), endpoint)
+ if not rows:
+ break
+
+ next_page = page + 1
+ total = data.get("total") if isinstance(data, dict) else None
+ is_last_page = (isinstance(total, int) and next_page * config.page_size >= total) or (
+ len(rows) < config.page_size
+ )
+
+ next_window_start = window_start
+ if not is_last_page and window_field and next_page * config.page_size >= SEARCH_RESULT_CAP:
+ # Auth0 refuses to page past the first 1000 matches, so restart at page 0 with the
+ # window's lower bound moved up to the newest row seen.
+ newest = _max_window_value(rows, window_field)
+ if newest is None:
+ raise Auth0PaginationStalledError(
+ f"{PAGINATION_STALLED_ERROR}: {endpoint} rows carry no `{window_field}` value to slide on"
+ )
+ if newest == window_start:
+ raise Auth0PaginationStalledError(
+ f"{PAGINATION_STALLED_ERROR}: more than {SEARCH_RESULT_CAP} {endpoint} rows share "
+ f"`{window_field}` = {newest}"
+ )
+ next_window_start = newest
+ next_page = 0
+
+ if not is_last_page:
+ # Save BEFORE yielding so the state already covers this page once the pipeline commits
+ # it; a worker shutdown right after the yield then resumes from the next page instead
+ # of silently re-reading (and, for a full refresh, duplicating) this one.
+ resumable_source_manager.save_state(Auth0ResumeConfig(page=next_page, window_start=next_window_start))
+
+ yield rows
+
+ if is_last_page:
+ break
+
+ page = next_page
+ window_start = next_window_start
+
+
+def auth0_source(
+ domain: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[Auth0ResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = AUTH0_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ domain=domain,
+ client_id=client_id,
+ client_secret=client_secret,
+ endpoint=endpoint,
+ api_version=api_version,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[config.primary_key],
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ # Every windowed collection is requested with `sort=<field>:1`, so rows arrive oldest
+ # first and the watermark advances correctly.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/canonical_descriptions.py
new file mode 100644
index 000000000000..d17415103592
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/canonical_descriptions.py
@@ -0,0 +1,157 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "users": {
+ "description": "End users of the Auth0 tenant, across every enabled connection (database, social, and enterprise).",
+ "docs_url": "https://auth0.com/docs/api/management/v2/users/get-users",
+ "columns": {
+ "user_id": "Unique identifier of the user, prefixed with the connection strategy (e.g. auth0|abc123).",
+ "email": "Email address of the user.",
+ "email_verified": "Whether the user has verified their email address.",
+ "username": "Username of the user, for connections that enable usernames.",
+ "phone_number": "Phone number of the user, for SMS connections.",
+ "phone_verified": "Whether the user has verified their phone number.",
+ "name": "Full name of the user from the identity provider profile.",
+ "nickname": "Preferred nickname or username from the identity provider profile.",
+ "given_name": "Given (first) name of the user.",
+ "family_name": "Family (last) name of the user.",
+ "picture": "URL of the user's profile picture.",
+ "created_at": "Timestamp of when the user profile was first created.",
+ "updated_at": "Timestamp of the most recent change to the user profile.",
+ "last_login": "Timestamp of the user's most recent successful login.",
+ "last_ip": "IP address the user most recently logged in from.",
+ "logins_count": "Total number of times the user has logged in.",
+ "identities": "Linked identity provider accounts for this user, each with its provider, connection, and user_id.",
+ "app_metadata": "Application data about the user that the user cannot edit, such as roles or plan.",
+ "user_metadata": "User-editable profile data, such as preferences.",
+ "blocked": "Whether the user has been blocked from signing in.",
+ "multifactor": "Multi-factor authentication providers enrolled for the user.",
+ },
+ },
+ "logs": {
+ "description": "Tenant log events, covering authentication attempts, Management API calls, and administrative changes. Retention depends on the Auth0 subscription.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/logs/get-logs",
+ "columns": {
+ "log_id": "Unique identifier of the log event.",
+ "date": "Timestamp of when the event occurred.",
+ "type": "Short event type code (e.g. s for successful login, f for failed login).",
+ "description": "Human-readable description of the event.",
+ "client_id": "Identifier of the application the event relates to.",
+ "client_name": "Name of the application the event relates to.",
+ "ip": "IP address the request originated from.",
+ "user_agent": "User agent string of the client that made the request.",
+ "user_id": "Identifier of the user the event relates to, when there is one.",
+ "user_name": "Username or email of the user the event relates to.",
+ "connection": "Name of the connection used for the authentication attempt.",
+ "connection_id": "Identifier of the connection used for the authentication attempt.",
+ "audience": "API audience requested by the authentication attempt.",
+ "scope": "Scopes requested by the authentication attempt.",
+ "strategy": "Connection strategy used (e.g. auth0, google-oauth2, samlp).",
+ "hostname": "Auth0 hostname that served the request.",
+ "location_info": "Geographic information derived from the request IP address.",
+ "details": "Event-specific payload, including the request and response when available.",
+ },
+ },
+ "clients": {
+ "description": "Applications registered in the tenant, each representing something that authenticates users through Auth0.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/clients/get-clients",
+ "columns": {
+ "client_id": "Unique identifier of the application.",
+ "name": "Display name of the application.",
+ "description": "Free-text description of the application.",
+ "app_type": "Application type (e.g. spa, native, regular_web, non_interactive).",
+ "is_first_party": "Whether the application belongs to the tenant owner rather than a third party.",
+ "oidc_conformant": "Whether the application uses the OIDC-conformant authentication pipeline.",
+ "callbacks": "Allowed callback URLs the authorization response may be redirected to.",
+ "allowed_origins": "Origins allowed to make cross-origin authentication requests.",
+ "web_origins": "Origins allowed to use cross-origin authentication and silent authentication.",
+ "allowed_logout_urls": "URLs a user may be redirected to after logging out.",
+ "grant_types": "OAuth grant types the application is allowed to use.",
+ "jwt_configuration": "Token lifetime and signing algorithm used for this application's ID tokens.",
+ "token_endpoint_auth_method": "How the application authenticates against the token endpoint.",
+ "sso": "Whether single sign-on is enabled for the application.",
+ "logo_uri": "URL of the application's logo, shown on the login page.",
+ },
+ },
+ "connections": {
+ "description": "Identity sources enabled in the tenant, such as database, social, and enterprise connections.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/connections/get-connections",
+ "columns": {
+ "id": "Unique identifier of the connection.",
+ "name": "Name of the connection.",
+ "display_name": "Name shown to users on the login page.",
+ "strategy": "Connection strategy (e.g. auth0, google-oauth2, samlp, ad).",
+ "options": "Strategy-specific configuration for the connection, including its provider settings.",
+ "enabled_clients": "Identifiers of the applications this connection is enabled for.",
+ "realms": "Realms the connection serves, used for home realm discovery.",
+ "is_domain_connection": "Whether the connection is a domain-level connection for organizations.",
+ "metadata": "Custom key-value metadata attached to the connection.",
+ },
+ },
+ "roles": {
+ "description": "Roles defined in the tenant's role-based access control settings.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/roles/get-roles",
+ "columns": {
+ "id": "Unique identifier of the role.",
+ "name": "Name of the role.",
+ "description": "Free-text description of what the role grants.",
+ },
+ },
+ "organizations": {
+ "description": "Organizations in the tenant, used to represent business customers and partners in a B2B setup.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/organizations/get-organizations",
+ "columns": {
+ "id": "Unique identifier of the organization.",
+ "name": "Machine-readable name of the organization.",
+ "display_name": "Name of the organization shown to users.",
+ "branding": "Login page branding for the organization, such as its logo and colors.",
+ "metadata": "Custom key-value metadata attached to the organization.",
+ },
+ },
+ "resource_servers": {
+ "description": "APIs registered in the tenant, each defining an audience that access tokens can be issued for.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/resource-servers/get-resource-servers",
+ "columns": {
+ "id": "Unique identifier of the API.",
+ "name": "Display name of the API.",
+ "identifier": "Audience value used when requesting access tokens for this API.",
+ "scopes": "Permissions defined on the API, each with a value and description.",
+ "signing_alg": "Algorithm used to sign access tokens issued for this API.",
+ "token_lifetime": "Lifetime in seconds of access tokens issued for this API.",
+ "allow_offline_access": "Whether refresh tokens can be issued for this API.",
+ "skip_consent_for_verifiable_first_party_clients": "Whether first-party applications skip the consent prompt.",
+ "enforce_policies": "Whether role-based access control policies are enforced for this API.",
+ },
+ },
+ "actions": {
+ "description": "Actions defined in the tenant: custom Node.js functions bound to points in the Auth0 authentication and authorization pipelines.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/actions/get-actions",
+ "columns": {
+ "id": "Unique identifier of the action.",
+ "name": "Name of the action.",
+ "supported_triggers": "Pipeline triggers the action can be bound to, with their versions.",
+ "created_at": "Timestamp of when the action was created.",
+ "updated_at": "Timestamp of the most recent change to the action.",
+ "dependencies": "npm packages the action's code depends on.",
+ "secrets": "Names of the secrets configured for the action; values are not returned.",
+ "runtime": "Node.js runtime the action executes on.",
+ "status": "Build status of the action's most recent version.",
+ "all_changes_deployed": "Whether every change to the action has been deployed.",
+ "deployed_version": "The action version currently deployed.",
+ },
+ },
+ "log_streams": {
+ "description": "Log streams configured in the tenant, each forwarding tenant log events to an external sink.",
+ "docs_url": "https://auth0.com/docs/api/management/v2/log-streams/get-log-streams",
+ "columns": {
+ "id": "Unique identifier of the log stream.",
+ "name": "Name of the log stream.",
+ "type": "Sink type the stream delivers to (e.g. http, datadog, eventbridge, splunk).",
+ "status": "Delivery status of the stream (active, paused, or suspended).",
+ "sink": "Sink-specific delivery configuration for the stream.",
+ "filters": "Event categories the stream is limited to, when filtering is configured.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/settings.py
new file mode 100644
index 000000000000..1cea57caf448
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/settings.py
@@ -0,0 +1,133 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Auth0 refuses to page past the first 1000 results of a searchable collection, so the
+# endpoints that expose a searchable timestamp walk history in windows: once a window is
+# exhausted the Lucene `q` lower bound moves to the newest row seen and paging restarts.
+SEARCH_RESULT_CAP = 1000
+
+DEFAULT_PAGE_SIZE = 100
+
+# The Management API caps `per_page` at 100 on every collection that accepts it.
+MAX_PAGE_SIZE = 100
+
+
+@dataclass(frozen=True)
+class Auth0EndpointConfig:
+ name: str
+ # Formatted with the resolved vendor API version, so the version pin lives on the source
+ # class rather than being hardcoded in the request layer.
+ path_template: str
+ # Key the rows sit under in the response envelope. None means the endpoint returns a bare
+ # JSON array and takes no pagination parameters.
+ data_key: Optional[str] = None
+ primary_key: str = "id"
+ page_size: int = DEFAULT_PAGE_SIZE
+ # Only the collections that document `include_totals` accept it; the Actions API always
+ # returns its own totals envelope instead.
+ supports_include_totals: bool = True
+ # Field the window slides on and the collection is sorted by. Set only for the two
+ # collections whose Lucene query syntax documents a date range filter.
+ window_field: Optional[str] = None
+ # Window field used when the run is a full refresh: an immutable timestamp keeps page
+ # boundaries stable while paging, which `updated_at` cannot guarantee.
+ full_refresh_window_field: Optional[str] = None
+ # Auth0's user search needs the engine pinned; the logs endpoint has no such parameter.
+ search_engine: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable (never-rewritten) timestamp column used to partition the delta table.
+ partition_key: Optional[str] = None
+ # Whether responses may enter opt-in HTTP sample capture. Off wherever the body carries
+ # end-user PII or tenant credentials (connection secrets, log stream sink keys) that the
+ # name-based sample scrubbers cannot recognise.
+ capture_samples: bool = False
+ # Management API scope the token must carry, surfaced when a scoped probe is denied.
+ required_scope: str = ""
+
+ @property
+ def paginated(self) -> bool:
+ return self.data_key is not None
+
+
+AUTH0_ENDPOINTS: dict[str, Auth0EndpointConfig] = {
+ "users": Auth0EndpointConfig(
+ name="users",
+ path_template="/api/{version}/users",
+ data_key="users",
+ primary_key="user_id",
+ window_field="updated_at",
+ full_refresh_window_field="created_at",
+ search_engine="v3",
+ incremental_fields=[incremental_field("updated_at"), incremental_field("created_at")],
+ partition_key="created_at",
+ required_scope="read:users",
+ ),
+ "logs": Auth0EndpointConfig(
+ name="logs",
+ path_template="/api/{version}/logs",
+ data_key="logs",
+ primary_key="log_id",
+ window_field="date",
+ full_refresh_window_field="date",
+ incremental_fields=[incremental_field("date")],
+ partition_key="date",
+ required_scope="read:logs",
+ ),
+ "clients": Auth0EndpointConfig(
+ name="clients",
+ path_template="/api/{version}/clients",
+ data_key="clients",
+ primary_key="client_id",
+ required_scope="read:clients",
+ ),
+ "connections": Auth0EndpointConfig(
+ name="connections",
+ path_template="/api/{version}/connections",
+ data_key="connections",
+ required_scope="read:connections",
+ ),
+ "roles": Auth0EndpointConfig(
+ name="roles",
+ path_template="/api/{version}/roles",
+ data_key="roles",
+ capture_samples=True,
+ required_scope="read:roles",
+ ),
+ "organizations": Auth0EndpointConfig(
+ name="organizations",
+ path_template="/api/{version}/organizations",
+ data_key="organizations",
+ capture_samples=True,
+ required_scope="read:organizations",
+ ),
+ "resource_servers": Auth0EndpointConfig(
+ name="resource_servers",
+ path_template="/api/{version}/resource-servers",
+ data_key="resource_servers",
+ required_scope="read:resource_servers",
+ ),
+ "actions": Auth0EndpointConfig(
+ name="actions",
+ path_template="/api/{version}/actions/actions",
+ data_key="actions",
+ supports_include_totals=False,
+ capture_samples=True,
+ required_scope="read:actions",
+ ),
+ "log_streams": Auth0EndpointConfig(
+ name="log_streams",
+ path_template="/api/{version}/log-streams",
+ required_scope="read:log_streams",
+ ),
+}
+
+ENDPOINTS = tuple(AUTH0_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in AUTH0_ENDPOINTS.items()
+}
+
+REQUIRED_SCOPES: dict[str, str] = {name: config.required_scope for name, config in AUTH0_ENDPOINTS.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/source.py
index 3b7534c7863a..055ca2fca3f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/source.py
@@ -1,25 +1,165 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.auth0 import (
+ HOST_NOT_ALLOWED_ERROR,
+ PAGINATION_STALLED_ERROR,
+ Auth0ResumeConfig,
+ auth0_source,
+ validate_credentials as validate_auth0_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.settings import (
+ 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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.auth0 import Auth0SourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class Auth0Source(SimpleSource[Auth0SourceConfig]):
+class Auth0Source(ResumableSource[Auth0SourceConfig, Auth0ResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://auth0.com/docs/api/management/v2"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AUTH0
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `auth0_domain` is where the stored client secret is sent; retargeting it must re-require it.
+ return ["auth0_domain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AUTH0,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Auth0",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["okta", "identity", "sso", "authentication", "ciam"],
+ caption="""Enter your Auth0 tenant domain and a machine-to-machine application's credentials to pull your users, tenant logs, and tenant configuration into the PostHog Data warehouse.
+
+In the Auth0 dashboard go to **Applications > Applications**, create a **Machine to Machine** application, and authorize it for the **Auth0 Management API**. Grant the read scopes for the tables you want to sync: `read:users`, `read:logs`, `read:clients`, `read:connections`, `read:roles`, `read:organizations`, `read:resource_servers`, `read:actions`, `read:log_streams`.
+
+Use your canonical tenant domain (for example `your-tenant.us.auth0.com`), not a custom domain. Auth0 only issues Management API tokens for the canonical one.""",
iconPath="/static/services/auth0.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/auth0",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="auth0_domain",
+ label="Auth0 domain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your-tenant.us.auth0.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Auth0 rejected the credentials. Check the machine-to-machine application's client ID and secret, then reconnect.",
+ "403 Client Error": "Your Auth0 application is missing a read scope for this table. Grant it on the Management API and try again.",
+ HOST_NOT_ALLOWED_ERROR: "The Auth0 domain is not allowed. Use your tenant's canonical Auth0 domain.",
+ PAGINATION_STALLED_ERROR: "Auth0 could not page past its 1000-result limit because too many rows share the same timestamp.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: Auth0SourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # Users are mutable and the window's inclusive lower bound re-reads its boundary rows, so
+ # merge is the only safe incremental mode — append would duplicate rows.
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)
+
+ def validate_credentials(
+ self,
+ config: Auth0SourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_auth0_credentials(
+ domain=config.auth0_domain,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ api_version=self.resolve_api_version(api_version),
+ schema_name=schema_name,
+ team_id=team_id,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[Auth0ResumeConfig]:
+ return ResumableSourceManager[Auth0ResumeConfig](inputs, Auth0ResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: Auth0SourceConfig,
+ resumable_source_manager: ResumableSourceManager[Auth0ResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return auth0_source(
+ domain=config.auth0_domain,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field=inputs.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/auth0/tests/test_auth0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/tests/test_auth0.py
new file mode 100644
index 000000000000..a01d5fbb61ae
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/tests/test_auth0.py
@@ -0,0 +1,691 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0 import auth0 as auth0_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.auth0 import (
+ Auth0HostNotAllowedError,
+ Auth0PaginationLimitError,
+ Auth0PaginationStalledError,
+ Auth0ResponseTooLargeError,
+ Auth0ResponseTooSlowError,
+ Auth0ResumeConfig,
+ Auth0RetryableError,
+ Auth0TokenManager,
+ _build_params,
+ _build_url,
+ _format_window_value,
+ _max_window_value,
+ _reject_redirect_response,
+ auth0_source,
+ get_rows,
+ management_audience,
+ normalize_domain,
+ resolve_window_field,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.settings import AUTH0_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+DOMAIN = "tenant.us.auth0.com"
+TOKEN_JSON = {"access_token": "tok", "expires_in": 86400, "token_type": "Bearer"}
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ 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 = text
+ body = json.dumps(json_data).encode() if json_data is not None else text.encode()
+ # Bodies are read via stream=True + iter_content, so serve them in that shape. A fresh
+ # iterator per call lets one mock response stand in for repeated reads.
+ response.iter_content.side_effect = lambda *args, **kwargs: iter([body] if body else [])
+ if status_code >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status_code} Client Error: for url: https://{DOMAIN}", response=response
+ )
+ return response
+
+
+def _token_session() -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.post.return_value = _response(json_data=TOKEN_JSON)
+ return session
+
+
+def _data_session(get_responses: list[Any]) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.get.side_effect = get_responses
+ return session
+
+
+def _requested_params(session: mock.MagicMock, index: int) -> dict[str, list[str]]:
+ return parse_qs(urlsplit(session.get.call_args_list[index].args[0]).query)
+
+
+def _user_rows(count: int, updated_at: str, start: int = 0) -> list[dict[str, Any]]:
+ return [{"user_id": f"auth0|{start + i}", "updated_at": updated_at} for i in range(count)]
+
+
+class FakeResumeManager(ResumableSourceManager[Auth0ResumeConfig]):
+ """In-memory stand-in for the Redis-backed manager."""
+
+ def __init__(self, state: Optional[Auth0ResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[Auth0ResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[Auth0ResumeConfig]:
+ return self.state
+
+ def save_state(self, data: Auth0ResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestNormalizeDomain:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("tenant.us.auth0.com", "tenant.us.auth0.com"),
+ ("https://tenant.us.auth0.com", "tenant.us.auth0.com"),
+ ("http://tenant.us.auth0.com/", "tenant.us.auth0.com"),
+ (" tenant.us.auth0.com ", "tenant.us.auth0.com"),
+ ("tenant.us.auth0.com/api/v2", "tenant.us.auth0.com"),
+ ("https://tenant.eu.auth0.com/api/v2/users", "tenant.eu.auth0.com"),
+ ],
+ )
+ def test_normalize(self, raw: str, expected: str) -> None:
+ assert normalize_domain(raw) == expected
+
+ def test_audience_is_the_management_api_identifier(self) -> None:
+ assert management_audience("https://tenant.us.auth0.com/", "v2") == "https://tenant.us.auth0.com/api/v2/"
+
+
+class TestFormatWindowValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("2026-03-04T02:58:14.000Z", "2026-03-04T02:58:14.000Z"),
+ ],
+ )
+ def test_format(self, value: Any, expected: str) -> None:
+ assert _format_window_value(value) == expected
+
+ def test_double_quotes_cannot_escape_the_lucene_term(self) -> None:
+ assert _format_window_value('2026-01-01" TO *] OR user_id:*') == "2026-01-01 TO *] OR user_id:*"
+
+
+class TestResolveWindowField:
+ @pytest.mark.parametrize(
+ "endpoint, should_use_incremental_field, incremental_field, expected",
+ [
+ ("users", True, "updated_at", "updated_at"),
+ ("users", True, "created_at", "created_at"),
+ # An unadvertised cursor never reaches the query string; fall back to the default.
+ ("users", True, "last_login", "updated_at"),
+ ("users", True, None, "updated_at"),
+ # Full refresh sorts on the immutable column so page boundaries stay stable.
+ ("users", False, None, "created_at"),
+ ("logs", True, "date", "date"),
+ ("logs", False, None, "date"),
+ ("clients", True, "created_at", None),
+ ("log_streams", False, None, None),
+ ],
+ )
+ def test_resolve(
+ self,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ expected: Optional[str],
+ ) -> None:
+ resolved = resolve_window_field(AUTH0_ENDPOINTS[endpoint], should_use_incremental_field, incremental_field)
+ assert resolved == expected
+
+
+class TestBuildParams:
+ def test_users_incremental_window_filters_and_sorts_ascending(self) -> None:
+ params = _build_params(AUTH0_ENDPOINTS["users"], page=0, window_field="updated_at", window_start="2024-01-01")
+ assert params["q"] == 'updated_at:["2024-01-01" TO *]'
+ assert params["sort"] == "updated_at:1"
+ assert params["include_totals"] == "true"
+ assert params["search_engine"] == "v3"
+ assert params["per_page"] == 100
+
+ def test_first_window_sorts_but_does_not_filter(self) -> None:
+ params = _build_params(AUTH0_ENDPOINTS["users"], page=3, window_field="updated_at", window_start=None)
+ assert "q" not in params
+ assert params["sort"] == "updated_at:1"
+ assert params["page"] == 3
+
+ @pytest.mark.parametrize("endpoint", ["clients", "connections", "roles", "organizations", "resource_servers"])
+ def test_plain_collections_send_no_search_params(self, endpoint: str) -> None:
+ params = _build_params(AUTH0_ENDPOINTS[endpoint], page=0, window_field=None, window_start=None)
+ assert "q" not in params
+ assert "sort" not in params
+ assert "search_engine" not in params
+ assert params["include_totals"] == "true"
+
+ def test_actions_omits_include_totals(self) -> None:
+ # The Actions API returns its own totals envelope and does not document include_totals.
+ params = _build_params(AUTH0_ENDPOINTS["actions"], page=0, window_field=None, window_start=None)
+ assert "include_totals" not in params
+ assert params["page"] == 0
+
+ def test_unpaginated_endpoint_sends_no_params(self) -> None:
+ assert _build_params(AUTH0_ENDPOINTS["log_streams"], page=0, window_field=None, window_start=None) == {}
+
+ def test_build_url_applies_the_resolved_api_version(self) -> None:
+ url = _build_url(DOMAIN, AUTH0_ENDPOINTS["actions"], "v2", {})
+ assert url == f"https://{DOMAIN}/api/v2/actions/actions"
+
+
+class TestMaxWindowValue:
+ def test_takes_the_maximum_not_the_last_row(self) -> None:
+ rows = [{"updated_at": "2024-01-02T00:00:00.000Z"}, {"updated_at": "2024-01-01T00:00:00.000Z"}]
+ assert _max_window_value(rows, "updated_at") == "2024-01-02T00:00:00.000Z"
+
+ @pytest.mark.parametrize("rows", [[], [{"updated_at": None}], [{"user_id": "auth0|1"}]])
+ def test_missing_values_yield_none(self, rows: list[dict[str, Any]]) -> None:
+ assert _max_window_value(rows, "updated_at") is None
+
+
+class TestTokenManager:
+ def test_mints_once_and_caches(self) -> None:
+ session = _token_session()
+ manager = Auth0TokenManager(session, DOMAIN, "cid", "secret", "v2")
+
+ assert manager.get_token() == "tok"
+ assert manager.get_token() == "tok"
+ assert session.post.call_count == 1
+
+ body = session.post.call_args.kwargs["json"]
+ assert body["grant_type"] == "client_credentials"
+ assert body["audience"] == f"https://{DOMAIN}/api/v2/"
+ assert session.post.call_args.kwargs["allow_redirects"] is False
+ assert session.post.call_args.kwargs["hooks"] == {"response": _reject_redirect_response}
+
+ def test_re_mints_once_the_token_expires(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _response(json_data={"access_token": "first", "expires_in": 1}),
+ _response(json_data={"access_token": "second", "expires_in": 86400}),
+ ]
+ manager = Auth0TokenManager(session, DOMAIN, "cid", "secret", "v2")
+
+ assert manager.get_token() == "first"
+ # A 1s lifetime is already inside the refresh margin, so the next call re-mints.
+ assert manager.get_token() == "second"
+ assert session.post.call_count == 2
+
+ @pytest.mark.parametrize("status_code", [429, 500, 503])
+ def test_transient_token_failures_are_retryable(self, status_code: int) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(status_code=status_code)
+ manager = Auth0TokenManager(session, DOMAIN, "cid", "secret", "v2")
+
+ with pytest.raises(Auth0RetryableError):
+ manager.get_token()
+
+ def test_redirected_token_endpoint_is_refused(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(status_code=302)
+ manager = Auth0TokenManager(session, DOMAIN, "cid", "secret", "v2")
+
+ with pytest.raises(Auth0HostNotAllowedError):
+ manager.get_token()
+
+ def test_oversized_token_body_is_refused(self) -> None:
+ session = mock.MagicMock()
+ response = _response(json_data=TOKEN_JSON)
+ response.iter_content.side_effect = lambda *args, **kwargs: iter([b"x" * 1024])
+ session.post.return_value = response
+ manager = Auth0TokenManager(session, DOMAIN, "cid", "secret", "v2")
+
+ with mock.patch.object(auth0_module, "MAX_RESPONSE_BYTES", 16):
+ with pytest.raises(Auth0ResponseTooLargeError):
+ manager.get_token()
+
+ def test_download_deadline_closes_a_blocked_response(self) -> None:
+ class ImmediateTimer:
+ daemon = False
+
+ def __init__(self, interval: float, callback: Any) -> None:
+ self.callback = callback
+
+ def start(self) -> None:
+ self.callback()
+
+ def cancel(self) -> None:
+ pass
+
+ session = _token_session()
+ manager = Auth0TokenManager(session, DOMAIN, "cid", "secret", "v2")
+
+ with mock.patch.object(auth0_module.threading, "Timer", ImmediateTimer):
+ with pytest.raises(Auth0ResponseTooSlowError):
+ manager.get_token()
+
+ session.post.return_value.close.assert_called()
+
+ def test_redirect_hook_closes_before_raising(self) -> None:
+ response = _response(status_code=302)
+
+ with pytest.raises(Auth0HostNotAllowedError):
+ _reject_redirect_response(response)
+
+ response.close.assert_called_once()
+
+
+class TestGetRows:
+ def _run(
+ self,
+ endpoint: str,
+ get_responses: list[Any],
+ manager: Optional[FakeResumeManager] = None,
+ **kwargs: Any,
+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock, FakeResumeManager]:
+ manager = manager or FakeResumeManager()
+ data_session = _data_session(get_responses)
+ with (
+ mock.patch.object(auth0_module, "_is_host_safe", return_value=(True, None)),
+ mock.patch.object(auth0_module, "make_tracked_session", side_effect=[_token_session(), data_session]),
+ ):
+ batches = list(
+ get_rows(
+ domain=DOMAIN,
+ client_id="cid",
+ client_secret="secret",
+ endpoint=endpoint,
+ api_version="v2",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ **kwargs,
+ )
+ )
+ return batches, data_session, manager
+
+ def test_log_streams_omit_sink_credentials(self) -> None:
+ rows = [
+ {
+ "id": "lst_1",
+ "type": "http",
+ "sink": {
+ "httpEndpoint": "https://example.com/logs",
+ "httpAuthorization": "Bearer secret",
+ "httpCustomHeaders": [{"header": "X-Api-Key", "value": "secret"}],
+ },
+ }
+ ]
+ batches, session, manager = self._run("log_streams", [_response(json_data=rows)])
+
+ assert batches == [[{"id": "lst_1", "type": "http"}]]
+ assert session.get.call_count == 1
+ assert manager.saved == []
+ assert session.get.call_args.kwargs["hooks"] == {"response": _reject_redirect_response}
+
+ def test_resource_servers_omit_signing_secret(self) -> None:
+ page = {"resource_servers": [{"id": "rs_1", "identifier": "https://api.example.com", "signing_secret": "shh"}]}
+ batches, _, _ = self._run("resource_servers", [_response(json_data=page)])
+
+ assert batches == [[{"id": "rs_1", "identifier": "https://api.example.com"}]]
+
+ def test_clients_omit_credential_fields(self) -> None:
+ page = {
+ "clients": [
+ {
+ "client_id": "cid_1",
+ "name": "My App",
+ "client_secret": "shh",
+ "signing_keys": [{"cert": "..."}],
+ "addons": {"azure_blob": {"storageAccessKey": "shh"}},
+ }
+ ]
+ }
+ batches, _, _ = self._run("clients", [_response(json_data=page)])
+
+ assert batches == [[{"client_id": "cid_1", "name": "My App"}]]
+
+ def test_connections_omit_options(self) -> None:
+ page = {
+ "connections": [
+ {
+ "id": "con_1",
+ "name": "my-oidc",
+ "strategy": "oidc",
+ "options": {"client_id": "abc", "clientSecret": "shh"},
+ }
+ ]
+ }
+ batches, _, _ = self._run("connections", [_response(json_data=page)])
+
+ assert batches == [[{"id": "con_1", "name": "my-oidc", "strategy": "oidc"}]]
+
+ def test_users_omit_identity_provider_tokens(self) -> None:
+ page = {
+ "users": [
+ {
+ "user_id": "auth0|1",
+ "email": "[email protected]",
+ "identities": [
+ {
+ "connection": "google-oauth2",
+ "provider": "google-oauth2",
+ "user_id": "123",
+ "access_token": "shh-access",
+ "access_token_secret": "shh-access-secret",
+ "refresh_token": "shh-refresh",
+ }
+ ],
+ }
+ ],
+ "total": 1,
+ }
+ batches, _, _ = self._run("users", [_response(json_data=page)])
+
+ assert batches == [
+ [
+ {
+ "user_id": "auth0|1",
+ "email": "[email protected]",
+ "identities": [
+ {
+ "connection": "google-oauth2",
+ "provider": "google-oauth2",
+ "user_id": "123",
+ }
+ ],
+ }
+ ]
+ ]
+
+ def test_pagination_stops_once_total_is_reached(self) -> None:
+ page_0 = {"clients": [{"client_id": str(i)} for i in range(100)], "total": 150}
+ page_1 = {"clients": [{"client_id": str(i)} for i in range(100, 150)], "total": 150}
+ batches, session, manager = self._run("clients", [_response(json_data=page_0), _response(json_data=page_1)])
+
+ assert [len(batch) for batch in batches] == [100, 50]
+ assert session.get.call_count == 2
+ assert manager.saved == [Auth0ResumeConfig(page=1, window_start=None)]
+
+ def test_pagination_stops_on_a_short_page_without_totals(self) -> None:
+ page = {"actions": [{"id": "a1"}]}
+ batches, session, _ = self._run("actions", [_response(json_data=page)])
+
+ assert batches == [[{"id": "a1"}]]
+ assert session.get.call_count == 1
+
+ def test_pagination_stops_on_an_empty_page(self) -> None:
+ batches, session, _ = self._run("roles", [_response(json_data={"roles": [], "total": 0})])
+
+ assert batches == []
+ assert session.get.call_count == 1
+
+ def test_incremental_run_seeds_the_window_from_the_watermark(self) -> None:
+ page = {"users": _user_rows(1, "2024-05-01T00:00:00.000Z"), "total": 1}
+ _, session, _ = self._run(
+ "users",
+ [_response(json_data=page)],
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value=datetime(2024, 4, 1, tzinfo=UTC),
+ )
+
+ params = _requested_params(session, 0)
+ assert params["q"] == ['updated_at:["2024-04-01T00:00:00.000Z" TO *]']
+ assert params["sort"] == ["updated_at:1"]
+
+ def test_window_slides_past_the_search_result_cap(self) -> None:
+ newest = "2024-06-02T00:00:00.000Z"
+ page_0 = {"users": _user_rows(100, "2024-06-01T00:00:00.000Z"), "total": 5000}
+ page_1 = {"users": _user_rows(100, newest, start=100), "total": 5000}
+ page_2 = {"users": _user_rows(3, newest, start=200), "total": 3}
+
+ with mock.patch.object(auth0_module, "SEARCH_RESULT_CAP", 200):
+ batches, session, manager = self._run(
+ "users",
+ [_response(json_data=page_0), _response(json_data=page_1), _response(json_data=page_2)],
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ )
+
+ assert [len(batch) for batch in batches] == [100, 100, 3]
+ # The third request restarts at page 0 with the window's lower bound moved to the newest
+ # row seen — that is how the collection is walked past Auth0's 1000-result ceiling.
+ third = _requested_params(session, 2)
+ assert third["page"] == ["0"]
+ assert third["q"] == [f'updated_at:["{newest}" TO *]']
+ assert manager.saved == [
+ Auth0ResumeConfig(page=1, window_start=None),
+ Auth0ResumeConfig(page=0, window_start=newest),
+ ]
+
+ def test_window_that_cannot_advance_fails_loudly(self) -> None:
+ stuck = "2024-06-01T00:00:00.000Z"
+ page = {"users": _user_rows(100, stuck), "total": 5000}
+
+ with mock.patch.object(auth0_module, "SEARCH_RESULT_CAP", 200):
+ with pytest.raises(Auth0PaginationStalledError):
+ self._run(
+ "users",
+ [_response(json_data=page), _response(json_data=page)],
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value=stuck,
+ )
+
+ def test_non_windowed_collection_never_slides(self) -> None:
+ page_0 = {"clients": [{"client_id": str(i)} for i in range(100)], "total": 250}
+ page_1 = {"clients": [{"client_id": str(i)} for i in range(100, 200)], "total": 250}
+ page_2 = {"clients": [{"client_id": str(i)} for i in range(200, 250)], "total": 250}
+
+ with mock.patch.object(auth0_module, "SEARCH_RESULT_CAP", 100):
+ _, session, manager = self._run(
+ "clients",
+ [_response(json_data=page_0), _response(json_data=page_1), _response(json_data=page_2)],
+ )
+
+ assert [_requested_params(session, i)["page"] for i in range(3)] == [["0"], ["1"], ["2"]]
+ assert all(state.window_start is None for state in manager.saved)
+
+ def test_resumes_from_saved_page_and_window(self) -> None:
+ resumed_window = "2024-07-01T00:00:00.000Z"
+ page = {"users": _user_rows(1, "2024-07-02T00:00:00.000Z"), "total": 1}
+ _, session, _ = self._run(
+ "users",
+ [_response(json_data=page)],
+ manager=FakeResumeManager(Auth0ResumeConfig(page=4, window_start=resumed_window)),
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value="2020-01-01T00:00:00.000Z",
+ )
+
+ params = _requested_params(session, 0)
+ # The saved window wins over the (older) database watermark.
+ assert params["page"] == ["4"]
+ assert params["q"] == [f'updated_at:["{resumed_window}" TO *]']
+
+ def test_runaway_pagination_is_bounded(self) -> None:
+ page = {"clients": [{"client_id": str(i)} for i in range(100)], "total": 10**9}
+
+ with mock.patch.object(auth0_module, "MAX_PAGES", 2):
+ with pytest.raises(Auth0PaginationLimitError):
+ self._run("clients", [_response(json_data=page)] * 3)
+
+ def test_redirected_data_request_is_refused(self) -> None:
+ with pytest.raises(Auth0HostNotAllowedError):
+ self._run("roles", [_response(status_code=302)])
+
+ def test_internal_domain_is_blocked_before_any_request(self) -> None:
+ manager = FakeResumeManager()
+ with mock.patch.object(auth0_module, "_is_host_safe", return_value=(False, "resolves to a private address")):
+ with pytest.raises(Auth0HostNotAllowedError):
+ list(
+ get_rows(
+ domain="internal.auth0.com",
+ client_id="cid",
+ client_secret="secret",
+ endpoint="roles",
+ api_version="v2",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ )
+ )
+
+ @pytest.mark.parametrize("status_code", [400, 401, 403, 404])
+ def test_client_errors_propagate(self, status_code: int) -> None:
+ with pytest.raises(requests.HTTPError):
+ self._run("roles", [_response(status_code=status_code)])
+
+
+class TestValidateCredentials:
+ def _validate(
+ self,
+ *,
+ post_response: Any,
+ get_response: Any = None,
+ schema_name: Optional[str] = None,
+ domain: str = DOMAIN,
+ host_safe: bool = True,
+ ) -> tuple[bool, str | None]:
+ session = mock.MagicMock()
+ session.post.return_value = post_response
+ if get_response is not None:
+ session.get.return_value = get_response
+ with (
+ mock.patch.object(
+ auth0_module, "_is_host_safe", return_value=(host_safe, None if host_safe else "private address")
+ ),
+ mock.patch.object(auth0_module, "make_tracked_session", return_value=session),
+ ):
+ return validate_credentials(domain, "cid", "secret", "v2", schema_name=schema_name, team_id=1)
+
+ def test_token_exchange_alone_is_enough_at_source_create(self) -> None:
+ assert self._validate(post_response=_response(json_data=TOKEN_JSON)) == (True, None)
+
+ @pytest.mark.parametrize("status_code", [401, 403])
+ def test_bad_client_credentials_are_rejected(self, status_code: int) -> None:
+ ok, error = self._validate(post_response=_response(status_code=status_code))
+ assert ok is False
+ assert error == "Invalid Auth0 client ID or client secret"
+
+ @pytest.mark.parametrize("domain", ["", " ", "https://", "tenant us auth0 com", "tenant.auth0.com:8080"])
+ def test_malformed_domains_are_rejected(self, domain: str) -> None:
+ assert self._validate(post_response=_response(json_data=TOKEN_JSON), domain=domain) == (
+ False,
+ "Invalid Auth0 domain",
+ )
+
+ def test_internal_domain_is_rejected(self) -> None:
+ ok, error = self._validate(post_response=_response(json_data=TOKEN_JSON), host_safe=False)
+ assert ok is False
+ assert error == "private address"
+
+ def test_scoped_probe_accepts_a_reachable_collection(self) -> None:
+ result = self._validate(
+ post_response=_response(json_data=TOKEN_JSON),
+ get_response=_response(json_data={"users": [], "total": 0}),
+ schema_name="users",
+ )
+ assert result == (True, None)
+
+ @pytest.mark.parametrize(
+ "endpoint, scope",
+ [("users", "read:users"), ("logs", "read:logs"), ("log_streams", "read:log_streams")],
+ )
+ def test_scoped_probe_names_the_missing_scope(self, endpoint: str, scope: str) -> None:
+ ok, error = self._validate(
+ post_response=_response(json_data=TOKEN_JSON),
+ get_response=_response(status_code=403),
+ schema_name=endpoint,
+ )
+ assert ok is False
+ assert error is not None
+ assert scope in error
+
+ def test_scoped_probe_refuses_a_redirect(self) -> None:
+ ok, error = self._validate(
+ post_response=_response(json_data=TOKEN_JSON),
+ get_response=_response(status_code=302),
+ schema_name="roles",
+ )
+ assert (ok, error) == (False, auth0_module.HOST_NOT_ALLOWED_ERROR)
+
+ def test_network_failure_surfaces_rather_than_passing(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError("no route to host")
+ with (
+ mock.patch.object(auth0_module, "_is_host_safe", return_value=(True, None)),
+ mock.patch.object(auth0_module, "make_tracked_session", return_value=session),
+ ):
+ ok, error = validate_credentials(DOMAIN, "cid", "secret", "v2", team_id=1)
+ assert ok is False
+ assert error is not None
+
+
+class TestAuth0Source:
+ @pytest.mark.parametrize(
+ "endpoint, primary_key, partition_key",
+ [
+ ("users", "user_id", "created_at"),
+ ("logs", "log_id", "date"),
+ ("clients", "client_id", None),
+ ("connections", "id", None),
+ ("log_streams", "id", None),
+ ],
+ )
+ def test_response_shape_per_endpoint(self, endpoint: str, primary_key: str, partition_key: Optional[str]) -> None:
+ response = auth0_source(
+ domain=DOMAIN,
+ client_id="cid",
+ client_secret="secret",
+ endpoint=endpoint,
+ api_version="v2",
+ logger=mock.MagicMock(),
+ resumable_source_manager=FakeResumeManager(),
+ team_id=1,
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == [primary_key]
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+ assert response.partition_mode == ("datetime" if partition_key else None)
+
+ def test_items_is_lazy(self) -> None:
+ response = auth0_source(
+ domain=DOMAIN,
+ client_id="cid",
+ client_secret="secret",
+ endpoint="roles",
+ api_version="v2",
+ logger=mock.MagicMock(),
+ resumable_source_manager=FakeResumeManager(),
+ team_id=1,
+ )
+
+ # Building the response must not touch the network; only iterating does.
+ with mock.patch.object(auth0_module, "_is_host_safe", return_value=(True, None)):
+ with mock.patch.object(
+ auth0_module,
+ "make_tracked_session",
+ side_effect=[_token_session(), _data_session([_response(json_data={"roles": [], "total": 0})])],
+ ):
+ assert list(cast("Iterable[Any]", response.items())) == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/tests/test_auth0_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/tests/test_auth0_source.py
new file mode 100644
index 000000000000..d3805e4bcecd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/auth0/tests/test_auth0_source.py
@@ -0,0 +1,165 @@
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.facade.source_config import (
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.auth0 import Auth0ResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.settings import (
+ AUTH0_ENDPOINTS,
+ ENDPOINTS,
+ REQUIRED_SCOPES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.auth0.source import Auth0Source
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.auth0 import Auth0SourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.auth0.source"
+
+
+def _inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "users",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 7,
+ "should_use_incremental_field": True,
+ "db_incremental_field_last_value": "2024-01-01T00:00:00.000Z",
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": "updated_at",
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ return SourceInputs(**{**defaults, **overrides})
+
+
+class TestAuth0Source:
+ def setup_method(self) -> None:
+ self.source = Auth0Source()
+ self.team_id = 7
+ self.config = Auth0SourceConfig(auth0_domain="tenant.us.auth0.com", client_id="cid", client_secret="secret")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.AUTH0
+
+ def test_source_is_released_as_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.label == "Auth0"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/auth0"
+
+ def test_fields_take_machine_to_machine_credentials(self) -> None:
+ fields = self.source.get_source_config.fields
+
+ assert [f.name for f in fields] == ["auth0_domain", "client_id", "client_secret"]
+ for source_field in fields:
+ assert isinstance(source_field, SourceFieldInputConfig)
+ assert source_field.required is True
+ secret_flags = {f.name: f.secret for f in fields if isinstance(f, SourceFieldInputConfig)}
+ assert secret_flags == {"auth0_domain": False, "client_id": False, "client_secret": True}
+ client_secret = next(f for f in fields if f.name == "client_secret")
+ assert isinstance(client_secret, SourceFieldInputConfig)
+ assert client_secret.type == SourceFieldInputConfigType.PASSWORD
+
+ def test_connection_host_fields_pin_the_domain(self) -> None:
+ # Without this, an org member could retarget the domain at a server they control and the
+ # preserved client secret would be sent there.
+ assert self.source.connection_host_fields == ["auth0_domain"]
+
+ def test_api_version_is_pinned_to_what_the_paths_call(self) -> None:
+ assert self.source.supported_versions == ("v2",)
+ assert self.source.default_version == "v2"
+ assert self.source.resolve_api_version(None) == "v2"
+ assert all("/api/{version}/" in c.path_template for c in AUTH0_ENDPOINTS.values())
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_auth_failures_are_non_retryable(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_only_collections_with_a_server_side_date_filter_are_incremental(self, endpoint: str) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ # Only users and logs document a Lucene date range filter; everything else is full refresh.
+ assert schemas[endpoint].supports_incremental is (endpoint in ("users", "logs"))
+ # The window's inclusive lower bound re-reads boundary rows, so append would duplicate them.
+ assert schemas[endpoint].supports_append is False
+
+ def test_users_offers_both_timestamp_cursors(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert [f["field"] for f in schemas["users"].incremental_fields] == ["updated_at", "created_at"]
+ assert [f["field"] for f in schemas["logs"].incremental_fields] == ["date"]
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["logs"])
+ assert [s.name for s in schemas] == ["logs"]
+
+ def test_table_catalog_is_listed_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_every_endpoint_is_documented(self, endpoint: str) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert endpoint in descriptions
+ assert descriptions[endpoint]["columns"]
+ assert REQUIRED_SCOPES[endpoint].startswith("read:")
+
+ @pytest.mark.parametrize("schema_name", [None, "users"])
+ def test_validate_credentials_passes_the_config_through(self, schema_name: Optional[str]) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.validate_auth0_credentials", return_value=(True, None)) as mock_validate:
+ assert self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name) == (True, None)
+
+ kwargs = mock_validate.call_args.kwargs
+ assert kwargs == {
+ "domain": "tenant.us.auth0.com",
+ "client_id": "cid",
+ "client_secret": "secret",
+ "api_version": "v2",
+ "schema_name": schema_name,
+ "team_id": self.team_id,
+ }
+
+ def test_validate_credentials_surfaces_failures(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.validate_auth0_credentials", return_value=(False, "nope")):
+ assert self.source.validate_credentials(self.config, self.team_id) == (False, "nope")
+
+ def test_resumable_manager_is_bound_to_the_resume_dataclass(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is Auth0ResumeConfig
+
+ def test_source_for_pipeline_forwards_the_incremental_cursor(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs())
+ with mock.patch(f"{SOURCE_MODULE}.auth0_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, _inputs())
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["endpoint"] == "users"
+ assert kwargs["api_version"] == "v2"
+ assert kwargs["incremental_field"] == "updated_at"
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00.000Z"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 7
+
+ def test_full_refresh_drops_the_watermark(self) -> None:
+ inputs = _inputs(should_use_incremental_field=False, schema_name="clients")
+ manager = self.source.get_resumable_source_manager(inputs)
+ with mock.patch(f"{SOURCE_MODULE}.auth0_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/auth0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/auth0.py
index e89c11e19b60..888ac69c6f2c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/auth0.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/auth0.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class Auth0SourceConfig(config.Config):
- pass
+ auth0_domain: str
+ client_id: str
+ client_secret: str