: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement okta import source (#61152)
Tom Owers04d2d6df5431
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex cfc7df5bb3ca..f5ec8ad8cba6 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -375,6 +375,28 @@ If the API issues OAuth scopes or per-resource access tokens, declare every scop- **OAuth sources:** set `requiredScopes` on `SourceFieldOauthConfig` (space-separated string, matches the OAuth `scope` parameter format). The frontend diffs it against the integration's granted scopes and warns the user with a Reconnect action when any are missing.- **Non-OAuth sources (PAT, API key):** there's no integration object to inspect, so list scopes in the `caption` instead. Captions render through `LemonMarkdown`, so backticks, bold, and links work.+## Connection host fields (credential retargeting)++If your source stores a secret (API token, password) and sends it to a host that the user configures in a+**non-`host`** field, declare that field on the source class's `connection_host_fields` property (from the+base source in `common/base.py`):++```python+@property+def connection_host_fields(self) -> list[str]:+ # `okta_domain` is where the stored API token is sent; retargeting it must re-require the token.+ return ["okta_domain"]+```++The update serializer reads this list and forces the editor to re-enter the source's secrets whenever one of+these fields changes. Without it, an org member could PATCH the host field to a server they control while the+preserved (omitted) secret is reused — exfiltrating the credential. `host` and the SSH-tunnel target are+already handled separately, so only sources whose connection target lives in a differently named field (e.g.+Okta's `okta_domain`) need to override this. The default is `[]` (no extra fields).++Pair this with `_is_host_safe` (see `## Outbound HTTP must go through the tracked transport`) at both+source-create and sync time to block hosts resolving to internal/private IPs.+## MixinsFrom `posthog/temporal/data_imports/sources/common/mixins.py`:diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 0135c8a1c9bb..b8990f469dd9 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -79,6 +79,7 @@ the row lists both.| mongodb | DB protocol | pymongo | ➖ || mssql | DB protocol | pyodbc / pymssql | ➖ || mysql | DB protocol | pymysql | ➖ |+| okta | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ |@@ -191,7 +192,6 @@ doesn't conflict with concurrent PRs.- mixpanel- monday- netsuite-- okta- omnisend- onedrive- oraclediff --git a/posthog/temporal/data_imports/sources/common/base.py b/posthog/temporal/data_imports/sources/common/base.pyindex d714aea50188..10a3d3a693d8 100644--- a/posthog/temporal/data_imports/sources/common/base.py+++ b/posthog/temporal/data_imports/sources/common/base.py@@ -119,6 +119,17 @@ class _BaseSource(ABC, Generic[ConfigType]):"""Per-endpoint access check. ``{name: None}`` if reachable, ``{name: reason}`` if not. Default = all reachable."""return dict.fromkeys(endpoints)+ @property+ def connection_host_fields(self) -> list[str]:+ """``job_inputs`` fields that determine where stored credentials are sent.++ Changing one of these on an existing source must require the editor to re-enter the+ source's secrets — otherwise an org member could retarget the preserved credential at a+ server they control and exfiltrate it. The update serializer enforces this. ``host`` and+ the SSH tunnel target are handled separately, so sources whose connection target lives in+ a differently named field (e.g. Okta's ``okta_domain``) should list it here."""+ return []+def cleanup_cdc_resources_on_deletion(self, source: "ExternalDataSource") -> None:"""Best-effort teardown of CDC resources tied to the source. No-op by default."""return Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex ac59aef60b3a..096f959c7fdc 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -568,7 +568,8 @@ class NotionSourceConfig(config.Config):@config.configclass OktaSourceConfig(config.Config):- pass+ okta_domain: str+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/okta/okta.py b/posthog/temporal/data_imports/sources/okta/okta.pynew file mode 100644index 000000000000..e95645e8d52d--- /dev/null+++ b/posthog/temporal/data_imports/sources/okta/okta.py@@ -0,0 +1,357 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.okta.settings import OKTA_ENDPOINTS, OktaEndpointConfig++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60++HOST_NOT_ALLOWED_ERROR = "Okta domain is not allowed"+++class OktaRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class OktaHostNotAllowedError(Exception):+ pass+++class OktaResumeConfig:+ next_url: str+++def normalize_domain(domain: str) -> str:+ """Turn whatever the user typed into a bare Okta org host.++ Accepts values like ``company.okta.com``, ``https://company.okta.com/``,+ or ``company.okta.com/api/v1`` and returns ``company.okta.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)}/api/v1"+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"SSWS {api_key}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+++def _format_datetime_z(dt: datetime) -> str:+ """Okta wants ISO 8601 with millisecond precision and a literal ``Z`` suffix."""+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _format_incremental_value(value: Any) -> str:+ if isinstance(value, datetime):+ return _format_datetime_z(value)+ if isinstance(value, date):+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _build_initial_params(+ config: OktaEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": config.page_size}++ if config.name == "logs":+ # The System Log defaults to the last 7 days when `since` is omitted, so on the+ # first sync we explicitly reach back to the start of Okta's retention window.+ params["sortOrder"] = "ASCENDING"+ if should_use_incremental_field:+ since_value = db_incremental_field_last_value+ if not since_value and config.default_lookback_days:+ since_value = datetime.now(UTC) - timedelta(days=config.default_lookback_days)+ if since_value:+ params["since"] = _format_incremental_value(since_value)+ return params++ if config.incremental_param == "filter" and should_use_incremental_field and db_incremental_field_last_value:+ field = incremental_field or config.default_incremental_field+ formatted = _format_incremental_value(db_incremental_field_last_value)+ # Okta's SCIM-style filter expects the value wrapped in double quotes.+ params["filter"] = f'{field} gt "{formatted}"'++ return params+++def _build_initial_url(domain: str, config: OktaEndpointConfig, params: dict[str, Any]) -> str:+ url = f"{_base_url(domain)}{config.path}"+ if not params:+ return url+ return f"{url}?{urlencode(params)}"+++def _parse_next_url(link_header: str) -> str | None:+ """Return the URL with ``rel="next"`` from Okta's ``Link`` header, if any.++ Note: the System Log endpoint *always* returns a next link (it is designed for+ polling), so callers must also treat an empty page as the end of pagination.+ """+ if not link_header:+ return None+ for part in link_header.split(","):+ part = part.strip()+ match = re.match(r'<([^>]+)>;\s*rel="next"', part)+ if match:+ return match.group(1)+ return None+++def _is_same_host(url: str, domain: str) -> bool:+ """Whether ``url`` points at the configured Okta org host.++ Pagination/resume URLs are server-controlled (they arrive in the Link header), so we+ pin them to the validated org host to avoid being redirected at an arbitrary internal+ address (SSRF).+ """+ try:+ return (urlparse(url).hostname or "").lower() == normalize_domain(domain).lower()+ except Exception:+ return False+++def validate_credentials(+ domain: str, api_key: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe a cheap list endpoint to confirm the SSWS token is genuine.++ At source-create (``schema_name is None``) a 403 is accepted: the token is valid but may+ simply lack the scope for this particular probe. A scoped probe (``schema_name`` set) treats+ 403 as a hard failure.+ """+ try:+ normalized = normalize_domain(domain)+ except Exception:+ return False, "Invalid Okta domain"++ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):+ return False, "Invalid Okta domain"++ # The org domain is fully customer-controlled, so block hosts that resolve to private/+ # internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(normalized, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ url = f"https://{normalized}/api/v1/users"+ try:+ # Don't follow redirects: the validated host could 3xx to an internal address, defeating+ # the host check above (SSRF).+ response = make_tracked_session().get(+ url, headers=_get_headers(api_key), params={"limit": 1}, timeout=10, allow_redirects=False+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Okta API token"++ if response.status_code == 403:+ if schema_name is None:+ # Valid token, missing scope for this probe — let source creation through.+ return True, None+ return False, "Okta API token lacks the required permissions for this endpoint"++ try:+ body = response.json()+ return False, body.get("errorSummary", response.text)+ except Exception:+ return False, response.text+++def _parse_retry_after(response: requests.Response) -> float | None:+ """Okta sends ``Retry-After`` in whole seconds on 429. Ignore HTTP-date forms."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, OktaRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++def get_rows(+ domain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OktaResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = OKTA_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ # 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 OktaHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ initial_url = _build_initial_url(domain, config, params)+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and _is_same_host(resume_config.next_url, domain):+ url: str = resume_config.next_url+ logger.debug(f"Okta: resuming from URL: {url}")+ else:+ if resume_config is not None:+ logger.warning("Okta: ignoring resume URL whose host does not match the configured domain")+ url = initial_url++ @retry(+ retry=retry_if_exception_type((OktaRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(page_url: str) -> requests.Response:+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal address,+ # bypassing the host validation done before the request (SSRF).+ response = make_tracked_session().get(+ page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise OktaRetryableError(+ f"Okta API error (retryable): status={response.status_code}, url={page_url}",+ retry_after=retry_after,+ )++ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than+ # silently parsing the redirect body as data.+ if response.is_redirect or response.is_permanent_redirect:+ raise OktaHostNotAllowedError(+ f"Okta API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ logger.error(f"Okta API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response++ while True:+ response = fetch_page(url)++ data = response.json()+ if not isinstance(data, list) or not data:+ break++ next_url = _parse_next_url(response.headers.get("Link", ""))++ # Page and chunk boundaries don't line up, so checkpoint the CURRENT page URL.+ # On resume we re-fetch it and rely on primary-key merge semantics to dedupe rows+ # that were already yielded.+ checkpoint_url = url++ for item in data:+ batcher.batch(item)++ if batcher.should_yield():+ py_table = batcher.get_table()+ yield py_table+ resumable_source_manager.save_state(OktaResumeConfig(next_url=checkpoint_url))++ if not next_url:+ break++ # The next-page URL is server-controlled; only follow it if it stays on the org host.+ if not _is_same_host(next_url, domain):+ logger.warning("Okta: stopping pagination, next URL host does not match the configured domain")+ break++ url = next_url++ if batcher.should_yield(include_incomplete_chunk=True):+ py_table = batcher.get_table()+ yield py_table+++def okta_source(+ domain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OktaResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = OKTA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ domain=domain,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=[endpoint_config.primary_key],+ # Okta returns the System Log ascending (we request sortOrder=ASCENDING). The filter+ # endpoints don't guarantee an order, but each sync re-applies `filter=lastUpdated gt+ # <watermark>` and paginates every page, so completeness doesn't depend on ordering.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/okta/settings.py b/posthog/temporal/data_imports/sources/okta/settings.pynew file mode 100644index 000000000000..7a070ba9083d--- /dev/null+++ b/posthog/temporal/data_imports/sources/okta/settings.py@@ -0,0 +1,100 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class OktaEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Field used to build the server-side incremental filter. Okta exposes `lastUpdated`+ # on most resources and `published` on the System Log.+ default_incremental_field: Optional[str] = None+ # How the incremental filter is sent to Okta:+ # "filter" -> ?filter=lastUpdated gt "<ts>" (Users, Groups, Apps)+ # "since" -> ?since=<ts> (System Log)+ incremental_param: Optional[Literal["filter", "since"]] = None+ # Stable, immutable field to partition by. Never use lastUpdated (it mutates).+ partition_key: Optional[str] = None+ primary_key: str = "id"+ page_size: int = 200+ # Limit the first sync to the last N days instead of full history. Only used by+ # endpoints with a true time filter (System Log retention is bounded anyway).+ default_lookback_days: Optional[int] = None+++OKTA_ENDPOINTS: dict[str, OktaEndpointConfig] = {+ # lastUpdated is the only incremental cursor offered for the filter endpoints: it is the+ # canonical, documented server-side filter attribute and it actually advances on edits.+ # `created` never changes, so it stays the stable partition key but is not a useful cursor.+ "users": OktaEndpointConfig(+ name="users",+ path="/users",+ incremental_fields=[_datetime_incremental_field("lastUpdated")],+ default_incremental_field="lastUpdated",+ incremental_param="filter",+ partition_key="created",+ page_size=200,+ ),+ "groups": OktaEndpointConfig(+ name="groups",+ path="/groups",+ incremental_fields=[_datetime_incremental_field("lastUpdated")],+ default_incremental_field="lastUpdated",+ incremental_param="filter",+ partition_key="created",+ page_size=200,+ ),+ "applications": OktaEndpointConfig(+ name="applications",+ path="/apps",+ incremental_fields=[_datetime_incremental_field("lastUpdated")],+ default_incremental_field="lastUpdated",+ incremental_param="filter",+ partition_key="created",+ page_size=200,+ ),+ "logs": OktaEndpointConfig(+ name="logs",+ path="/logs",+ # System Log events are immutable; `published` is the only sensible cursor.+ incremental_fields=[_datetime_incremental_field("published")],+ default_incremental_field="published",+ incremental_param="since",+ partition_key="published",+ primary_key="uuid",+ page_size=1000,+ default_lookback_days=90,+ ),+ "group_rules": OktaEndpointConfig(+ name="group_rules",+ path="/groups/rules",+ # The group rules endpoint does not accept a server-side time filter, so this is+ # full-refresh only.+ partition_key="created",+ page_size=200,+ ),+ "user_types": OktaEndpointConfig(+ name="user_types",+ path="/meta/types/user",+ # Small, unpaginated metadata list. Full refresh only.+ page_size=200,+ ),+}++ENDPOINTS = tuple(OKTA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in OKTA_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/okta/source.py b/posthog/temporal/data_imports/sources/okta/source.pyindex 9e7d3698975b..a2879b58f110 100644--- a/posthog/temporal/data_imports/sources/okta/source.py+++ b/posthog/temporal/data_imports/sources/okta/source.py@@ -1,29 +1,136 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import OktaSourceConfig+from posthog.temporal.data_imports.sources.okta.okta import (+ HOST_NOT_ALLOWED_ERROR,+ OktaResumeConfig,+ okta_source,+ validate_credentials as validate_okta_credentials,+)+from posthog.temporal.data_imports.sources.okta.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class OktaSource(SimpleSource[OktaSourceConfig]):+class OktaSource(ResumableSource[OktaSourceConfig, OktaResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OKTA+ @property+ def connection_host_fields(self) -> list[str]:+ # `okta_domain` is where the stored API token is sent; retargeting it must re-require the token.+ return ["okta_domain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.OKTA,label="Okta",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Okta org domain and an API token to pull your Okta data into the PostHog Data warehouse.++You can create an API token in the Okta Admin Console under **Security > API > Tokens**.++The token's user should have read access to the resources you want to sync, for example:+- `okta.users.read`+- `okta.groups.read`+- `okta.apps.read`+- `okta.logs.read`+""",iconPath="/static/services/okta.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/okta",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="okta_domain",+ label="Okta domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="your-org.okta.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Okta API token. Please generate a new token and reconnect.",+ "403 Client Error": "Your Okta API token lacks the required permissions. Please check the token's scopes and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Okta domain is not allowed. Please use your organization's Okta domain.",+ }++ def get_schemas(+ self,+ config: OktaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description="Only syncs the last 90 days on initial sync" if endpoint == "logs" else None,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: OktaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_okta_credentials(config.okta_domain, config.api_key, schema_name, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OktaResumeConfig]:+ return ResumableSourceManager[OktaResumeConfig](inputs, OktaResumeConfig)++ def source_for_pipeline(+ self,+ config: OktaSourceConfig,+ resumable_source_manager: ResumableSourceManager[OktaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return okta_source(+ domain=config.okta_domain,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/okta/tests/test_okta.py b/posthog/temporal/data_imports/sources/okta/tests/test_okta.pynew file mode 100644index 000000000000..e46d5906c817--- /dev/null+++ b/posthog/temporal/data_imports/sources/okta/tests/test_okta.py@@ -0,0 +1,424 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.okta import okta as okta_module+from posthog.temporal.data_imports.sources.okta.okta import (+ OktaResumeConfig,+ _build_initial_params,+ _build_initial_url,+ _format_incremental_value,+ _parse_next_url,+ get_rows,+ normalize_domain,+ okta_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.okta.settings import OKTA_ENDPOINTS+++def _response(+ *, status_code: int = 200, json_data: Any = None, link: Optional[str] = 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 (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.json.return_value = json_data+ response.headers = {"Link": link} if link else {}+ return response+++class _FakeBatcher:+ """Yields whatever has been buffered on every ``should_yield`` check, so the per-item+ save_state path in ``get_rows`` is exercised without needing 2000+ rows."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._buf: list[Any] = []++ def batch(self, item: Any) -> None:+ self._buf.append(item)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._buf) > 0++ def get_table(self) -> list[Any]:+ rows, self._buf = self._buf, []+ return rows+++class TestNormalizeDomain:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("example.okta.com", "example.okta.com"),+ ("https://example.okta.com", "example.okta.com"),+ ("http://example.okta.com/", "example.okta.com"),+ (" example.okta.com ", "example.okta.com"),+ ("example.okta.com/api/v1", "example.okta.com"),+ ("https://example.okta.com/api/v1/users", "example.okta.com"),+ ],+ )+ def test_normalize_domain(self, raw, expected):+ assert normalize_domain(raw) == expected+++class TestFormatIncrementalValue:+ @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"),+ ("already-a-cursor", "already-a-cursor"),+ ],+ )+ def test_format(self, value, expected):+ assert _format_incremental_value(value) == expected++ def test_no_offset_suffix(self):+ assert "+00:00" not in _format_incremental_value(datetime(2026, 3, 4, tzinfo=UTC))+++class TestBuildInitialParams:+ def test_filter_endpoint_incremental(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["users"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="lastUpdated",+ )+ assert params["filter"] == 'lastUpdated gt "2024-01-01T00:00:00.000Z"'+ assert params["limit"] == 200++ def test_filter_endpoint_no_watermark_has_no_filter(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["users"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="lastUpdated",+ )+ assert "filter" not in params++ def test_filter_endpoint_full_refresh_has_no_filter(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["groups"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field=None,+ )+ assert "filter" not in params++ def test_logs_incremental_uses_since(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["logs"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="published",+ )+ assert params["since"] == "2024-01-01T00:00:00.000Z"+ assert params["sortOrder"] == "ASCENDING"++ def test_logs_first_sync_applies_lookback(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["logs"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="published",+ )+ # The 90-day lookback means `since` is populated even without a stored watermark.+ assert "since" in params+ assert params["sortOrder"] == "ASCENDING"++ def test_logs_full_refresh_has_no_since(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["logs"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )+ assert "since" not in params+ assert params["sortOrder"] == "ASCENDING"++ def test_logs_full_refresh_ignores_stray_watermark(self):+ # Even if a watermark leaks in, a non-incremental run must not apply a `since` filter.+ params = _build_initial_params(+ OKTA_ENDPOINTS["logs"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field=None,+ )+ assert "since" not in params++ def test_non_incremental_endpoint_only_limit(self):+ params = _build_initial_params(+ OKTA_ENDPOINTS["group_rules"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field=None,+ )+ assert params == {"limit": 200}+++class TestBuildInitialUrl:+ def test_builds_url_with_params(self):+ url = _build_initial_url("example.okta.com", OKTA_ENDPOINTS["users"], {"limit": 200})+ assert url == "https://example.okta.com/api/v1/users?limit=200"++ def test_builds_url_without_params(self):+ url = _build_initial_url("example.okta.com", OKTA_ENDPOINTS["user_types"], {})+ assert url == "https://example.okta.com/api/v1/meta/types/user"+++class TestParseNextUrl:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ("", None),+ ('<https://x/api/v1/users>; rel="self"', None),+ ('<https://x/api/v1/users?after=abc>; rel="next"', "https://x/api/v1/users?after=abc"),+ (+ '<https://x/api/v1/users>; rel="self", <https://x/api/v1/users?after=abc>; rel="next"',+ "https://x/api/v1/users?after=abc",+ ),+ ],+ )+ def test_parse(self, header, expected):+ assert _parse_next_url(header) == expected+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(okta_module, "make_tracked_session", return_value=session)++ def test_success(self):+ with self._patch_session(_response(status_code=200)):+ assert validate_credentials("example.okta.com", "tok") == (True, None)++ def test_invalid_token(self):+ with self._patch_session(_response(status_code=401)):+ valid, msg = validate_credentials("example.okta.com", "tok")+ assert valid is False+ assert "Invalid Okta API token" == msg++ def test_403_at_source_create_is_accepted(self):+ with self._patch_session(_response(status_code=403)):+ assert validate_credentials("example.okta.com", "tok", schema_name=None) == (True, None)++ def test_403_for_scoped_probe_fails(self):+ with self._patch_session(_response(status_code=403)):+ valid, msg = validate_credentials("example.okta.com", "tok", schema_name="users")+ assert valid is False+ assert msg is not None++ @pytest.mark.parametrize("bad_domain", ["", "not a domain!", "https://"])+ def test_invalid_domain_short_circuits(self, bad_domain):+ valid, msg = validate_credentials(bad_domain, "tok")+ assert valid is False+ assert msg == "Invalid Okta domain"++ def test_request_exception_returns_failure(self):+ import requests++ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials("example.okta.com", "tok")+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ # A validated host that 3xx-redirects (potentially to an internal address) must be rejected,+ # not followed (SSRF).+ with self._patch_session(_response(status_code=302)) as patched:+ valid, msg = validate_credentials("example.okta.com", "tok")+ assert valid is False+ assert msg == okta_module.HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host(self):+ # When a team_id is supplied, a host that resolves to an internal address is rejected+ # before any HTTP request is made (SSRF guard).+ with (+ mock.patch.object(okta_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(_response(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("10.0.0.1", "tok", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()+++class TestOktaSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_key, partition_key",+ [+ ("users", "id", "created"),+ ("groups", "id", "created"),+ ("applications", "id", "created"),+ ("logs", "uuid", "published"),+ ("group_rules", "id", "created"),+ ("user_types", "id", None),+ ],+ )+ def test_response_shape(self, endpoint, primary_key, partition_key):+ response = okta_source(+ domain="example.okta.com",+ api_key="tok",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == [primary_key]+ assert response.sort_mode == "asc"+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestGetRows:+ def _run(self, manager, responses):+ session = mock.MagicMock()+ session.get.side_effect = responses+ with (+ mock.patch.object(okta_module, "make_tracked_session", return_value=session),+ mock.patch.object(okta_module, "Batcher", _FakeBatcher),+ ):+ rows: list[Any] = []+ for table in get_rows(+ domain="example.okta.com",+ api_key="tok",+ endpoint="users",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ ):+ rows.extend(table)+ return rows, session++ def test_follows_link_header_across_pages(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _response(+ json_data=[{"id": "1"}, {"id": "2"}],+ link='<https://example.okta.com/api/v1/users?after=cur>; rel="next"',+ )+ page2 = _response(json_data=[{"id": "3"}])+ rows, session = self._run(manager, [page1, page2])++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ # Second fetch follows the Link header URL.+ second_url = session.get.call_args_list[1].args[0]+ assert second_url == "https://example.okta.com/api/v1/users?after=cur"++ def test_saves_state_after_yielding(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page = _response(json_data=[{"id": "1"}])+ self._run(manager, [page])++ assert manager.save_state.called+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, OktaResumeConfig)++ def test_resumes_from_saved_state(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = OktaResumeConfig(+ next_url="https://example.okta.com/api/v1/users?after=resume"+ )+ rows, session = self._run(manager, [_response(json_data=[{"id": "9"}])])++ first_url = session.get.call_args_list[0].args[0]+ assert first_url == "https://example.okta.com/api/v1/users?after=resume"+ assert [r["id"] for r in rows] == ["9"]++ def test_empty_page_terminates_even_with_next_link(self):+ # The System Log always returns a next link, so an empty page must end pagination.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ empty = _response(+ json_data=[],+ link='<https://example.okta.com/api/v1/logs?after=x>; rel="next"',+ )+ rows, session = self._run(manager, [empty])++ assert rows == []+ assert session.get.call_count == 1++ def test_does_not_follow_next_url_on_foreign_host(self):+ # A server-controlled Link header pointing off-org must not be followed (SSRF guard).+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _response(+ json_data=[{"id": "1"}],+ link='<http://169.254.169.254/latest/meta-data/>; rel="next"',+ )+ rows, session = self._run(manager, [page1])++ assert [r["id"] for r in rows] == ["1"]+ assert session.get.call_count == 1++ def test_ignores_resume_url_on_foreign_host(self):+ # A poisoned resume URL must fall back to the initial org URL, not be followed.+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = OktaResumeConfig(next_url="http://169.254.169.254/latest/meta-data/")+ rows, session = self._run(manager, [_response(json_data=[{"id": "1"}])])++ first_url = session.get.call_args_list[0].args[0]+ assert first_url.startswith("https://example.okta.com/api/v1/users")+ assert [r["id"] for r in rows] == ["1"]++ def test_does_not_follow_redirects(self):+ # Requests are made with allow_redirects=False, and a redirect response is rejected rather+ # than followed to a (potentially internal) Location (SSRF).+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ with pytest.raises(okta_module.OktaHostNotAllowedError):+ self._run(manager, [_response(status_code=302)])++ def test_passes_allow_redirects_false(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ _rows, session = self._run(manager, [_response(json_data=[{"id": "1"}])])+ assert session.get.call_args.kwargs["allow_redirects"] is False+++class TestRetryAfter:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ({"Retry-After": "5"}, 5.0),+ ({"Retry-After": " 9 "}, 9.0),+ ({"Retry-After": "100000"}, 60.0), # capped+ ({"Retry-After": "Wed, 21 Oct 2025 07:28:00 GMT"}, None), # HTTP-date ignored+ ({}, None),+ ],+ )+ def test_parse_retry_after(self, header, expected):+ from posthog.temporal.data_imports.sources.okta.okta import _parse_retry_after++ response = mock.MagicMock()+ response.headers = header+ assert _parse_retry_after(response) == expected++ def test_retry_wait_prefers_retry_after(self):+ from posthog.temporal.data_imports.sources.okta.okta import OktaRetryableError, _retry_wait++ state = mock.MagicMock()+ state.outcome.exception.return_value = OktaRetryableError("rate limited", retry_after=7.0)+ assert _retry_wait(state) == 7.0diff --git a/posthog/temporal/data_imports/sources/okta/tests/test_okta_source.py b/posthog/temporal/data_imports/sources/okta/tests/test_okta_source.pynew file mode 100644index 000000000000..7ea3feb210bd--- /dev/null+++ b/posthog/temporal/data_imports/sources/okta/tests/test_okta_source.py@@ -0,0 +1,137 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import OktaSourceConfig+from posthog.temporal.data_imports.sources.okta.okta import OktaResumeConfig+from posthog.temporal.data_imports.sources.okta.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.okta.source import OktaSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestOktaSource:+ def setup_method(self):+ self.source = OktaSource()+ self.team_id = 123+ self.config = OktaSourceConfig(okta_domain="example.okta.com", api_key="00token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.OKTA++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Okta"+ assert config.label == "Okta"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/okta.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["okta_domain", "api_key"]++ domain_field, token_field = config.fields+ assert isinstance(domain_field, SourceFieldInputConfig)+ assert domain_field.type == SourceFieldInputConfigType.TEXT+ assert domain_field.secret is False++ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "endpoint, incremental",+ [+ ("users", True),+ ("groups", True),+ ("applications", True),+ ("logs", True),+ ("group_rules", False),+ ("user_types", False),+ ],+ )+ def test_schema_incremental_support(self, endpoint, incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].supports_incremental is incremental+ assert schemas[endpoint].supports_append is incremental++ def test_logs_schema_has_lookback_description(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert "90 days" in (schemas["logs"].description or "")++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users"])+ assert len(schemas) == 1+ assert schemas[0].name == "users"++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected",+ [+ ((True, None), (True, None)),+ ((False, "Invalid Okta API token"), (False, "Invalid Okta API token")),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.okta.source.validate_okta_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="users")++ assert result == expected+ mock_validate.assert_called_once_with(self.config.okta_domain, self.config.api_key, "users", self.team_id)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OktaResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.okta.source.okta_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_okta_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.team_id = 42+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00.000Z"+ inputs.incremental_field = "lastUpdated"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_okta_source.assert_called_once()+ kwargs = mock_okta_source.call_args.kwargs+ assert kwargs["domain"] == "example.okta.com"+ assert kwargs["api_key"] == "00token"+ assert kwargs["endpoint"] == "users"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00.000Z"+ assert kwargs["incremental_field"] == "lastUpdated"++ @mock.patch("posthog.temporal.data_imports.sources.okta.source.okta_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_okta_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "group_rules"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_okta_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex c6eeb073080b..569f023849d6 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -762,6 +762,14 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerfor field in _CONNECTION_TARGET_FIELDS)+ # Some sources keep their connection target in a differently named field (e.g. Okta's+ # `okta_domain`). Changing one would send the preserved credential to a new host — the same+ # exfiltration risk as a `host` change — so require re-entry too.+ connection_host_changed = connection_host_changed or any(+ field in incoming_job_inputs and incoming_job_inputs[field] != existing_job_inputs.get(field)+ for field in source.connection_host_fields+ )+# If the SSH tunnel's connection target changed, also require credentials. Without this an# editor could swap in a tunnel that routes the backend's auth to an attacker-controlled# server, exfiltrating the stored database credentials (VERIA-311).diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 5dcae86c868c..2fa409048732 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -4254,6 +4254,62 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["auth_api_key"] == "sk_existing"mock_validate_credentials.assert_called_once()+ def _okta_source(self) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Okta",+ created_by=self.user,+ prefix="okta_src",+ job_inputs={"okta_domain": "company.okta.com", "api_key": "existing_token"},+ )++ @parameterized.expand([("without_token", {}, 400), ("with_token", {"api_key": "new_token"}, 200)])+ @patch(+ "posthog.temporal.data_imports.sources.okta.source.OktaSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_okta_source_domain_change_requires_token(+ self, _name, extra_creds, expected_status, mock_validate_credentials+ ):+ # `okta_domain` is the connection target for Okta. Retargeting it without re-supplying the API+ # token would send the preserved token to a host the editor chose, so the change is rejected.+ source = self._okta_source()++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"okta_domain": "attacker.example.com", **extra_creds}},+ )++ assert response.status_code == expected_status, response.json()+ assert ("re-entering your credentials" in str(response.json())) == (expected_status == 400)+ source.refresh_from_db()+ expected_domain = "attacker.example.com" if expected_status == 200 else "company.okta.com"+ assert source.job_inputs["okta_domain"] == expected_domain+ assert source.job_inputs["api_key"] == ("new_token" if expected_status == 200 else "existing_token")+ # The credential probe only runs once the re-entry gate has passed.+ assert mock_validate_credentials.called == (expected_status == 200)++ @patch(+ "posthog.temporal.data_imports.sources.okta.source.OktaSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_okta_source_same_domain_keeps_token(self, mock_validate_credentials):+ # Re-saving the source without changing the domain must not force the user to re-enter the token.+ source = self._okta_source()++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"okta_domain": "company.okta.com"}},+ )++ assert response.status_code == 200, response.json()+ source.refresh_from_db()+ assert source.job_inputs["api_key"] == "existing_token"+ mock_validate_credentials.assert_called_once()+@patch("posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",return_value=(True, None),