Skip to content

: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.

fix(warehouse-sources): honor a flat auth method in source payloads (#98042)

posthog[bot]25b6ee256168
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
index 6e628cab9a5f..e120e16c9b85 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
@@ -167,6 +167,22 @@ class MetaConfig:
converter: typing.Callable[[typing.Any], typing.Any] = _noop_convert
+def _selection_options(config_type: type) -> tuple[str, ...] | None:
+ """The values a select container's `selection` field accepts, or None if it has no such field.
+
+ A select field (e.g. Stripe `auth_method`) is a nested config whose branch is named by
+ `selection`. Callers of the source API may send that branch as a bare string under the
+ container name instead of a mapping, so both spellings must resolve to the same branch.
+ """
+ for field in dataclasses.fields(config_type):
+ if field.name != "selection":
+ continue
+ field_type = _resolve_field_type(field, module_path=config_type.__module__)
+ options = tuple(arg for arg in typing.get_args(field_type) if isinstance(arg, str))
+ return options or None
+ return None
+
+
def validate_config(
config_cls: type, d: dict[str, typing.Any], prefixes: tuple[str, ...] | None = None
) -> tuple[bool, list[str]]:
@@ -212,6 +228,18 @@ def validate_config(
if not is_valid:
errors.extend(nested_errors)
else:
+ # A select container sent as a bare string names the branch to use, so an
+ # unknown value would otherwise pass validation and land on the default branch.
+ selection_options = _selection_options(config_type)
+ nested_value = d.get(field_nested_key)
+ if (
+ selection_options is not None
+ and isinstance(nested_value, str)
+ and nested_value not in selection_options
+ ):
+ errors.append(f"Field '{field.name}' must be one of: {', '.join(selection_options)}")
+ continue
+
# Trying a flat structure
field_type_meta = _try_get_meta(config_type)
if field_type_meta:
@@ -363,8 +391,17 @@ def to_config(
)
child_reserved_keys = reserved_keys | (sibling_names - {field.name})
+ # A select container sent as a bare string (`auth_method: "oauth"`) names the
+ # branch the caller chose, so read it as `selection`. Without this the flat
+ # spelling silently falls back to the default branch.
+ flat_source = d
+ selection_options = _selection_options(config_type)
+ nested_value = d.get(field_nested_key)
+ if selection_options is not None and nested_value in selection_options:
+ flat_source = {**d, "selection": nested_value}
+
try:
- value = to_config(config_type, d, field_prefixes, reserved_keys=child_reserved_keys)
+ value = to_config(config_type, flat_source, field_prefixes, reserved_keys=child_reserved_keys)
except TypeError:
# We want to try all possible config types
continue
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.py
index dafe94e480f7..e636e13ebe54 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
@@ -487,9 +487,9 @@ def test_to_config_union_nested_configs_with_alias():
"config_dict,expected_selection,expected_integration_id,expected_secret_key,expected_account_id",
[
# Flat select payload: the option value as a scalar with the option's fields as
- # siblings. The scalar isn't mapped to `selection`, so it keeps its default and
- # the siblings are parsed flat.
- ({"auth_method": "oauth", "integration_id": 123, "account_id": "acct_x"}, "api_key", 123, None, "acct_x"),
+ # siblings. The scalar names the branch, so it must pick the same one the nested
+ # form picks.
+ ({"auth_method": "oauth", "integration_id": 123, "account_id": "acct_x"}, "oauth", 123, None, "acct_x"),
# Flat payload whose scalar sibling is a string field — it must survive the flat
# fallback and land on the nested config (e.g. Stripe's `secret_key`).
(
@@ -512,19 +512,18 @@ def test_to_config_union_nested_configs_with_alias():
def test_to_config_scalar_under_nested_config_key(
config_dict, expected_selection, expected_integration_id, expected_secret_key, expected_account_id
):
- """A scalar under a nested-config key must not crash `to_config`.
+ """A scalar under a nested-config key names the branch and must not crash `to_config`.
A flat select payload (e.g. `auth_method: "oauth"` with the option's fields as
siblings, instead of the nested `auth_method: {"selection": "oauth", ...}`) puts a
- scalar where a nested config dict is expected. `validate_config` already treats this
- as a flat structure (it guards with `isinstance(..., dict)`), so `to_config` must do
- the same and fall through to flat parsing instead of recursing into the scalar and
- raising an unhandled `TypeError`.
+ scalar where a nested config dict is expected. `to_config` must read it as the
+ `selection` value instead of recursing into the scalar and raising an unhandled
+ `TypeError`, so the source API honors the branch the caller asked for.
"""
@config.config
class AuthMethod:
- selection: str = "api_key"
+ selection: typing.Literal["api_key", "oauth"] = "api_key"
integration_id: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)
secret_key: str | None = None
@@ -547,6 +546,22 @@ def test_to_config_scalar_under_nested_config_key(
assert cfg.account_id == expected_account_id
+def test_validate_dict_rejects_unknown_scalar_under_nested_config_key():
+ @config.config
+ class AuthMethod:
+ selection: typing.Literal["api_key", "oauth"] = "api_key"
+ secret_key: str | None = None
+
+ @config.config
+ class SourceConfig(config.Config):
+ auth_method: AuthMethod
+
+ is_valid, errors = SourceConfig.validate_dict({"auth_method": "oauth_v2"})
+
+ assert is_valid is False
+ assert errors == ["Field 'auth_method' must be one of: api_key, oauth"]
+
+
@pytest.mark.parametrize("bad_input", ["not a mapping", '"scalar"', "[1, 2, 3]", b"bytes", 5, ["a", "b"], None])
def test_from_dict_with_non_mapping_raises_clear_error(bad_input):
"""A non-mapping input must raise an actionable error, not the opaque builtin `TypeError`.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
index 83f7acd978b8..a3c61f94d4f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
@@ -337,6 +337,16 @@ class TestStripeSource:
assert ok is False
assert message == expected_message
+ def test_parse_config_reads_flat_oauth_auth_method(self):
+ # The source API accepts a flat payload, so an OAuth connection arrives as
+ # `auth_method: "oauth"` with the integration id as a sibling. Parsing must pick the
+ # OAuth branch; the api_key default would report a missing API key for an account the
+ # user connected with OAuth.
+ config = self.source.parse_config({"auth_method": "oauth", "stripe_integration_id": 123})
+
+ assert config.auth_method.selection == "oauth"
+ assert config.auth_method.stripe_integration_id == 123
+
def test_validate_credentials_does_not_echo_rejected_key(self):
# Stripe's 401 body echoes the submitted key verbatim; here the user pasted a password into
# the key field. The validation message must not leak it into the toast or analytics event.