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(brevo): say why the API key failed instead of calling it invalid (#127929)

Tom Owersbffb7a37e4af
diff --git a/products/warehouse_sources/sources/brevo/brevo.py b/products/warehouse_sources/sources/brevo/brevo.py
index 0cc16b7377d5..e4de5c455452 100644
--- a/products/warehouse_sources/sources/brevo/brevo.py
+++ b/products/warehouse_sources/sources/brevo/brevo.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.sources.sdk import (
ResumableSourceManager,
SinglePagePaginator,
SourceResponse,
+ capture_exception,
make_tracked_session,
rest_api_resource,
validate_via_probe,
@@ -17,6 +18,19 @@ from products.warehouse_sources.sources.sdk import (
BREVO_BASE_URL = "https://api.brevo.com/v3"
+BREVO_SMTP_KEY_PREFIX = "xsmtpsib-"
+
+BREVO_INVALID_API_KEY_MESSAGE = (
+ "Brevo rejected your API key. Create a new API key in your Brevo account settings, then reconnect."
+)
+BREVO_SMTP_KEY_MESSAGE = (
+ "You entered a Brevo SMTP key. Create a key on the API keys tab of your Brevo SMTP & API settings, then reconnect."
+)
+BREVO_MISSING_PERMISSIONS_MESSAGE = (
+ "Your Brevo API key can't read your account. Check the key in your Brevo account settings, then reconnect."
+)
+BREVO_UNREACHABLE_MESSAGE = "Couldn't reach Brevo to validate your API key. Try again in a few minutes."
+
@dataclasses.dataclass(frozen=False)
class BrevoResumeConfig:
@@ -37,14 +51,29 @@ def _format_datetime(value: Any) -> str:
return str(value)
-def validate_credentials(api_key: str) -> bool:
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
"""Cheap probe to confirm the API key is genuine."""
- ok, _status = validate_via_probe(
+ ok, status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
f"{BREVO_BASE_URL}/account",
headers={"api-key": api_key, "accept": "application/json"},
+ allow_redirects=False,
)
- return ok
+ if ok:
+ return True, None
+ if status == 401:
+ # Brevo lists SMTP keys next to API keys, and only API keys work against the REST API.
+ if api_key.strip().startswith(BREVO_SMTP_KEY_PREFIX):
+ return False, BREVO_SMTP_KEY_MESSAGE
+ return False, BREVO_INVALID_API_KEY_MESSAGE
+ if status == 403:
+ return False, BREVO_MISSING_PERMISSIONS_MESSAGE
+ # No status means the request never completed. That, a rate limit and a Brevo-side error are
+ # all transient, so none of them should point the user at a key that may be fine.
+ if status is None or status == 429 or status >= 500:
+ return False, BREVO_UNREACHABLE_MESSAGE
+ capture_exception(Exception(f"Unexpected Brevo credential validation response ({status})"))
+ return False, BREVO_INVALID_API_KEY_MESSAGE
def _build_base_params(
diff --git a/products/warehouse_sources/sources/brevo/source.py b/products/warehouse_sources/sources/brevo/source.py
index 8129b6b265cc..cf5509303742 100644
--- a/products/warehouse_sources/sources/brevo/source.py
+++ b/products/warehouse_sources/sources/brevo/source.py
@@ -2,6 +2,8 @@ from typing import Optional, cast
from products.warehouse_sources.sources.brevo._config import BrevoSourceConfig
from products.warehouse_sources.sources.brevo.brevo import (
+ BREVO_INVALID_API_KEY_MESSAGE,
+ BREVO_MISSING_PERMISSIONS_MESSAGE,
BrevoResumeConfig,
brevo_source,
validate_credentials as validate_brevo_credentials,
@@ -26,10 +28,6 @@ from products.warehouse_sources.sources.sdk import (
detect,
)
-BREVO_INVALID_API_KEY_MESSAGE = (
- "Brevo authentication failed. Your API key is invalid or expired - please generate a new key and reconnect."
-)
-
@SourceRegistry.register
class BrevoSource(ResumableSource[BrevoSourceConfig, BrevoResumeConfig]):
@@ -60,7 +58,7 @@ class BrevoSource(ResumableSource[BrevoSourceConfig, BrevoResumeConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
"401 Client Error: Unauthorized for url": BREVO_INVALID_API_KEY_MESSAGE,
- "403 Client Error: Forbidden for url": "Your Brevo API key does not have the required permissions. Please check the key and reconnect.",
+ "403 Client Error: Forbidden for url": BREVO_MISSING_PERMISSIONS_MESSAGE,
}
@property
@@ -105,10 +103,7 @@ You can create an API key in your [Brevo account settings](https://app.brevo.com
def validate_credentials(
self, config: BrevoSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
) -> tuple[bool, str | None]:
- if validate_brevo_credentials(config.api_key):
- return True, None
-
- return False, BREVO_INVALID_API_KEY_MESSAGE
+ return validate_brevo_credentials(config.api_key)
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrevoResumeConfig]:
return ResumableSourceManager[BrevoResumeConfig](inputs, BrevoResumeConfig)
diff --git a/products/warehouse_sources/sources/brevo/tests/test_brevo.py b/products/warehouse_sources/sources/brevo/tests/test_brevo.py
index 4b75802bc8cf..a329d2721d29 100644
--- a/products/warehouse_sources/sources/brevo/tests/test_brevo.py
+++ b/products/warehouse_sources/sources/brevo/tests/test_brevo.py
@@ -143,12 +143,8 @@ class TestSession:
class TestValidateCredentials:
def test_validate_credentials_sends_api_key_header(self) -> None:
with scripted_network([ScriptedResponse(json={})]) as network:
- assert validate_credentials("test-key") is True
+ assert validate_credentials("test-key") == (True, None)
assert len(network.session_options) == 1
assert network.session_options[0]["redact_values"] == ("test-key",)
assert network.requests_log[0].headers["api-key"] == "test-key"
-
- def test_validate_credentials_network_error_returns_false(self) -> None:
- with scripted_network([OSError("network down")]):
- assert validate_credentials("test-key") is False
diff --git a/products/warehouse_sources/sources/brevo/tests/test_brevo_source.py b/products/warehouse_sources/sources/brevo/tests/test_brevo_source.py
index 9a5527c79567..6a9ac271a057 100644
--- a/products/warehouse_sources/sources/brevo/tests/test_brevo_source.py
+++ b/products/warehouse_sources/sources/brevo/tests/test_brevo_source.py
@@ -1,27 +1,38 @@
import pytest
-from unittest.mock import patch
from products.warehouse_sources.sources.brevo._config import BrevoSourceConfig
-from products.warehouse_sources.sources.brevo.source import BREVO_INVALID_API_KEY_MESSAGE, BrevoSource
+from products.warehouse_sources.sources.brevo.brevo import (
+ BREVO_INVALID_API_KEY_MESSAGE,
+ BREVO_MISSING_PERMISSIONS_MESSAGE,
+ BREVO_SMTP_KEY_MESSAGE,
+ BREVO_UNREACHABLE_MESSAGE,
+)
+from products.warehouse_sources.sources.brevo.source import BrevoSource
+from products.warehouse_sources.sources.sdk.testing import ScriptedResponse, scripted_network
-
-def _config() -> BrevoSourceConfig:
- return BrevoSourceConfig(api_key="test-key")
+# The shared session retries a connection error, 429 and 5xx three times before it gives up.
+_RETRIED_ATTEMPTS = 4
class TestBrevoSource:
@pytest.mark.parametrize(
- ("valid", "expected_ok", "expected_msg"),
+ ("api_key", "answers", "expected_ok", "expected_msg"),
[
- (True, True, None),
- (False, False, BREVO_INVALID_API_KEY_MESSAGE),
+ ("xkeysib-test", [ScriptedResponse(json={})], True, None),
+ ("xkeysib-test", [ScriptedResponse(status=401)], False, BREVO_INVALID_API_KEY_MESSAGE),
+ ("xsmtpsib-test", [ScriptedResponse(status=401)], False, BREVO_SMTP_KEY_MESSAGE),
+ ("xkeysib-test", [ScriptedResponse(status=403)], False, BREVO_MISSING_PERMISSIONS_MESSAGE),
+ ("xkeysib-test", [ScriptedResponse(status=404)], False, BREVO_INVALID_API_KEY_MESSAGE),
+ ("xkeysib-test", [ScriptedResponse(status=429)] * _RETRIED_ATTEMPTS, False, BREVO_UNREACHABLE_MESSAGE),
+ ("xkeysib-test", [ScriptedResponse(status=503)] * _RETRIED_ATTEMPTS, False, BREVO_UNREACHABLE_MESSAGE),
+ ("xkeysib-test", [OSError("network down")] * _RETRIED_ATTEMPTS, False, BREVO_UNREACHABLE_MESSAGE),
],
)
- def test_validate_credentials(self, valid: bool, expected_ok: bool, expected_msg: str | None) -> None:
- with patch(
- "products.warehouse_sources.sources.brevo.source.validate_brevo_credentials",
- return_value=valid,
- ):
- ok, msg = BrevoSource().validate_credentials(_config(), team_id=1)
+ def test_validate_credentials(
+ self, api_key: str, answers: list[ScriptedResponse | Exception], expected_ok: bool, expected_msg: str | None
+ ) -> None:
+ with scripted_network(answers) as network:
+ ok, msg = BrevoSource().validate_credentials(BrevoSourceConfig(api_key=api_key), team_id=1)
assert ok is expected_ok
assert msg == expected_msg
+ assert len(network.requests_log) == len(answers)