: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-imports): let an SSH tunnel config load without an auth method (#95619)
Tom Owerse63f8135c601
diff --git a/products/warehouse_sources/backend/models/ssh_tunnel.py b/products/warehouse_sources/backend/models/ssh_tunnel.pyindex 95c4f4bbcdbf..8564f2e28f05 100644--- a/products/warehouse_sources/backend/models/ssh_tunnel.py+++ b/products/warehouse_sources/backend/models/ssh_tunnel.py@@ -68,7 +68,9 @@ def from_private_key(file_obj: IO[str], passphrase: str | None = None) -> PKey:class SSHTunnelAuthConfig(config.Config):"""Configuration for SSH tunnel authentication."""- type: Literal["password", "keypair"] | None = config.value(alias="selection")+ # `SSHTunnelConfig.auth` falls back to an empty auth config, so every field here needs a+ # default. `config.value` ignores `default=None`, so the factory is the way to express it.+ type: Literal["password", "keypair"] | None = config.value(alias="selection", default_factory=lambda: None)password: str | None = Nonepassphrase: str | None = Noneprivate_key: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.pyindex ded119e18ee1..6e628cab9a5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py@@ -244,6 +244,7 @@ def to_config(config_cls: type[ConfigProtocol],d: dict[str, typing.Any],prefixes: tuple[str, ...] | None = None,+ reserved_keys: frozenset[str] = frozenset(),) -> ConfigProtocol:"""Initialize a class from dict.@@ -254,6 +255,9 @@ def to_config(d: The dictionary we are using to initialize the class.prefixes: Used in recursive call, should be left empty by top levelcallers.+ reserved_keys: Bare (unprefixed) key names that belong to a sibling field one level up+ and must not be read by this class's own fields. Used in recursive calls, should be+ left empty by top level callers. See its use below for why it exists.Raises:TypeError: If called with a class not decorated with @config.@@ -268,6 +272,7 @@ def to_config(fields = dataclasses.fields(config_cls)module_path = config_cls.__module__+ sibling_names = frozenset(f.name for f in fields)for field in fields:field_type = _resolve_field_type(field, module_path=module_path)@@ -278,10 +283,15 @@ def to_config(if field_flat_key in d:field_key = field_flat_key- elif field_nested_key in d:+ elif field_nested_key in d and field_nested_key not in reserved_keys:field_key = field_nested_key- else:+ elif field.name not in reserved_keys:field_key = field.name+ else:+ # Every bare-name spelling of this key is reserved for a sibling field one level up+ # (see the call site below), so it must not be read here even though it is present in+ # `d`. `None` never collides with a real dict key, so the lookups below simply miss.+ field_key = Noneif field_meta and field_meta.converter != _noop_convert:convert = field_meta.converter@@ -305,6 +315,8 @@ def to_config(# downstream (e.g. `config.ssh_tunnel.enabled`). Skip so the field# falls back to its default instead.continue+ if field_key is None:+ continuetry:value = d[field_key]except KeyError:@@ -335,20 +347,31 @@ def to_config(breakelse:- # Assuming a flat structure+ # Assuming a flat structure. The nested config is built from the very same+ # mapping as its enclosing config, matched by bare (unprefixed) field name —+ # see `_get_nested_key`. Left unchecked, that lets a nested config's field+ # steal a sibling field's value purely by sharing its name (e.g. an SSH+ # tunnel's own `host` reading the database's `host`). Reserve this config's+ # other field names so the nested config can't read them by bare name; it can+ # still be built from its own prefixed keys or its own defaults. Union with+ # the reserved names inherited from callers above us, so a field several+ # levels down (e.g. an SSH tunnel's `auth.password`) can't reach past its+ # immediate parent and read a grandparent's bare key either (e.g. the+ # database's own `password`, two levels up from `ssh_tunnel.auth`).field_prefixes = _resolve_field_prefixes(config_type, field_type_meta, field_meta, top_level_prefixes)+ child_reserved_keys = reserved_keys | (sibling_names - {field.name})try:- value = to_config(config_type, d, field_prefixes)+ value = to_config(config_type, d, field_prefixes, reserved_keys=child_reserved_keys)except TypeError:# We want to try all possible config typescontinueelse:inputs[field.name] = convert(value)break- else:+ elif field_key is not None:try:value = d[field_key]except KeyError:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.pyindex c764059b80ca..dafe94e480f7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py@@ -880,3 +880,25 @@ def test_validate_dict_with_nested_dict():assert is_valid is Falseassert len(errors) == 1+++def test_to_config_absent_nested_config_keeps_its_default():+ """An absent nested config must not be built from the enclosing config's own keys."""++ @config.config+ class Tunnel(config.Config):+ host: str | None+ port: int | None = config.value(converter=config.str_to_optional_int)+ enabled: bool = config.value(converter=config.str_to_bool, default=False)++ @config.config+ class Source(config.Config):+ host: str+ port: int = config.value(converter=int)+ tunnel: Tunnel | None = None++ cfg = Source.from_dict({"host": "db.example.com", "port": "5432"})++ assert cfg.host == "db.example.com"+ assert cfg.port == 5432+ assert cfg.tunnel is Nonediff --git a/products/warehouse_sources/backend/tests/test_ssh_tunnel.py b/products/warehouse_sources/backend/tests/test_ssh_tunnel.pyindex f857a469b4be..37fa7260e63e 100644--- a/products/warehouse_sources/backend/tests/test_ssh_tunnel.py+++ b/products/warehouse_sources/backend/tests/test_ssh_tunnel.py@@ -3,7 +3,7 @@ import pytestfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import ed25519-from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel+from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel, SSHTunnelConfigdef _keypair_tunnel(private_key: str | None, passphrase: str | None) -> SSHTunnel:@@ -145,3 +145,10 @@ def test_get_tunnel_invalid_port():with pytest.raises(Exception) as e:ssh_tunnel.get_tunnel("host.com", 1337, ssh_host="93.184.216.34")assert "port" in str(e.value)+++def test_config_from_dict_without_an_auth_section():+ ssh_tunnel_config = SSHTunnelConfig.from_dict({"host": "host.com", "port": "22", "enabled": "false"})++ assert ssh_tunnel_config.enabled is False+ assert ssh_tunnel_config.auth.type is None