: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
refactor(warehouse-sources): share the connect-time host check (#101362)
Tom Piccirello06dcf547fa80
diff --git a/posthog/temporal/common/client.py b/posthog/temporal/common/client.pyindex f3be263786ff..6d24cc34197b 100644--- a/posthog/temporal/common/client.py+++ b/posthog/temporal/common/client.py@@ -22,6 +22,7 @@ async def connect(client_key: str | None = None,runtime: Runtime | None = None,server_root_ca_cert: str | None = None,+ tls_domain: str | None = None,settings: Any | None = django_settings,use_pydantic_converter: bool = False,add_otel_tracing_interceptor: bool = True,@@ -29,9 +30,13 @@ async def connect() -> Client:tls: TLSConfig | bool = Falseif client_cert and client_key:+ # `tls_domain` names the server the certificate is checked against, for a caller that+ # dials an address rather than the name the certificate was issued for. Unset, the+ # certificate is checked against the host that was dialled.tls = TLSConfig(client_cert=bytes(client_cert, "utf-8"),client_private_key=bytes(client_key, "utf-8"),+ domain=tls_domain,)if server_root_ca_cert:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md b/products/warehouse_sources/backend/temporal/data_imports/sources/README.mdindex 68d17c735ea9..01857f6bcb46 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/README.md@@ -210,7 +210,7 @@ Provides a simple `get_oauth_integration()` method to pull the `Integration` obj#### `ValidateDatabaseHostMixin`-Provides `is_database_host_valid()` to validate that the source isn't trying to access local IP addresses in our internal VPC on AWS (unless if the user is using a SSH tunnel). This runs when a source is created or updated; the connection-time check lives in `with_ssh_tunnel()` above.+Provides `is_database_host_valid()` to validate that the source isn't trying to access local IP addresses in our internal VPC on AWS (unless if the user is using a SSH tunnel). This runs when a source is created or updated; the connection-time check lives in `with_ssh_tunnel()` above. A source that dials the host itself, without the tunnel mixin, calls `pinned_connect_host()` on its connect path instead. A raw socket has no egress proxy in front of it, so a stored host is otherwise never re-checked. `TemporalIOSource` is the example.## Non-Retryable Errorsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex 9cd620d8f921..2827d8ad8238 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py@@ -13,6 +13,7 @@ from django.db import OperationalError, close_old_connectionsimport structlogfrom posthog.cloud_utils import is_cloud+from posthog.dataclasses import frozenfrom posthog.models.integration import Integrationfrom posthog.psycopg_helpers import (is_resolvable_hostname,@@ -76,11 +77,12 @@ class TemporaryHostResolutionError(NonReportableError):class HostNotAllowedError(NonReportableError):"""A direct database or SSH tunnel host resolved to an address PostHog won't connect to.- Raised at connect time by `_check_direct_host` and `_pinned_ssh_host`. A host can pass the- validation-layer check and still land here, because each check resolves the host again and a- short-TTL record can answer public for one lookup and private for the next. It is always the- customer's own DNS or network config, never a PostHog defect, and retrying re-hits the same- rejection, so it must fail the work without minting an error tracking issue.+ Raised at connect time by `_check_direct_host`, `_pinned_ssh_host`, `pinned_connect_host` and+ `pinned_host_kwargs`. A host can pass the validation-layer check and still land here, because+ each check resolves the host again and a short-TTL record can answer public for one lookup and+ private for the next. It is always the customer's own DNS or network config, never a PostHog+ defect, and retrying re-hits the same rejection, so it must fail the work without minting an+ error tracking issue.Two connect paths reach it, and each suppresses reporting its own way:- Import pipeline (Temporal): `NonReportableError` makes the activity interceptor fail the@@ -271,6 +273,36 @@ def _normalize_host(host: str) -> str:return host.lower().strip().rstrip(".")+def unbracket_host(host: str) -> str:+ """Return an IPv6 literal without the brackets it carries inside a `host:port` string.++ Both `_is_safe_public_ip` and the resolver want the bare address. Anything else, a hostname or+ an IPv4 literal, comes back unchanged.+ """+ inner = host.strip()+ if not (inner.startswith("[") and inner.endswith("]")):+ return host+ try:+ ipaddress.ip_address(inner[1:-1])+ except ValueError:+ return host+ return inner[1:-1]+++def bracket_host(host: str) -> str:+ """Return an IPv6 address in the form a `host:port` string needs.++ The inverse of `unbracket_host`: a client that joins host and port with a colon cannot tell an+ IPv6 address from its own port. A hostname or an IPv4 address comes back unchanged.+ """+ stripped = host.strip()+ try:+ parsed = ipaddress.ip_address(stripped)+ except ValueError:+ return host+ return f"[{stripped}]" if parsed.version == 6 else host++_HOST_LABEL = re.compile(r"^(?!-)[a-z0-9_-]{1,63}(?<!-)\Z")@@ -463,6 +495,14 @@ def _require_loopback(host: str) -> str:return host+def _checked_connect_host(host: str, team_id: int | None, refusal_prefix: str) -> str:+ """Return the address `resolve_safe_host` approves for `host`, or raise `HostNotAllowedError`."""+ resolution = resolve_safe_host(host, team_id)+ if resolution.connect_host is None:+ raise HostNotAllowedError(f"{refusal_prefix}: {resolution.error or _INTERNAL_IP_ERROR}")+ return resolution.connect_host++def _pinned_ssh_host(ssh_config, team_id: int | None) -> str:"""Resolve the SSH host and return the address to open the tunnel to.@@ -472,10 +512,40 @@ def _pinned_ssh_host(ssh_config, team_id: int | None) -> str:public address at setup is never re-checked on any later scheduled run. The SSH hop is araw socket that no egress proxy sees, which makes this check the only thing in its path."""- resolution = resolve_safe_host(ssh_config.host, team_id)- if resolution.connect_host is None:- raise HostNotAllowedError(f"{SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR}: {resolution.error}")- return resolution.connect_host+ return _checked_connect_host(ssh_config.host, team_id, SSH_TUNNEL_HOST_NOT_ALLOWED_ERROR)+++@frozen+class DialTarget:+ """Where `pinned_connect_host` sends a connection.++ `host` is the address to dial, in brackets when it is IPv6, so it joins a port with a colon.+ `tls_server_name` is the configured hostname, which the server certificate must match once+ the dial goes to an address. It is None when the configured host is itself an address.+ """++ host: str+ tls_server_name: str | None+++def pinned_connect_host(host: str, team_id: int | None) -> DialTarget:+ """Resolve `host` and return the address to dial and the name to check TLS against.++ For a source whose client dials the host itself, on a raw socket that no egress proxy sees.+ A client that takes the hostname resolves it a second time, and a record with a short TTL can+ answer public for the check and private for that second lookup. Dialling the address the check+ approved closes that race, so the hostname goes to TLS separately.++ `host` can be an IPv6 address in brackets, the form a `host:port` string needs. The brackets+ come off here rather than in `resolve_safe_host`. The database drivers dial the host as written+ and cannot dial the bracketed form, so their check must keep refusing it.+ """+ lookup_host = unbracket_host(host)+ connect_host = _checked_connect_host(lookup_host, team_id, DATABASE_HOST_NOT_ALLOWED_ERROR)+ return DialTarget(+ host=bracket_host(connect_host),+ tls_server_name=lookup_host if is_resolvable_hostname(lookup_host) else None,+ )def _check_direct_host(config, team_id: int | None) -> None:@@ -506,9 +576,7 @@ def _check_direct_host(config, team_id: int | None) -> None:activity until Temporal's `start_to_close_timeout` rather than failing fast and retryably.Bounding this one is the follow-up."""- resolution = resolve_safe_host(config.host, team_id)- if resolution.connect_host is None:- raise HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: {resolution.error or _INTERNAL_IP_ERROR}")+ _checked_connect_host(config.host, team_id, DATABASE_HOST_NOT_ALLOWED_ERROR)@contextmanagerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.pyindex c0cc3913a243..f2f819035b8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py@@ -25,11 +25,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixTemporaryHostResolutionError,ValidateDatabaseHostMixin,_is_host_safe,+ bracket_host,check_resolved_addresses,make_ssh_tunnel_factory,open_ssh_tunnel,resolve_safe_host,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import resolver_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"@@ -70,6 +72,7 @@ class TestIsHostSafe(SimpleTestCase):("public_ip", "8.8.8.8"),("public_ip_2", "1.1.1.1"),("public_ip_3", "52.0.0.1"),+ ("ipv6_public", "2606:4700:4700::1111"),])@override_settings(CLOUD_DEPLOYMENT="US")@@ -276,6 +279,19 @@ class TestIsHostSafe(SimpleTestCase):mock_logger.warning.assert_not_called()+class TestBracketHost(SimpleTestCase):+ @parameterized.expand(+ [+ ("ipv6", "2606:4700:4700::1111", "[2606:4700:4700::1111]"),+ ("ipv6_already_bracketed", "[2606:4700:4700::1111]", "[2606:4700:4700::1111]"),+ ("ipv4", "93.184.216.34", "93.184.216.34"),+ ("hostname", "db.example.com", "db.example.com"),+ ]+ )+ def test_brackets_only_an_ipv6_address(self, _name: str, host: str, expected: str):+ assert bracket_host(host) == expected++class TestValidateDatabaseHostMixin(SimpleTestCase):@override_settings(CLOUD_DEPLOYMENT="US")def test_blocks_private_ip(self):@@ -627,6 +643,18 @@ class TestDirectHostIsCheckedAtConnect(SimpleTestCase):with self._connection_cm(entrypoint, config, 999):pass+ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_bracketed_address_is_refused_because_the_driver_dials_the_host_as_written(self, entrypoint: str):+ config = FakeConfig(host="[2606:4700:4700::1111]", ssh_tunnel=None)+ with (+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=resolver("2606:4700:4700::1111")),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ with pytest.raises(HostNotAllowedError, match="Database host not allowed"):+ with self._connection_cm(entrypoint, config, 999):+ pass+@parameterized.expand([("open_ssh_tunnel",), ("factory",)])@override_settings(CLOUD_DEPLOYMENT="US")def test_a_resolver_blip_is_a_retryable_error_not_a_rejection(self, entrypoint: str) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.pyindex 3ee986633b09..36652b243df5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/resolver.py@@ -1,6 +1,26 @@+import reimport socket+import ipaddress+from collections.abc import Callable++_HOSTNAME = re.compile(r"[A-Za-z0-9.-]+")# nosemgrep: semgrep.rules.devex.tuple-return-prefer-dataclass -- mirrors socket.getaddrinfo's positional resultdef addrinfo(port: int, *addresses: str) -> list[tuple[int, int, int, str, tuple[str, int]]]:return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, port)) for address in addresses]+++# A stand-in for `socket.getaddrinfo` that answers `addresses` for any IP address or hostname. It+# fails any other string, such as a bracketed IPv6 address, the way the system resolver does, so a+# test can tell whether the host reached the lookup in a form the resolver accepts.+def resolver(*addresses: str) -> Callable[..., list[tuple[int, int, int, str, tuple[str, int]]]]:+ def getaddrinfo(host: str, *_args: object, **_kwargs: object) -> list[tuple[int, int, int, str, tuple[str, int]]]:+ try:+ ipaddress.ip_address(host)+ except ValueError:+ if not _HOSTNAME.fullmatch(host):+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")+ return addrinfo(0, *addresses)++ return getaddrinfodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/temporalio.pyindex cd01a9432cff..4904d6c26355 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/temporalio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/temporalio.py@@ -7,10 +7,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass TemporalIOSourceConfig(config.Config):host: str- port: strnamespace: strserver_client_root_ca: strclient_certificate: strclient_private_key: str+ port: int = config.value(converter=int)encryption_key: str | None = Nonefallback_decryption_keys: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/source.pyindex 5de1863498f0..78c06826c41c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/source.py@@ -10,6 +10,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ ValidateDatabaseHostMixin,+ unbracket_host,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (@@ -31,7 +35,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TemporalIOSource(ResumableSource[TemporalIOSourceConfig, TemporalIOResumeConfig]):+class TemporalIOSource(ValidateDatabaseHostMixin, ResumableSource[TemporalIOSourceConfig, TemporalIOResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docsapi_docs_url = "https://docs.temporal.io"@@ -91,6 +95,16 @@ class TemporalIOSource(ResumableSource[TemporalIOSourceConfig, TemporalIOResumeCdef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TemporalIOResumeConfig]:return ResumableSourceManager[TemporalIOResumeConfig](inputs, TemporalIOResumeConfig)+ def validate_credentials(+ self,+ config: TemporalIOSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ # An IPv6 host is entered in brackets because `connect()` joins host and port with a colon.+ return self.is_database_host_valid(unbracket_host(config.host), team_id)+def source_for_pipeline(self,config: TemporalIOSourceConfig,@@ -105,6 +119,7 @@ class TemporalIOSource(ResumableSource[TemporalIOSourceConfig, TemporalIOResumeCelse None,resumable_source_manager=resumable_source_manager,logger=inputs.logger,+ team_id=inputs.team_id,should_use_incremental_field=inputs.should_use_incremental_field,)@@ -131,7 +146,7 @@ class TemporalIOSource(ResumableSource[TemporalIOSourceConfig, TemporalIOResumeCSourceFieldInputConfig(name="port",label="Port",- type=SourceFieldInputConfigType.TEXT,+ type=SourceFieldInputConfigType.NUMBER,required=True,placeholder="",secret=False,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.pyindex 48ddbe5fa183..132a4183d545 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py@@ -15,6 +15,7 @@ from temporalio.service import RPCError, RPCStatusCodefrom posthog.dataclasses import frozenfrom posthog.temporal.common.client import connect+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import pinned_connect_hostfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.temporalio import (@@ -263,15 +264,20 @@ class FakeSettings:DEBUG: bool = False-async def _get_temporal_client(config: TemporalIOSourceConfig) -> Client:+async def _get_temporal_client(config: TemporalIOSourceConfig, team_id: int | None) -> Client:+ # The Temporal core dials over gRPC from Rust and reads no proxy environment, so the egress+ # proxy does not see this connection. The lookup blocks, so it runs off the event loop.+ target = await asyncio.to_thread(pinned_connect_host, config.host, team_id)+if config.fallback_decryption_keys:fallback_keys = [k.strip() for k in config.fallback_decryption_keys.split(",") if k.strip()]else:fallback_keys = []return await connect(- host=config.host,+ host=target.host,port=config.port,+ tls_domain=target.tls_server_name,namespace=config.namespace,client_cert=config.client_certificate,client_key=config.client_private_key,@@ -298,6 +304,7 @@ async def _get_workflows(should_use_incremental_field: bool,resumable_source_manager: ResumableSourceManager[TemporalIOResumeConfig],logger: FilteringBoundLogger,+ team_id: int,):query: str | None = Noneif should_use_incremental_field and db_incremental_field_last_value:@@ -314,7 +321,7 @@ async def _get_workflows(next_page_token = _decode_page_token(resume_config.next_page_token)logger.debug("TemporalIO: resuming from next_page_token")- client = await _get_temporal_client(config)+ client = await _get_temporal_client(config, team_id)workflows = client.list_workflows(query=query, next_page_token=next_page_token, page_size=100)page_count = 0@@ -349,6 +356,7 @@ async def _get_workflow_histories(should_use_incremental_field: bool,resumable_source_manager: ResumableSourceManager[TemporalIOResumeConfig],logger: FilteringBoundLogger,+ team_id: int,):query: str | None = Noneif should_use_incremental_field and db_incremental_field_last_value:@@ -365,7 +373,7 @@ async def _get_workflow_histories(next_page_token = _decode_page_token(resume_config.next_page_token)logger.debug("TemporalIO: resuming workflow histories from next_page_token")- client = await _get_temporal_client(config)+ client = await _get_temporal_client(config, team_id)workflows = client.list_workflows(query=query, next_page_token=next_page_token, page_size=100)page_count = 0@@ -421,13 +429,19 @@ def temporalio_source(db_incremental_field_last_value: Optional[Any],resumable_source_manager: ResumableSourceManager[TemporalIOResumeConfig],logger: FilteringBoundLogger,+ team_id: int,should_use_incremental_field: bool = False,) -> SourceResponse:if resource == TemporalIOResource.Workflows:async def get_workflows_iterator():return _get_workflows(- config, db_incremental_field_last_value, should_use_incremental_field, resumable_source_manager, logger+ config,+ db_incremental_field_last_value,+ should_use_incremental_field,+ resumable_source_manager,+ logger,+ team_id,)workflows = _async_iter_to_sync(asyncio.run(get_workflows_iterator()))@@ -447,7 +461,12 @@ def temporalio_source(async def get_histories_iterator():return _get_workflow_histories(- config, db_incremental_field_last_value, should_use_incremental_field, resumable_source_manager, logger+ config,+ db_incremental_field_last_value,+ should_use_incremental_field,+ resumable_source_manager,+ logger,+ team_id,)workflows = _async_iter_to_sync(asyncio.run(get_histories_iterator()))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.pyindex bfa521daa952..245415e406da 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/test_temporalio.py@@ -1,11 +1,15 @@import pytestfrom unittest.mock import AsyncMock, MagicMock, call, patch+from django.test import override_settings+from temporalio.client import Clientfrom temporalio.service import RPCError, RPCStatusCodefrom posthog.temporal.common.codec import EncryptionCodec+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import addrinfo, resolverfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.temporalio import (TemporalIOSourceConfig,)@@ -21,11 +25,29 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.temporalio_with_transient_rpc_retry,)+_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"+def _rpc_error(message: str, status: RPCStatusCode) -> RPCError:return RPCError(message, status, b"")+def _payload(**overrides: str) -> dict[str, str]:+ return {+ "host": "temporal.example.com",+ "port": "7233",+ "namespace": "namespace",+ "server_client_root_ca": "ca",+ "client_certificate": "cert",+ "client_private_key": "key",+ **overrides,+ }+++def _config(**overrides: str) -> TemporalIOSourceConfig:+ return TemporalIOSourceConfig.from_dict(_payload(**overrides))++class TestTemporalIOClient:def test_fake_settings_satisfies_encryption_codec_contract(self):# FakeSettings must expose every attribute EncryptionCodec.from_settings reads@@ -36,24 +58,79 @@ class TestTemporalIOClient:assert isinstance(codec, EncryptionCodec)async def test_get_temporal_client_builds_encryption_codec(self):- config = TemporalIOSourceConfig.from_dict(- {- "host": "host",- "port": "7233",- "namespace": "namespace",- "encryption_key": "k" * 32,- "server_client_root_ca": "ca",- "client_certificate": "cert",- "client_private_key": "key",- }- )+ config = _config(encryption_key="k" * 32)with patch.object(Client, "connect", new=AsyncMock(return_value=MagicMock())) as mock_connect:- await _get_temporal_client(config)+ await _get_temporal_client(config, team_id=999)data_converter = mock_connect.call_args.kwargs["data_converter"]assert isinstance(data_converter.payload_codec, EncryptionCodec)+ @pytest.mark.parametrize("resolved_ip", ["169.254.169.254", "10.0.0.5"])+ async def test_a_host_resolving_to_an_internal_ip_is_refused_before_dialling(self, resolved_ip):+ with (+ override_settings(CLOUD_DEPLOYMENT="US"),+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=addrinfo(0, resolved_ip)),+ patch(f"{_MIXINS_MODULE}.logger"),+ patch.object(Client, "connect", new=AsyncMock(return_value=MagicMock())) as mock_connect,+ ):+ with pytest.raises(HostNotAllowedError):+ await _get_temporal_client(_config(), team_id=999)++ mock_connect.assert_not_called()++ @pytest.mark.parametrize(+ "host,resolved,expected_target,expected_tls_domain",+ [+ ("temporal.example.com", "93.184.216.34", "93.184.216.34:7233", "temporal.example.com"),+ ("93.184.216.34", "93.184.216.34", "93.184.216.34:7233", None),+ ("2606:4700:4700::1111", "2606:4700:4700::1111", "[2606:4700:4700::1111]:7233", None),+ ("[2606:4700:4700::1111]", "2606:4700:4700::1111", "[2606:4700:4700::1111]:7233", None),+ ("2606:4700:4700:0::1111", "2606:4700:4700::1111", "[2606:4700:4700::1111]:7233", None),+ ],+ )+ async def test_the_checked_address_is_dialled_and_only_a_name_carries_tls(+ self, host, resolved, expected_target, expected_tls_domain+ ):+ # An address has no name of its own for the certificate, however it is written.+ with (+ override_settings(CLOUD_DEPLOYMENT="US"),+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=resolver(resolved)),+ patch(f"{_MIXINS_MODULE}.logger"),+ patch.object(Client, "connect", new=AsyncMock(return_value=MagicMock())) as mock_connect,+ ):+ await _get_temporal_client(_config(host=host), team_id=999)++ assert mock_connect.call_args.args[0] == expected_target+ assert mock_connect.call_args.kwargs["tls"].domain == expected_tls_domain++ @pytest.mark.parametrize("port", ["[email protected]:80", "not-a-port"])+ def test_a_port_that_is_not_a_number_is_rejected(self, port):+ # `connect()` builds the dial target from host and port, so a port that carries anything+ # but a number moves the target past the host check.+ is_valid, errors = TemporalIOSource().validate_config(_payload(port=port))++ assert not is_valid+ assert errors++ @pytest.mark.parametrize(+ "host,resolved,expected_valid",+ [+ ("temporal.example.com", "10.0.0.5", False),+ ("[2606:4700:4700::1111]", "2606:4700:4700::1111", True),+ ],+ )+ def test_creating_a_source_checks_the_host(self, host, resolved, expected_valid):+ with (+ override_settings(CLOUD_DEPLOYMENT="US"),+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=resolver(resolved)),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ is_valid, error = TemporalIOSource().validate_credentials(_config(host=host), team_id=999)++ assert is_valid is expected_valid+ assert (error is None) is expected_valid+class TestTemporalIONonRetryableErrors:def setup_method(self):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.pyindex ffad92a7a248..40c026b57e0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py@@ -457,7 +457,7 @@ def test_temporal_config():})assert config.host == "host"- assert config.port == "22"+ assert config.port == 22assert config.namespace == "namespace"assert config.encryption_key == "encryption_key"assert config.server_client_root_ca == "server_client_root_ca"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.pyindex 8578db70f1a5..2d51b2096c76 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py@@ -2,8 +2,11 @@ import reimport pytest+from django.test import override_settings+import products.warehouse_sources.backend.temporal.data_imports.sources._load_all # noqa: F401from products.warehouse_sources.backend.facade.source_config import SourceFieldInputConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryALL_SOURCES = SourceRegistry.get_all_sources()@@ -51,6 +54,42 @@ PUBLIC_CREDENTIAL_HALVES = {"Imagga.api_key",}+# Sources that take a host but do not inherit ValidateDatabaseHostMixin. Each one reaches its host+# only over HTTP, where the egress proxy refuses an internal address on every request, so the mixin+# is not required. Most still check the host themselves, with `_is_host_safe` or a vendor domain+# allowlist. A source that opens a raw socket, such as a database wire protocol or gRPC, has no+# proxy in its path, so it must inherit the mixin and check the host where it connects.+HTTP_SOURCES_WITHOUT_THE_HOST_MIXIN = {+ "Appdynamics",+ "Argocd",+ "Bigeye",+ "Chatwoot",+ "Formbricks",+ "Gerrit",+ "Grafana",+ "Hatchet",+ "LangSmith",+ "Langfuse",+ "Metabase",+ "OctopusDeploy",+ "Omni",+ "SigNoz",+ "Sourcegraph",+ "Teamcity",+ "WeightsAndBiases",+ "Windmill",+ "Wrike",+}++HOST_FIELD_SOURCES = sorted(+ (+ source_type+ for source_type, source in ALL_SOURCES.items()+ if any(getattr(field, "name", None) == "host" for field in source.get_source_config.fields)+ ),+ key=str,+)+def _schema_names(source) -> set[str]:return {schema.name for schema in source.get_schemas(source._placeholder_config(), team_id=0)}@@ -134,3 +173,25 @@ def test_credential_fields_are_marked_secret(source_type):f"stays readable after the source is connected. Set secret=True, or record it in "f"PUBLIC_CREDENTIAL_HALVES if it is the public half of a keypair.")++[email protected]("source_type", HOST_FIELD_SOURCES, ids=str)+def test_sources_with_a_host_field_refuse_an_internal_host(source_type):+ source = ALL_SOURCES[source_type]+ listed = str(source_type) in HTTP_SOURCES_WITHOUT_THE_HOST_MIXIN++ if not isinstance(source, ValidateDatabaseHostMixin):+ assert listed, (+ f"{source_type} takes a host but does not inherit ValidateDatabaseHostMixin. Inherit it "+ f"and check the host where the source connects. If the source reaches its host only over "+ f"HTTP, where the egress proxy covers it, record it in HTTP_SOURCES_WITHOUT_THE_HOST_MIXIN."+ )+ return++ assert not listed, (+ f"{source_type} now inherits ValidateDatabaseHostMixin. Remove it from HTTP_SOURCES_WITHOUT_THE_HOST_MIXIN."+ )+ with override_settings(CLOUD_DEPLOYMENT="US"):+ is_valid, _ = source.is_database_host_valid("169.254.169.254", team_id=999)++ assert not is_valid, f"{source_type} accepts a link-local host."