: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
fix(data-warehouse): re-enter credentials on custom source host change (#60609)
Marcus Hof4d1b659cb85f
diff --git a/posthog/temporal/data_imports/sources/common/rest_source/rest_client.py b/posthog/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 248d3a83aac1..3ff1af60ebbc 100644--- a/posthog/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/posthog/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -2,7 +2,6 @@ import copyimport loggingfrom collections.abc import Callable, Iteratorfrom typing import Any, Optional-from urllib.parse import urljoinfrom requests import Request, Response, Sessionfrom requests.auth import AuthBase@@ -14,6 +13,7 @@ from .auth import auth_secret_valuesfrom .exceptions import IgnoreResponseExceptionfrom .jsonpath_utils import TJsonPath, find_valuesfrom .paginators import BasePaginator+from .utils import resolve_request_urllogger = logging.getLogger(__name__)@@ -61,12 +61,7 @@ class RESTClient:self.session.headers.update(self.headers)def _join_url(self, path: str) -> str:- if path.startswith(("http://", "https://")):- return path- base = self.base_url- if not base.endswith("/"):- base += "/"- return urljoin(base, path.lstrip("/"))+ return resolve_request_url(self.base_url, path)def paginate(self,diff --git a/posthog/temporal/data_imports/sources/common/rest_source/utils.py b/posthog/temporal/data_imports/sources/common/rest_source/utils.pyindex 25a56a55442c..99ff0b62f186 100644--- a/posthog/temporal/data_imports/sources/common/rest_source/utils.py+++ b/posthog/temporal/data_imports/sources/common/rest_source/utils.py@@ -1,5 +1,6 @@from collections.abc import Iterable, Mappingfrom typing import Any+from urllib.parse import urljoindef join_url(base_url: str, path: str) -> str:@@ -8,6 +9,24 @@ def join_url(base_url: str, path: str) -> str:return base_url + path.lstrip("/")+def resolve_request_url(base_url: str, path: str) -> str:+ """Resolve a (possibly relative) request path against ``base_url`` — the exact URL a+ request is sent to at runtime.++ Centralized so callers that must *predict* the destination host (the custom-source+ retarget guard, its URL validator, and its credential probe) resolve it the same way+ the engine does. A literal ``http(s)://`` path is returned untouched; anything else is+ joined onto ``base_url``. The ``urljoin`` strips leading whitespace/control chars and+ normalizes the scheme before parsing, so ``" HTTPS://attacker"`` resolves to the+ attacker host here too — a string ``startswith`` check would miss it and let a+ credential be retargeted past the re-entry gate.+ """+ if path.startswith(("http://", "https://")):+ return path+ base = base_url if base_url.endswith("/") else base_url + "/"+ return urljoin(base, path.lstrip("/"))++def exclude_keys(d: Mapping[str, Any], keys: Iterable[str]) -> dict[str, Any]:"""Removes specified keys from a dictionary and returns a new dictionary."""return {k: v for k, v in d.items() if k not in keys}diff --git a/posthog/temporal/data_imports/sources/custom/source.py b/posthog/temporal/data_imports/sources/custom/source.pyindex e450ce11711c..ed4f96a34afd 100644--- a/posthog/temporal/data_imports/sources/custom/source.py+++ b/posthog/temporal/data_imports/sources/custom/source.py@@ -22,6 +22,7 @@ from posthog.temporal.data_imports.sources.common.registry import SourceRegistryfrom posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resourcefrom posthog.temporal.data_imports.sources.common.rest_source.auth import auth_secret_valuesfrom posthog.temporal.data_imports.sources.common.rest_source.config_setup import create_auth+from posthog.temporal.data_imports.sources.common.rest_source.utils import resolve_request_urlfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import CustomSourceConfigfrom posthog.temporal.data_imports.util import NonRetryableException@@ -160,23 +161,125 @@ def validate_manifest_urls(manifest: dict[str, Any], team_id: int) -> tuple[boolif not ok:return False, f"Invalid base_url: {err}"+ base_host = _url_hostname(base_url)for resource in manifest["resources"]:- path = resource.get("endpoint", {}).get("path", "")- if path.startswith(("http://", "https://")):- ok, err = _check_url(path, team_id)- if not ok:- return False, f"Resource {resource['name']!r}: {err}"+ # Resolve exactly as the engine will (so a whitespace/case-disguised absolute path+ # is caught), then only re-vet resources that resolve to a *different* host than+ # base_url — `_is_host_safe` does a DNS lookup, so don't re-resolve base per resource.+ resolved = _endpoint_request_url(base_url, resource.get("endpoint"))+ if resolved is None or _url_hostname(resolved) == base_host:+ continue+ ok, err = _check_url(resolved, team_id)+ if not ok:+ return False, f"Resource {resource['name']!r}: {err}"return True, Nonedef _check_url(url: str, team_id: int) -> tuple[bool, str | None]:- parsed = urlparse(url)- if not parsed.hostname:+ # `_url_hostname` mirrors the real connect host (backslash/whitespace-normalized) so the+ # validator can't be fooled into vetting a different host than the request reaches.+ hostname = _url_hostname(url)+ if not hostname:return False, f"URL {url!r} is missing a hostname"- if is_cloud() and parsed.scheme != "https":+ if is_cloud() and urlparse(url).scheme != "https":return False, f"URL {url!r} must use https:// on PostHog Cloud"- return _is_host_safe(parsed.hostname, team_id)+ return _is_host_safe(hostname, team_id)+++class _LeaveMissing(dict):+ """Format mapping that leaves unknown ``{name}`` placeholders untouched."""++ def __missing__(self, key: str) -> str:+ return "{" + key + "}"+++def _endpoint_request_url(base_url: str, endpoint: Any) -> str | None:+ """The URL an endpoint will send a request — and the credential — to.++ The REST engine binds scalar ``params`` into the path (``_bind_path_params`` runs+ ``path.format(**params)``) and then resolves it against ``base_url`` via+ ``resolve_request_url``. We do exactly the same here, so a template like ``"{target}"``+ (``params={"target": "https://attacker/"}``) or ``"{scheme}://attacker/"``+ (``params={"scheme": "https"}``) — and any whitespace/case/encoding-disguised absolute+ URL — resolves to the same destination the runtime would request. Returns ``None`` for a+ non-dict endpoint or a missing/non-string path. (SSRF to internal hosts is separately+ caught at request time by the transport-layer guard; this is about detecting a *new+ destination* for the credential re-entry check.)+ """+ if not isinstance(endpoint, dict):+ return None+ path = endpoint.get("path")+ if not isinstance(path, str):+ return None++ params = endpoint.get("params")+ bindable = (+ _LeaveMissing({name: value for name, value in params.items() if isinstance(value, str)})+ if isinstance(params, dict)+ else _LeaveMissing()+ )+ try:+ resolved = path.format_map(bindable)+ except (ValueError, IndexError, KeyError):+ # Malformed / positional format string — it's re-vetted at request time anyway.+ resolved = path++ return resolve_request_url(base_url, resolved)+++def manifest_request_hosts(manifest_json: Any) -> frozenset[str]:+ """Hostnames a stored manifest will send requests — and the credential — to.++ Lets the API layer detect when an update retargets the source at a new host+ so it can require the credential to be re-entered: an editor who can't read+ the stored secret must not be able to redirect it to a server they control.+ Returns an empty set for anything unparseable — the caller treats "no hosts"+ as "nothing new", and a malformed manifest is rejected elsewhere.+ """+ if not isinstance(manifest_json, str):+ return frozenset()+ try:+ manifest = json.loads(manifest_json)+ except json.JSONDecodeError:+ return frozenset()+ if not isinstance(manifest, dict):+ return frozenset()++ client = manifest.get("client")+ base_url = client.get("base_url") if isinstance(client, dict) else None+ # Resolve resource paths against base_url the same way the engine does. With no usable+ # base_url an absolute resource path still has a host; a relative one is left hostless+ # (its destination is unknown) — the manifest is rejected elsewhere for the missing base.+ base_for_resolve = base_url if isinstance(base_url, str) else ""++ urls: list[str] = [base_url] if isinstance(base_url, str) else []+ resources = manifest.get("resources")+ if isinstance(resources, list):+ for resource in resources:+ endpoint = resource.get("endpoint") if isinstance(resource, dict) else None+ resolved = _endpoint_request_url(base_for_resolve, endpoint)+ if resolved is not None:+ urls.append(resolved)++ # `_url_hostname` returns an already-lowercased host.+ hosts = {host for url in urls if (host := _url_hostname(url))}+ return frozenset(hosts)+++def _url_hostname(url: str) -> str | None:+ """The host the HTTP client will actually connect to.++ `urlparse` treats a backslash — and its ``%5c`` encoding — as ordinary+ userinfo, so ``https://evil.example\\@trusted.example/`` parses as host+ ``trusted.example`` here, while requests/urllib3 (per the WHATWG URL rules)+ treat ``\\`` as a path separator and connect to ``evil.example``. Normalizing+ those to ``/`` before parsing keeps the retarget guard aligned with the real+ destination, so an ambiguous-authority URL can't smuggle the credential to a+ new host while appearing unchanged.+ """+ normalized = url.replace("\\", "/").replace("%5c", "/").replace("%5C", "/")+ return urlparse(normalized).hostname@SourceRegistry.register@@ -315,7 +418,8 @@ class CustomSource(SimpleSource[CustomSourceConfig]):endpoint = resource.get("endpoint", {})method = (endpoint.get("method") or "GET").upper()path = endpoint.get("path", "")- url = path if path.startswith(("http://", "https://")) else f"{base_url.rstrip('/')}/{path.lstrip('/')}"+ # Resolve via the shared helper so the probe hits the same host the sync will.+ url = resolve_request_url(base_url, path)# Replay the configured query params and request body so the probe# matches what the sync sends — an endpoint that needs them shouldn't# answer differently at probe vs sync time.diff --git a/posthog/temporal/data_imports/sources/custom/test_custom_source.py b/posthog/temporal/data_imports/sources/custom/test_custom_source.pyindex 68b527ce0566..f1aef652e890 100644--- a/posthog/temporal/data_imports/sources/custom/test_custom_source.py+++ b/posthog/temporal/data_imports/sources/custom/test_custom_source.py@@ -11,6 +11,7 @@ from posthog.temporal.data_imports.sources.custom.source import (CustomSource,ManifestValidationError,is_custom_source_available_for_team,+ manifest_request_hosts,validate_manifest,validate_manifest_urls,)@@ -155,6 +156,20 @@ class TestValidateManifestUrls(SimpleTestCase):assert not okassert "users" in (err or "")+ @override_settings(CLOUD_DEPLOYMENT="US")+ @patch(+ "posthog.temporal.data_imports.sources.custom.source._is_host_safe",+ side_effect=lambda host, team_id: (host != "127.0.0.1", None if host != "127.0.0.1" else "blocked"),+ )+ def test_rejects_whitespace_prefixed_internal_path(self, _mock):+ # A leading space makes the raw `startswith` check miss the absolute URL, but urljoin+ # strips it and the sync reaches 127.0.0.1 — the validator must resolve it the same way.+ manifest = _minimal_manifest()+ manifest["resources"][0]["endpoint"]["path"] = " https://127.0.0.1/leak"+ ok, err = validate_manifest_urls(manifest, team_id=999)+ assert not ok+ assert "users" in (err or "")+@parameterized.expand([("http_public", "http://api.example.com"),@@ -480,6 +495,127 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):assert err is not None+class TestManifestRequestHosts(SimpleTestCase):+ def _manifest(self, base_url: str, resource_paths: list[str]) -> str:+ return json.dumps(+ {+ "client": {"base_url": base_url},+ "resources": [{"name": f"r{i}", "endpoint": {"path": p}} for i, p in enumerate(resource_paths)],+ }+ )++ def test_base_url_host(self):+ assert manifest_request_hosts(self._manifest("https://api.example.com/v1", ["/users"])) == frozenset(+ {"api.example.com"}+ )++ def test_absolute_resource_paths_add_hosts(self):+ # Relative paths inherit base_url's host; only absolute URLs introduce a new host.+ manifest = self._manifest("https://api.example.com", ["/users", "https://cdn.other.net/data"])+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "cdn.other.net"})++ def test_path_param_absolute_url_is_collected(self):+ # A scalar param bound into a "{placeholder}" becomes the request URL at sync time+ # (_bind_path_params), so its host must be tracked even though the literal path is relative.+ manifest = json.dumps(+ {+ "client": {"base_url": "https://api.example.com"},+ "resources": [+ {+ "name": "r",+ "endpoint": {"path": "{target}", "params": {"target": "https://attacker.example.net/"}},+ }+ ],+ }+ )+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "attacker.example.net"})++ def test_path_param_split_scheme_is_resolved(self):+ # The absolute URL is split across the template and a param ("{scheme}://host" ++ # {"scheme": "https"}); neither piece is a URL on its own, but the bound path is.+ manifest = json.dumps(+ {+ "client": {"base_url": "https://api.example.com"},+ "resources": [+ {+ "name": "r",+ "endpoint": {"path": "{scheme}://attacker.example.net/data", "params": {"scheme": "https"}},+ }+ ],+ }+ )+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "attacker.example.net"})++ def test_uppercase_scheme_absolute_path_adds_host(self):+ # urljoin treats `HTTPS://host` as absolute (schemes are case-insensitive), so a+ # mixed-case scheme must still register the new host — otherwise an editor who can't+ # read the stored secret could retarget the preserved credential past the re-entry gate.+ manifest = self._manifest("https://api.example.com", ["HTTPS://attacker.example.net/data"])+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "attacker.example.net"})++ def test_uppercase_scheme_split_across_param_adds_host(self):+ # Same retarget bypass via a split scheme: "{scheme}://host" + {"scheme": "HTTPS"}.+ manifest = json.dumps(+ {+ "client": {"base_url": "https://api.example.com"},+ "resources": [+ {+ "name": "r",+ "endpoint": {"path": "{scheme}://attacker.example.net/data", "params": {"scheme": "HTTPS"}},+ }+ ],+ }+ )+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "attacker.example.net"})++ @parameterized.expand(+ [+ ("leading_space", " https://attacker.example.net/data"),+ ("leading_tab", "\thttps://attacker.example.net/data"),+ ("leading_newline", "\nhttps://attacker.example.net/data"),+ ("leading_nul", "\x00https://attacker.example.net/data"),+ ("leading_space_uppercase", " HTTPS://attacker.example.net/data"),+ ]+ )+ def test_whitespace_prefixed_absolute_path_adds_host(self, _name, path):+ # urljoin strips leading whitespace/control chars before parsing the scheme, so the+ # sync requests attacker.example.net while a raw `startswith` check sees no new host —+ # the retarget guard must resolve the path the same way the engine does.+ manifest = self._manifest("https://api.example.com", [path])+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "attacker.example.net"})++ def test_url_param_not_referenced_in_path_is_ignored(self):+ # A URL-valued query param that isn't a path placeholder is a normal query value, not a+ # request destination — it must not be counted (avoids false re-entry prompts).+ manifest = json.dumps(+ {+ "client": {"base_url": "https://api.example.com"},+ "resources": [+ {"name": "r", "endpoint": {"path": "/users", "params": {"callback": "https://other.net/"}}}+ ],+ }+ )+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com"})++ def test_backslash_authority_resolves_to_real_host(self):+ # `https://evil\@trusted/` connects to `evil` (urllib3/WHATWG) even though urlparse+ # alone reads `trusted` — the guard must see the real destination, not be fooled.+ manifest = json.dumps(+ {+ "client": {"base_url": "https://attacker.example.net\\@api.example.com/"},+ "resources": [{"name": "r", "endpoint": {"path": "/users"}}],+ }+ )+ assert manifest_request_hosts(manifest) == frozenset({"attacker.example.net"})++ def test_host_is_lowercased(self):+ assert manifest_request_hosts(self._manifest("https://API.Example.COM", [])) == frozenset({"api.example.com"})++ @parameterized.expand([("not json", "{nope}"), ("non_string", 123), ("none", None), ("json_array", "[1, 2]")])+ def test_unparseable_returns_empty(self, _name, raw):+ assert manifest_request_hosts(raw) == frozenset()++class TestIsCustomSourceAvailableForTeam(SimpleTestCase):@override_settings(CLOUD_DEPLOYMENT="US")def test_allows_pilot_team_on_us_cloud(self):diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex d5658fe6a40e..3d1131a1d643 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -48,7 +48,10 @@ from posthog.temporal.data_imports.sources.common.config import Configfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_by_enabled_columns, sql_schema_metadatafrom posthog.temporal.data_imports.sources.common.sql.base import SQLSource-from posthog.temporal.data_imports.sources.custom.source import is_custom_source_available_for_team+from posthog.temporal.data_imports.sources.custom.source import (+ is_custom_source_available_for_team,+ manifest_request_hosts,+)from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfigfrom posthog.temporal.data_imports.sources.postgres.source import PostgresSource@@ -708,13 +711,24 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerincoming_job_inputs.get("ssh_tunnel"),)- if connection_host_changed or ssh_tunnel_changed:+ # The custom source's connection target lives inside the manifest, not a top-level `host`.+ # A manifest edit that introduces a new request host would send the preserved credential+ # somewhere it wasn't going before — the same exfiltration risk, so require re-entry too.+ manifest_host_added = False+ if source_type_model == ExternalDataSourceType.CUSTOM and "manifest_json" in incoming_job_inputs:+ new_hosts = manifest_request_hosts(incoming_job_inputs.get("manifest_json"))+ existing_hosts = manifest_request_hosts(existing_job_inputs.get("manifest_json"))+ manifest_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 ssh_tunnel_changed:raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")+ if manifest_host_added:+ raise ValidationError("Changing the manifest's request host requires re-entering your credentials.")raise ValidationError("Changing the connection host requires re-entering your credentials.")# Preserve sensitive credentials not explicitly provided (API response omits them for security)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 483d981e5e9d..e848ea0e5583 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@@ -1,3 +1,4 @@+import jsonimport uuidimport typing as tfrom typing import cast@@ -3891,6 +3892,191 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["password"] == "new_password"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 = {+ "client": {"base_url": base_url, "auth": {"type": "api_key", "name": "key", "location": "query"}},+ "resources": [{"name": f"resource_{i}", "endpoint": {"path": p}} for i, p in enumerate(paths)],+ }+ 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="Custom",+ created_by=self.user,+ prefix="custom_src",+ job_inputs={"manifest_json": json.dumps(manifest), "auth_api_key": "sk_existing"},+ )++ @parameterized.expand([("without_credentials", {}, 400), ("with_credentials", {"auth_api_key": "sk_new"}, 200)])+ @patch(+ "posthog.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_custom_source_manifest_host_change(+ self, _name, extra_creds, expected_status, mock_validate_credentials+ ):+ # The custom source's host lives inside the manifest. Retargeting it to a new host requires+ # re-supplying the secret; without it the preserved credential would reach a server the editor+ # chose, so the change is rejected and nothing is persisted.+ source = self._custom_source("https://api.example.com")+ new_manifest = {+ "client": {+ "base_url": "https://attacker.example.net",+ "auth": {"type": "api_key", "name": "key", "location": "query"},+ },+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],+ }++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest), **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()+ persisted_host = "attacker.example.net" if expected_status == 200 else "api.example.com"+ assert persisted_host in source.job_inputs["manifest_json"]+ # 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.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_custom_source_ambiguous_authority_host_change_is_rejected(self, mock_validate_credentials):+ # `https://attacker\@api.example.com/` connects to `attacker` (urllib3/WHATWG) but parses as+ # `api.example.com` under naive urlparse — the guard must see the real host and require re-entry.+ source = self._custom_source("https://api.example.com")+ new_manifest = {+ "client": {+ "base_url": "https://attacker.example.net\\@api.example.com/",+ "auth": {"type": "api_key", "name": "key", "location": "query"},+ },+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],+ }++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest)}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ mock_validate_credentials.assert_not_called()++ @patch(+ "posthog.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_custom_source_same_host_manifest_edit_keeps_credentials(self, mock_validate_credentials):+ # Editing a manifest without introducing a new host (e.g. tweaking a path) must not force+ # the user to re-enter the credential — the destination is unchanged.+ source = self._custom_source("https://api.example.com")+ new_manifest = {+ "client": {+ "base_url": "https://api.example.com",+ "auth": {"type": "api_key", "name": "key", "location": "query"},+ },+ "resources": [{"name": "users", "endpoint": {"path": "/v2/users"}}],+ }++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest)}},+ )++ assert response.status_code == 200, response.json()+ source.refresh_from_db()+ assert source.job_inputs["auth_api_key"] == "sk_existing"+ mock_validate_credentials.assert_called_once()++ @patch(+ "posthog.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_custom_source_path_param_host_injection_is_rejected(self, mock_validate_credentials):+ # The new host is hidden in a path-param value (resolved into the path at sync time), not the+ # literal path — the guard must still detect it and require re-entry.+ source = self._custom_source("https://api.example.com")+ new_manifest = {+ "client": {+ "base_url": "https://api.example.com",+ "auth": {"type": "api_key", "name": "key", "location": "query"},+ },+ "resources": [+ {+ "name": "users",+ "endpoint": {"path": "{target}", "params": {"target": "https://attacker.example.net/"}},+ }+ ],+ }++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest)}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ mock_validate_credentials.assert_not_called()++ @patch(+ "posthog.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_custom_source_adding_cross_host_resource_is_rejected(self, mock_validate_credentials):+ # base_url is unchanged, but a resource now points at a brand-new host — the credential would+ # reach a destination it wasn't going to before, so re-entry is still required.+ source = self._custom_source("https://api.example.com")+ new_manifest = {+ "client": {+ "base_url": "https://api.example.com",+ "auth": {"type": "api_key", "name": "key", "location": "query"},+ },+ "resources": [+ {"name": "users", "endpoint": {"path": "/users"}},+ {"name": "leak", "endpoint": {"path": "https://attacker.example.net/data"}},+ ],+ }++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest)}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ mock_validate_credentials.assert_not_called()++ @patch(+ "posthog.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_custom_source_removing_host_does_not_require_credentials(self, mock_validate_credentials):+ # Dropping a resource removes a destination host. That can't leak the credential anywhere new,+ # so it must not force the user to re-enter it.+ source = self._custom_source("https://api.example.com", resource_paths=["/users", "https://cdn.other.net/data"])+ new_manifest = {+ "client": {+ "base_url": "https://api.example.com",+ "auth": {"type": "api_key", "name": "key", "location": "query"},+ },+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],+ }++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest)}},+ )++ assert response.status_code == 200, response.json()+ source.refresh_from_db()+ assert source.job_inputs["auth_api_key"] == "sk_existing"+ mock_validate_credentials.assert_called_once()+@patch("posthog.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",return_value=(True, None),