: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 servicenow import source (#61143)
Tom Owersbe0d8df95332
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex c9c4b2a5a9b6..7eb5d1b6e80c 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -91,6 +91,7 @@ the row lists both.| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |+| servicenow | HTTP | requests | ✅ || shopify | HTTP | requests | ✅ || shortcut | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -206,7 +207,6 @@ doesn't conflict with concurrent PRs.- ringcentral- salesloft- sendgrid-- servicenow- sftp- sharepoint- smartsheetdiff --git a/posthog/temporal/data_imports/sources/common/http/sampling.py b/posthog/temporal/data_imports/sources/common/http/sampling.pyindex c5cb8a02bef6..f4f677569fed 100644--- a/posthog/temporal/data_imports/sources/common/http/sampling.py+++ b/posthog/temporal/data_imports/sources/common/http/sampling.py@@ -69,7 +69,7 @@ MAX_CONFIG_TTL_SECONDS = 24 * 60 * 60_REDACTED_HEADER = "REDACTED"_REDACTED_FORM_VALUE = "REDACTED"_AUTH_HEADER_NAMES: frozenset[str] = frozenset(- {"authorization", "x-api-key", "x-auth-token", "cookie", "set-cookie", "proxy-authorization"}+ {"authorization", "x-api-key", "x-sn-apikey", "x-auth-token", "cookie", "set-cookie", "proxy-authorization"})__all__ = ["CaptureConfig", "CaptureRule", "maybe_capture"]diff --git a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.pyindex 0ccf6893e365..1fd83264d8b9 100644--- a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py+++ b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py@@ -391,7 +391,16 @@ def test_sample_payload_preserves_json_body_keys():@pytest.mark.parametrize("header_name",- ["Authorization", "authorization", "X-API-Key", "x-auth-token", "Cookie", "Set-Cookie", "Proxy-Authorization"],+ [+ "Authorization",+ "authorization",+ "X-API-Key",+ "x-sn-apikey",+ "x-auth-token",+ "Cookie",+ "Set-Cookie",+ "Proxy-Authorization",+ ],)def test_scrub_headers_redacts_auth_headers(header_name: str):cleaned = _scrub_headers({header_name: "Bearer sk_live_secret"})diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex c16a88d926c6..f1a49d8b3d2c 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -61,6 +61,14 @@ class HubspotCustomPropertiesConfig(config.Config):meetings_properties: str | None = None+class ServiceNowAuthMethodConfig(config.Config):+ selection: Literal["basic", "api_key"] = "basic"+ username: str | None = None+ password: str | None = None+ api_key: str | None = None++@config.configclass SnowflakeAuthTypeConfig(config.Config):user: str@@ -742,7 +750,8 @@ class SentrySourceConfig(config.Config):@config.configclass ServiceNowSourceConfig(config.Config):- pass+ instance_url: str+ auth_method: ServiceNowAuthMethodConfig@config.configdiff --git a/posthog/temporal/data_imports/sources/servicenow/servicenow.py b/posthog/temporal/data_imports/sources/servicenow/servicenow.pynew file mode 100644index 000000000000..02fb91880674--- /dev/null+++ b/posthog/temporal/data_imports/sources/servicenow/servicenow.py@@ -0,0 +1,309 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.servicenow.settings import SERVICENOW_ENDPOINTS++# ServiceNow's Table API defaults to a generous page size; we keep it modest so each+# heartbeat-bounded batch stays small and resumable. Offset pagination is simple and+# universally supported. Keyset pagination (ORDERBY sys_created_on with a moving+# floor) performs better on very large tables, but offset keeps resume state trivial+# and is adequate for the table sizes this source targets.+DEFAULT_PAGE_SIZE = 1000+REQUEST_TIMEOUT = 60+MAX_RETRY_ATTEMPTS = 5+++class ServiceNowRetryableError(Exception):+ pass+++class ServiceNowError(Exception):+ """Non-retryable ServiceNow transport error (e.g. an unexpected redirect)."""+++class ServiceNowResumeConfig:+ offset: int+++class ServiceNowAuth:+ """Resolved credentials for a single sync. Exactly one auth style is populated."""++ api_key: Optional[str] = None+ username: Optional[str] = None+ password: Optional[str] = None++ def headers(self) -> dict[str, str]:+ headers = {"Accept": "application/json"}+ if self.api_key:+ headers["x-sn-apikey"] = self.api_key+ return headers++ def basic_auth(self) -> Optional[tuple[str, str]]:+ if self.username and self.password:+ return (self.username, self.password)+ return None+++def normalize_instance_url(instance: str) -> str:+ """Accept a bare subdomain, host, or full URL and return `https://<host>[:port]`.++ Forces HTTPS and strips any path, query, fragment, or userinfo so only the+ host (and optional port) survive. This keeps the value safe to feed into the+ SSRF host check and to build Table API paths against.++ Examples: ``dev12345`` -> ``https://dev12345.service-now.com``;+ ``https://acme.service-now.com/foo?x=1`` -> ``https://acme.service-now.com``.+ """+ value = (instance or "").strip().rstrip("/")+ if not value:+ raise ValueError("ServiceNow instance URL is required")++ # Bare subdomain (no scheme, no dot) expands to the standard ServiceNow domain.+ if "://" not in value and "." not in value:+ return f"https://{value}.service-now.com"++ if "://" not in value:+ value = f"https://{value}"++ parsed = urlparse(value)+ host = parsed.hostname+ if not host:+ raise ValueError("Invalid ServiceNow instance URL")++ netloc = f"{host}:{parsed.port}" if parsed.port else host+ return f"https://{netloc}"+++def _resolve_base_url(instance_url: str, team_id: int) -> str:+ """Normalize the instance URL and reject internal/private hosts (SSRF guard).++ ``_is_host_safe`` is a no-op outside of PostHog Cloud, so self-hosted+ instances can still reach any host.+ """+ base_url = normalize_instance_url(instance_url)+ hostname = urlparse(base_url).hostname or ""+ is_safe, error = _is_host_safe(hostname, team_id)+ if not is_safe:+ raise ValueError(error or "ServiceNow instance host is not allowed.")+ return base_url+++def _format_datetime(value: Any) -> Optional[str]:+ """Format an incremental cursor value as ServiceNow's `YYYY-MM-DD HH:MM:SS` (UTC).++ With ``sysparm_display_value=false`` ServiceNow returns and filters audit+ timestamps in UTC, so we coerce everything to UTC before formatting.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ dt = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.strftime("%Y-%m-%d %H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d 00:00:00")+ return str(value)+++def build_sysparm_query(cursor_field: Optional[str], last_value: Optional[str], sort_field: str) -> str:+ """Build a ServiceNow encoded query.++ Filters server-side on ``<cursor_field>>=<last_value>`` when incremental, and+ always pins an explicit ascending order on ``sort_field`` so pagination is stable+ and the pipeline's cursor watermark advances correctly.+ """+ clauses: list[str] = []+ if cursor_field and last_value:+ clauses.append(f"{cursor_field}>={last_value}")+ clauses.append(f"ORDERBY{sort_field}")+ return "^".join(clauses)+++def validate_credentials(+ instance_url: str,+ auth: ServiceNowAuth,+ team_id: int,+ table: Optional[str] = None,+) -> tuple[bool, str | None]:+ try:+ base_url = _resolve_base_url(instance_url, team_id)+ except ValueError as exc:+ return False, str(exc)++ # Probe a cheap single-row read. At source-create (no specific table) we probe+ # `sys_user`; otherwise probe the requested table to confirm scope for it.+ probe_table = table or "sys_user"+ url = f"{base_url}/api/now/table/{probe_table}"+ params: dict[str, Any] = {"sysparm_limit": 1, "sysparm_fields": "sys_id"}++ try:+ # `instance_url` is user-supplied; don't follow redirects so a safe-looking+ # host can't bounce us to an internal one (SSRF guard).+ response = make_tracked_session().get(+ url,+ params=params,+ headers=auth.headers(),+ auth=auth.basic_auth(),+ timeout=10,+ allow_redirects=False,+ )+ except requests.RequestException as exc:+ return False, str(exc)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid ServiceNow credentials. Please check your instance URL and credentials."+ if response.status_code == 403:+ # Valid credentials, but no read access to this table. Accept at source-create+ # (the user may only intend to sync the tables they have access to) and only+ # surface the error when validating a specific table.+ if table is None:+ return True, None+ return False, f"Your ServiceNow account does not have read access to the '{table}' table."+ if response.status_code == 404:+ return False, f"ServiceNow table '{probe_table}' was not found on this instance."++ return False, f"ServiceNow returned an unexpected status ({response.status_code})."+++def get_rows(+ base_url: str,+ table: str,+ auth: ServiceNowAuth,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ServiceNowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ headers = auth.headers()+ basic_auth = auth.basic_auth()++ if should_use_incremental_field:+ cursor_field = incremental_field or "sys_updated_on"+ last_value = _format_datetime(db_incremental_field_last_value)+ sort_field = cursor_field+ else:+ cursor_field = None+ last_value = None+ # Partition by creation time, so a full refresh is ordered by the same stable field.+ sort_field = "sys_created_on"++ query = build_sysparm_query(cursor_field, last_value, sort_field)+ url = f"{base_url}/api/now/table/{table}"++ # One session for the whole paginated fetch so the TCP/TLS connection is reused+ # across pages. Disable urllib3-level retries — `tenacity` below is the single+ # retry mechanism (otherwise a 429 would be retried by both layers).+ session = make_tracked_session(retry=Retry(total=0))++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.offset if resume_config else 0+ if resume_config:+ logger.debug(f"ServiceNow: resuming '{table}' from offset {offset}")++ @retry(+ retry=retry_if_exception_type((ServiceNowRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_offset: int) -> list[dict[str, Any]]:+ params: dict[str, Any] = {+ "sysparm_query": query,+ "sysparm_limit": DEFAULT_PAGE_SIZE,+ "sysparm_offset": page_offset,+ "sysparm_display_value": "false",+ "sysparm_exclude_reference_link": "true",+ }+ # `base_url` is user-supplied; refuse redirects so a safe-looking host can't+ # bounce us to an internal one (SSRF guard).+ response = session.get(+ url,+ params=params,+ headers=headers,+ auth=basic_auth,+ timeout=REQUEST_TIMEOUT,+ allow_redirects=False,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise ServiceNowRetryableError(+ f"ServiceNow API error (retryable): status={response.status_code}, table={table}"+ )++ if 300 <= response.status_code < 400:+ raise ServiceNowError(+ f"ServiceNow returned an unexpected redirect (status={response.status_code}, table={table}); refusing to follow"+ )++ if not response.ok:+ logger.error(f"ServiceNow API error: status={response.status_code}, body={response.text}, table={table}")+ response.raise_for_status()++ return response.json().get("result", [])++ while True:+ rows = fetch_page(offset)+ if not rows:+ break++ yield rows++ offset += DEFAULT_PAGE_SIZE+ # Save state AFTER yielding so a crash re-yields the last batch (merge dedupes+ # on the primary key) rather than skipping it.+ resumable_source_manager.save_state(ServiceNowResumeConfig(offset=offset))++ if len(rows) < DEFAULT_PAGE_SIZE:+ break+++def servicenow_source(+ instance_url: str,+ auth: ServiceNowAuth,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ServiceNowResumeConfig],+ 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 = SERVICENOW_ENDPOINTS[endpoint]+ base_url = _resolve_base_url(instance_url, team_id)++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ base_url=base_url,+ table=endpoint_config.table,+ auth=auth,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ 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],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="week",+ partition_keys=[endpoint_config.partition_key],+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/servicenow/settings.py b/posthog/temporal/data_imports/sources/servicenow/settings.pynew file mode 100644index 000000000000..f5e251a76253--- /dev/null+++ b/posthog/temporal/data_imports/sources/servicenow/settings.py@@ -0,0 +1,61 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Every ServiceNow table exposes the same audit columns, so every endpoint advertises+# the same incremental options. `sys_updated_on` catches both inserts and updates;+# `sys_created_on` is offered for append-only style syncs.+SERVICENOW_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "sys_updated_on",+ "type": IncrementalFieldType.DateTime,+ "field": "sys_updated_on",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "sys_created_on",+ "type": IncrementalFieldType.DateTime,+ "field": "sys_created_on",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class ServiceNowEndpointConfig:+ name: str+ """Stream name shown to the user."""+ table: str+ """The underlying ServiceNow table queried via the Table API."""+ primary_key: str = "sys_id"+ partition_key: str = "sys_created_on"+ """Stable creation timestamp used for datetime partitioning (never `sys_updated_on`)."""+ default_incremental_field: str = "sys_updated_on"+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(SERVICENOW_INCREMENTAL_FIELDS))+++# Default stream catalog, cross-referenced against the Airbyte/Fivetran ServiceNow+# connectors. Friendly stream names map to the canonical ITSM table names. Every table+# carries `sys_id`, `sys_created_on`, and `sys_updated_on`, so the incremental and+# partition config is uniform across all of them.+SERVICENOW_ENDPOINTS: dict[str, ServiceNowEndpointConfig] = {+ "incidents": ServiceNowEndpointConfig(name="incidents", table="incident"),+ "problems": ServiceNowEndpointConfig(name="problems", table="problem"),+ "change_requests": ServiceNowEndpointConfig(name="change_requests", table="change_request"),+ "change_tasks": ServiceNowEndpointConfig(name="change_tasks", table="change_task"),+ "tasks": ServiceNowEndpointConfig(name="tasks", table="task"),+ "catalog_requests": ServiceNowEndpointConfig(name="catalog_requests", table="sc_request"),+ "requested_items": ServiceNowEndpointConfig(name="requested_items", table="sc_req_item"),+ "catalog_tasks": ServiceNowEndpointConfig(name="catalog_tasks", table="sc_task"),+ "users": ServiceNowEndpointConfig(name="users", table="sys_user"),+ "user_groups": ServiceNowEndpointConfig(name="user_groups", table="sys_user_group"),+ "configuration_items": ServiceNowEndpointConfig(name="configuration_items", table="cmdb_ci"),+ "knowledge_articles": ServiceNowEndpointConfig(name="knowledge_articles", table="kb_knowledge"),+ "assets": ServiceNowEndpointConfig(name="assets", table="alm_asset"),+}++ENDPOINTS = tuple(SERVICENOW_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SERVICENOW_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/servicenow/source.py b/posthog/temporal/data_imports/sources/servicenow/source.pyindex f531f270bd40..037e25aa45c9 100644--- a/posthog/temporal/data_imports/sources/servicenow/source.py+++ b/posthog/temporal/data_imports/sources/servicenow/source.py@@ -1,19 +1,38 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 ServiceNowSourceConfig+from posthog.temporal.data_imports.sources.servicenow.servicenow import (+ ServiceNowAuth,+ ServiceNowResumeConfig,+ servicenow_source,+ validate_credentials as validate_servicenow_credentials,+)+from posthog.temporal.data_imports.sources.servicenow.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SERVICENOW_ENDPOINTS,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class ServiceNowSource(SimpleSource[ServiceNowSourceConfig]):+class ServiceNowSource(ResumableSource[ServiceNowSourceConfig, ServiceNowResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SERVICENOW@@ -23,7 +42,147 @@ class ServiceNowSource(SimpleSource[ServiceNowSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.SERVICE_NOW,label="ServiceNow",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync your ServiceNow ITSM data (incidents, problems, change requests, users, configuration items, and more) into the PostHog Data warehouse.++Enter your ServiceNow instance URL (e.g. `https://your-instance.service-now.com`) and authenticate with either an API key or a username and password.++The account or API key needs **read** access (the `rest_api_explorer` role or equivalent table ACLs) to the tables you want to sync.""",iconPath="/static/services/servicenow.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/servicenow",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="instance_url",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://your-instance.service-now.com",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="basic",+ options=[+ SourceFieldSelectConfigOption(+ label="Username and password",+ value="basic",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="admin",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="API key",+ value="api_key",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid ServiceNow credentials. Please update your credentials and reconnect.",+ "403 Client Error": "Your ServiceNow account is missing read access to one of the selected tables. Please grant access and try again.",+ }++ def _auth_for_config(self, config: ServiceNowSourceConfig) -> ServiceNowAuth:+ if config.auth_method.selection == "api_key":+ if not config.auth_method.api_key:+ raise ValueError("Missing ServiceNow API key")+ return ServiceNowAuth(api_key=config.auth_method.api_key)++ if not config.auth_method.username or not config.auth_method.password:+ raise ValueError("Missing ServiceNow username or password")+ return ServiceNowAuth(username=config.auth_method.username, password=config.auth_method.password)++ def get_schemas(+ self,+ config: ServiceNowSourceConfig,+ 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, []),+ )+ for endpoint in list(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: ServiceNowSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ auth = self._auth_for_config(config)+ except ValueError as exc:+ return False, str(exc)++ table = SERVICENOW_ENDPOINTS[schema_name].table if schema_name in SERVICENOW_ENDPOINTS else None+ return validate_servicenow_credentials(config.instance_url, auth, team_id, table=table)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ServiceNowResumeConfig]:+ return ResumableSourceManager[ServiceNowResumeConfig](inputs, ServiceNowResumeConfig)++ def source_for_pipeline(+ self,+ config: ServiceNowSourceConfig,+ resumable_source_manager: ResumableSourceManager[ServiceNowResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return servicenow_source(+ instance_url=config.instance_url,+ auth=self._auth_for_config(config),+ 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/servicenow/tests/test_servicenow.py b/posthog/temporal/data_imports/sources/servicenow/tests/test_servicenow.pynew file mode 100644index 000000000000..4a24cafe3024--- /dev/null+++ b/posthog/temporal/data_imports/sources/servicenow/tests/test_servicenow.py@@ -0,0 +1,271 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.servicenow import servicenow as servicenow_module+from posthog.temporal.data_imports.sources.servicenow.servicenow import (+ ServiceNowAuth,+ ServiceNowResumeConfig,+ _format_datetime,+ build_sysparm_query,+ get_rows,+ normalize_instance_url,+ servicenow_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.servicenow.settings import SERVICENOW_ENDPOINTS+++class FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = ""):+ self.status_code = status_code+ self._json = json_data if json_data is not None else {"result": []}+ self.text = text++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._json++ def raise_for_status(self) -> None:+ if not self.ok:+ response = requests.Response()+ response.status_code = self.status_code+ raise requests.HTTPError(f"{self.status_code} Client Error", response=response)+++class FakeResumeManager:+ def __init__(self, initial: ServiceNowResumeConfig | None = None):+ self.state = initial+ self.saved: list[ServiceNowResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> ServiceNowResumeConfig | None:+ return self.state++ def save_state(self, data: ServiceNowResumeConfig) -> None:+ self.state = data+ self.saved.append(data)+++def _patch_session(get_mock: mock.Mock) -> mock.MagicMock:+ session = mock.MagicMock()+ session.get = get_mock+ return session+++class TestNormalizeInstanceUrl:+ @parameterized.expand(+ [+ ("full_url", "https://acme.service-now.com", "https://acme.service-now.com"),+ ("trailing_slash", "https://acme.service-now.com/", "https://acme.service-now.com"),+ ("http_upgraded_host_only", "http://acme.service-now.com", "https://acme.service-now.com"),+ ("bare_subdomain", "dev12345", "https://dev12345.service-now.com"),+ ("host_with_dot_no_scheme", "acme.service-now.com", "https://acme.service-now.com"),+ ("whitespace", " acme.service-now.com ", "https://acme.service-now.com"),+ ("strips_path_and_query", "https://acme.service-now.com/foo?x=1", "https://acme.service-now.com"),+ ("strips_path_no_scheme", "acme.service-now.com/foo", "https://acme.service-now.com"),+ ("strips_userinfo", "https://user:[email protected]", "https://acme.service-now.com"),+ ("keeps_port", "https://acme.service-now.com:8443", "https://acme.service-now.com:8443"),+ ]+ )+ def test_normalize(self, _name: str, value: str, expected: str) -> None:+ assert normalize_instance_url(value) == expected++ def test_empty_raises(self) -> None:+ with pytest.raises(ValueError):+ normalize_instance_url("")+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("none", None, None),+ ("utc_datetime", datetime(2024, 3, 4, 2, 58, 14, tzinfo=UTC), "2024-03-04 02:58:14"),+ ("naive_datetime", datetime(2024, 3, 4, 2, 58, 14), "2024-03-04 02:58:14"),+ ("date_value", date(2024, 3, 4), "2024-03-04 00:00:00"),+ ("string_passthrough", "2024-03-04 02:58:14", "2024-03-04 02:58:14"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str | None) -> None:+ assert _format_datetime(value) == expected++ def test_aware_non_utc_is_converted(self) -> None:+ from datetime import timedelta, timezone++ aware = datetime(2024, 3, 4, 5, 0, 0, tzinfo=timezone(timedelta(hours=3)))+ assert _format_datetime(aware) == "2024-03-04 02:00:00"+++class TestBuildSysparmQuery:+ def test_incremental_query(self) -> None:+ query = build_sysparm_query("sys_updated_on", "2024-01-01 00:00:00", "sys_updated_on")+ assert query == "sys_updated_on>=2024-01-01 00:00:00^ORDERBYsys_updated_on"++ def test_full_refresh_query_orders_only(self) -> None:+ query = build_sysparm_query(None, None, "sys_created_on")+ assert query == "ORDERBYsys_created_on"++ def test_no_value_drops_filter(self) -> None:+ query = build_sysparm_query("sys_updated_on", None, "sys_updated_on")+ assert query == "ORDERBYsys_updated_on"+++class TestServiceNowAuth:+ def test_api_key_headers(self) -> None:+ auth = ServiceNowAuth(api_key="abc")+ assert auth.headers()["x-sn-apikey"] == "abc"+ assert auth.basic_auth() is None++ def test_basic_auth(self) -> None:+ auth = ServiceNowAuth(username="admin", password="secret")+ assert "x-sn-apikey" not in auth.headers()+ assert auth.basic_auth() == ("admin", "secret")+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("forbidden_no_table_accepted", 403, None, True),+ ("not_found", 404, None, False),+ ("forbidden_with_table_rejected", 403, "incident", False),+ ("ok_with_table", 200, "incident", True),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, table: str | None, expected_valid: bool) -> None:+ get_mock = mock.Mock(return_value=FakeResponse(status_code=status))+ with mock.patch.object(servicenow_module, "make_tracked_session", return_value=_patch_session(get_mock)):+ valid, _ = validate_credentials(+ "https://acme.service-now.com", ServiceNowAuth(api_key="x"), team_id=1, table=table+ )+ assert valid is expected_valid++ def test_redirect_is_rejected(self) -> None:+ get_mock = mock.Mock(return_value=FakeResponse(status_code=302))+ with mock.patch.object(servicenow_module, "make_tracked_session", return_value=_patch_session(get_mock)):+ valid, error = validate_credentials("https://acme.service-now.com", ServiceNowAuth(api_key="x"), team_id=1)+ assert valid is False+ assert error is not None+ # redirects must not be followed (SSRF guard)+ assert get_mock.call_args.kwargs["allow_redirects"] is False++ def test_invalid_instance_url(self) -> None:+ valid, error = validate_credentials("", ServiceNowAuth(api_key="x"), team_id=1)+ assert valid is False+ assert error is not None++ def test_network_error_is_handled(self) -> None:+ get_mock = mock.Mock(side_effect=requests.ConnectionError("boom"))+ with mock.patch.object(servicenow_module, "make_tracked_session", return_value=_patch_session(get_mock)):+ valid, error = validate_credentials("https://acme.service-now.com", ServiceNowAuth(api_key="x"), team_id=1)+ assert valid is False+ assert error is not None+++class TestGetRows:+ def _run(+ self,+ pages: dict[int, list[dict[str, Any]]],+ manager: FakeResumeManager,+ page_size: int = 2,+ **kwargs: Any,+ ) -> tuple[list[list[dict[str, Any]]], list[dict[str, Any]]]:+ captured_params: list[dict[str, Any]] = []++ def fake_get(url: str, params: dict[str, Any], **_: Any) -> FakeResponse:+ captured_params.append(params)+ offset = params["sysparm_offset"]+ return FakeResponse(json_data={"result": pages.get(offset, [])})++ get_mock = mock.Mock(side_effect=fake_get)+ with (+ mock.patch.object(servicenow_module, "DEFAULT_PAGE_SIZE", page_size),+ mock.patch.object(servicenow_module, "make_tracked_session", return_value=_patch_session(get_mock)),+ ):+ batches = list(+ get_rows(+ base_url="https://acme.service-now.com",+ table="incident",+ auth=ServiceNowAuth(api_key="x"),+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ )+ )+ return batches, captured_params++ def test_paginates_until_short_page(self) -> None:+ pages = {+ 0: [{"sys_id": "1"}, {"sys_id": "2"}],+ 2: [{"sys_id": "3"}], # short page terminates iteration+ }+ manager = FakeResumeManager()+ batches, params = self._run(pages, manager, page_size=2)++ assert [len(b) for b in batches] == [2, 1]+ # state saved after each yielded batch, pointing at the next offset+ assert [s.offset for s in manager.saved] == [2, 4]+ assert params[0]["sysparm_offset"] == 0+ assert params[1]["sysparm_offset"] == 2++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = FakeResumeManager()+ batches, _ = self._run({0: []}, manager, page_size=2)+ assert batches == []+ assert manager.saved == []++ def test_resumes_from_saved_offset(self) -> None:+ pages = {+ 4: [{"sys_id": "5"}],+ }+ manager = FakeResumeManager(initial=ServiceNowResumeConfig(offset=4))+ batches, params = self._run(pages, manager, page_size=2)++ assert [len(b) for b in batches] == [1]+ assert params[0]["sysparm_offset"] == 4++ def test_incremental_query_in_params(self) -> None:+ manager = FakeResumeManager()+ _, params = self._run(+ {0: []},+ manager,+ page_size=2,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="sys_updated_on",+ )+ assert params[0]["sysparm_query"] == "sys_updated_on>=2024-01-01 00:00:00^ORDERBYsys_updated_on"++ def test_full_refresh_query_in_params(self) -> None:+ manager = FakeResumeManager()+ _, params = self._run({0: []}, manager, page_size=2, should_use_incremental_field=False)+ assert params[0]["sysparm_query"] == "ORDERBYsys_created_on"+++class TestServiceNowSource:+ @parameterized.expand(list(SERVICENOW_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint: str) -> None:+ response = servicenow_source(+ instance_url="https://acme.service-now.com",+ auth=ServiceNowAuth(api_key="x"),+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(), # type: ignore[arg-type]+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == ["sys_id"]+ assert response.partition_keys == ["sys_created_on"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"diff --git a/posthog/temporal/data_imports/sources/servicenow/tests/test_servicenow_source.py b/posthog/temporal/data_imports/sources/servicenow/tests/test_servicenow_source.pynew file mode 100644index 000000000000..84dfcc33609b--- /dev/null+++ b/posthog/temporal/data_imports/sources/servicenow/tests/test_servicenow_source.py@@ -0,0 +1,172 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import ServiceNowAuthMethodConfig, ServiceNowSourceConfig+from posthog.temporal.data_imports.sources.servicenow.servicenow import ServiceNowAuth, ServiceNowResumeConfig+from posthog.temporal.data_imports.sources.servicenow.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.servicenow.source import ServiceNowSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _basic_config(username: str = "admin", password: str = "secret") -> ServiceNowSourceConfig:+ return ServiceNowSourceConfig(+ instance_url="https://acme.service-now.com",+ auth_method=ServiceNowAuthMethodConfig(selection="basic", username=username, password=password),+ )+++def _api_key_config(api_key: str = "key123") -> ServiceNowSourceConfig:+ return ServiceNowSourceConfig(+ instance_url="https://acme.service-now.com",+ auth_method=ServiceNowAuthMethodConfig(selection="api_key", api_key=api_key),+ )+++def _source_inputs(schema_name: str = "incidents", incremental: bool = False) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=incremental,+ db_incremental_field_last_value="2024-01-01 00:00:00" if incremental else None,+ db_incremental_field_earliest_value=None,+ incremental_field="sys_updated_on" if incremental else None,+ incremental_field_type=None,+ job_id="job-1",+ logger=mock.MagicMock(),+ reset_pipeline=False,+ )+++class TestServiceNowSource:+ def setup_method(self) -> None:+ self.source = ServiceNowSource()+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SERVICENOW++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "ServiceNow"+ assert config.label == "ServiceNow"+ assert config.unreleasedSource is not True+ assert config.releaseStatus == ReleaseStatus.ALPHA++ field_names = [f.name for f in config.fields]+ assert field_names == ["instance_url", "auth_method"]++ instance_field = config.fields[0]+ assert isinstance(instance_field, SourceFieldInputConfig)+ assert instance_field.required is True++ auth_field = config.fields[1]+ assert isinstance(auth_field, SourceFieldSelectConfig)+ assert {option.value for option in auth_field.options} == {"basic", "api_key"}++ def test_non_retryable_errors(self) -> None:+ errors = self.source.get_non_retryable_errors()+ assert "401 Client Error" in errors+ assert "403 Client Error" in errors++ def test_get_schemas_all_incremental(self) -> None:+ schemas = self.source.get_schemas(_api_key_config(), self.team_id)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental for s in schemas)+ assert all(s.supports_append for s in schemas)+ # both audit timestamps are advertised as incremental options+ assert all({f["field"] for f in s.incremental_fields} == {"sys_updated_on", "sys_created_on"} for s in schemas)++ def test_get_schemas_filtered_by_name(self) -> None:+ schemas = self.source.get_schemas(_api_key_config(), self.team_id, names=["incidents"])+ assert len(schemas) == 1+ assert schemas[0].name == "incidents"++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(_api_key_config(), self.team_id, names=["nope"]) == []++ def test_auth_for_config_api_key(self) -> None:+ auth = self.source._auth_for_config(_api_key_config("abc"))+ assert auth == ServiceNowAuth(api_key="abc")++ def test_auth_for_config_basic(self) -> None:+ auth = self.source._auth_for_config(_basic_config("u", "p"))+ assert auth == ServiceNowAuth(username="u", password="p")++ def test_auth_for_config_missing_api_key_raises(self) -> None:+ config = ServiceNowSourceConfig(+ instance_url="https://acme.service-now.com",+ auth_method=ServiceNowAuthMethodConfig(selection="api_key"),+ )+ with pytest.raises(ValueError):+ self.source._auth_for_config(config)++ def test_auth_for_config_missing_basic_raises(self) -> None:+ config = ServiceNowSourceConfig(+ instance_url="https://acme.service-now.com",+ auth_method=ServiceNowAuthMethodConfig(selection="basic", username="only-user"),+ )+ with pytest.raises(ValueError):+ self.source._auth_for_config(config)++ @mock.patch("posthog.temporal.data_imports.sources.servicenow.source.validate_servicenow_credentials")+ def test_validate_credentials_success(self, mock_validate: mock.Mock) -> None:+ mock_validate.return_value = (True, None)+ valid, error = self.source.validate_credentials(_api_key_config(), self.team_id)+ assert valid is True+ assert error is None++ @mock.patch("posthog.temporal.data_imports.sources.servicenow.source.validate_servicenow_credentials")+ def test_validate_credentials_maps_schema_to_table(self, mock_validate: mock.Mock) -> None:+ mock_validate.return_value = (True, None)+ self.source.validate_credentials(_api_key_config(), self.team_id, schema_name="incidents")++ _, kwargs = mock_validate.call_args+ assert kwargs["table"] == "incident"++ @mock.patch("posthog.temporal.data_imports.sources.servicenow.source.validate_servicenow_credentials")+ def test_validate_credentials_no_schema_passes_none_table(self, mock_validate: mock.Mock) -> None:+ mock_validate.return_value = (True, None)+ self.source.validate_credentials(_basic_config(), self.team_id)++ _, kwargs = mock_validate.call_args+ assert kwargs["table"] is None++ def test_validate_credentials_missing_creds(self) -> None:+ config = ServiceNowSourceConfig(+ instance_url="https://acme.service-now.com",+ auth_method=ServiceNowAuthMethodConfig(selection="api_key"),+ )+ valid, error = self.source.validate_credentials(config, self.team_id)+ assert valid is False+ assert error is not None++ def test_get_resumable_source_manager(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ServiceNowResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.servicenow.source.servicenow_source")+ def test_source_for_pipeline_plumbing(self, mock_source: mock.Mock) -> None:+ config = _api_key_config("abc")+ inputs = _source_inputs(schema_name="problems", incremental=True)+ manager = mock.MagicMock()++ self.source.source_for_pipeline(config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["instance_url"] == "https://acme.service-now.com"+ assert kwargs["auth"] == ServiceNowAuth(api_key="abc")+ assert kwargs["endpoint"] == "problems"+ assert kwargs["team_id"] == 1+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01 00:00:00"+ assert kwargs["incremental_field"] == "sys_updated_on"diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex df57d8094efa..c6eeb073080b 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -268,6 +268,12 @@ def strip_sensitive_from_dict(data: dict, nonsensitive: set[str], sensitive: set# (and therefore exfiltrate credentials via a poisoned SSH tunnel — VERIA-311)._SSH_TUNNEL_CONNECTION_FIELDS = ("enabled", "host", "port")+# Top-level job_input fields that name the connection target. Changing any of them+# repoints the source at a different server, so preserved credentials must not be+# reused without re-entry (e.g. ServiceNow's `instance_url` could otherwise be swapped+# to an attacker host that then receives the stored API key / password — VERIA-311).+_CONNECTION_TARGET_FIELDS = ("host", "instance_url")+def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:"""True if the SSH tunnel's connection target (enabled/host/port) changed.@@ -286,6 +292,42 @@ def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:return any(_coerce(existing.get(key)) != _coerce(incoming.get(key)) for key in _SSH_TUNNEL_CONNECTION_FIELDS)+# Nested SourceFieldSelectConfig containers (Stripe `auth_method`, Snowflake `auth_type`,+# ServiceNow `auth_method`) keep their secrets one level down, not at the top level.+_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type")+++def has_preserved_credentials(existing: dict[str, Any], incoming: dict[str, Any], sensitive_fields: set[str]) -> bool:+ """True if any stored secret would be reused because the update didn't re-supply it.++ Checks both top-level secret fields and the nested auth containers where sources like+ ServiceNow, Stripe and Snowflake keep their credentials. Used to force credential+ re-entry when the connection target changes, so a redirected host can't receive a+ preserved secret. A secret only counts as preserved when it would survive the merge:+ an absent container carries the whole existing block over, a same-selection container+ preserves any field the update omits, and a selection switch replaces the block wholesale.+ """+ if any(existing.get(key) and not incoming.get(key) for key in sensitive_fields):+ return True++ for container_key in _NESTED_AUTH_CONTAINERS:+ existing_container = existing.get(container_key)+ if not isinstance(existing_container, dict):+ continue+ incoming_container = incoming.get(container_key)+ if not isinstance(incoming_container, dict):+ # Container not re-supplied — the existing secrets carry over wholesale.+ if any(existing_container.get(key) for key in sensitive_fields):+ return True+ continue+ if existing_container.get("selection") != incoming_container.get("selection"):+ continue+ if any(existing_container.get(key) and not incoming_container.get(key) for key in sensitive_fields):+ return True++ return False++def get_direct_postgres_connection_metadata(*,source_impl: Any,@@ -712,10 +754,13 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializernew_job_inputs = {**existing_job_inputs, **incoming_job_inputs}- # If the connection host changed, require credentials to be re-entered.- connection_host_changed = "host" in incoming_job_inputs and incoming_job_inputs[- "host"- ] != existing_job_inputs.get("host")+ # If the connection target changed, require credentials to be re-entered. Covers+ # both the generic `host` field and source-specific URL fields like ServiceNow's+ # `instance_url`, so a stored credential can't be redirected to a new host.+ connection_host_changed = any(+ field in incoming_job_inputs and incoming_job_inputs[field] != existing_job_inputs.get(field)+ for field in _CONNECTION_TARGET_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@@ -735,10 +780,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializermanifest_host_added = bool(new_hosts - existing_hosts)if connection_host_changed or ssh_tunnel_changed or manifest_host_added:- missing_credentials = [- key for key in sensitive_fields if existing_job_inputs.get(key) and not incoming_job_inputs.get(key)- ]- if missing_credentials:+ if has_preserved_credentials(existing_job_inputs, incoming_job_inputs, sensitive_fields):if ssh_tunnel_changed:raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")if manifest_host_added: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 2cfb13444e19..5dcae86c868c 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@@ -4010,6 +4010,65 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["password"] == "new_password"mock_validate_credentials.assert_called_once()+ def _servicenow_source(self) -> ExternalDataSource:+ # ServiceNow's connection target is `instance_url` (not a top-level `host`) and its+ # secret lives nested inside the `auth_method` container.+ 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="ServiceNow",+ created_by=self.user,+ prefix="servicenow_src",+ job_inputs={+ "instance_url": "https://acme.service-now.com",+ "auth_method": {"selection": "api_key", "api_key": "sk_existing"},+ },+ )++ @patch(+ "posthog.temporal.data_imports.sources.servicenow.source.ServiceNowSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_servicenow_instance_url_change_without_credentials_is_rejected(self, mock_validate_credentials):+ source = self._servicenow_source()++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"instance_url": "https://attacker.example.com"}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ source.refresh_from_db()+ assert source.job_inputs["instance_url"] == "https://acme.service-now.com"+ assert source.job_inputs["auth_method"]["api_key"] == "sk_existing"+ mock_validate_credentials.assert_not_called()++ @patch(+ "posthog.temporal.data_imports.sources.servicenow.source.ServiceNowSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_servicenow_instance_url_change_with_credentials_succeeds(self, mock_validate_credentials):+ source = self._servicenow_source()++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "instance_url": "https://new-instance.service-now.com",+ "auth_method": {"selection": "api_key", "api_key": "sk_new"},+ },+ },+ )++ assert response.status_code == 200, response.json()+ source.refresh_from_db()+ assert source.job_inputs["instance_url"] == "https://new-instance.service-now.com"+ assert source.job_inputs["auth_method"]["api_key"] == "sk_new"+ mock_validate_credentials.assert_called_once()+def _custom_source(self, base_url: str, resource_paths: list[str] | None = None) -> ExternalDataSource:paths = resource_paths if resource_paths is not None else ["/users"]manifest = {