: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(asaas): explain why asaas rejects an api key during setup (#130731)
Tom Owers44aff52d598f
diff --git a/products/warehouse_sources/sources/asaas/asaas.py b/products/warehouse_sources/sources/asaas/asaas.pyindex 0ae6f39ac991..b91ca444d53a 100644--- a/products/warehouse_sources/sources/asaas/asaas.py+++ b/products/warehouse_sources/sources/asaas/asaas.py@@ -1,6 +1,8 @@from datetime import date, datetimefrom typing import Any, Optional+import requests+from products.warehouse_sources.sources.asaas.settings import (ENDPOINT_PARAMS,ENDPOINT_PATHS,@@ -16,6 +18,7 @@ from products.warehouse_sources.sources.sdk import (OffsetPaginator,RESTAPIConfig,ResumableSourceManager,+ capture_exception,frozen,make_tracked_session,rename_parent_fields,@@ -27,6 +30,34 @@ SANDBOX_BASE_URL = "https://api-sandbox.asaas.com"PRODUCTION_BASE_URL = "https://api.asaas.com"API_PATH = "/v3"+PRODUCTION_KEY_PREFIX = "$aact_prod_"+SANDBOX_KEY_PREFIX = "$aact_hmlg_"++INVALID_KEY_ERROR = (+ "Your Asaas API key is invalid, expired or disabled. Create a new key in Asaas under Integrações > API, "+ "then reconnect."+)+KEY_FORMAT_ERROR = (+ "Your Asaas API key isn't in the right format. Copy the full key, including the leading $aact_ and "+ "with no extra spaces, then reconnect."+)+KEY_IN_PRODUCTION_ERROR = (+ "Your Asaas API key is a production key, but you chose Sandbox. Change the environment to Production, "+ "then reconnect."+)+KEY_IN_SANDBOX_ERROR = (+ "Your Asaas API key is a sandbox key, but you chose Production. Change the environment to Sandbox, then reconnect."+)+WRONG_ENVIRONMENT_ERROR = (+ "Your Asaas API key belongs to the other environment. Change the environment to the one you created "+ "the key in, then reconnect."+)+FORBIDDEN_ERROR = (+ "Asaas refused your API key. Check that the key can read your account's data and that any IP allow list "+ "includes PostHog's IP addresses."+)+UNAVAILABLE_ERROR = "PostHog couldn't reach Asaas to check your API key. Wait a few minutes, then try again."+# Asaas caps list endpoints at 100 rows/page (offset/limit + hasMore/totalCount envelope).PAGE_SIZE = 100@@ -172,11 +203,48 @@ def asaas_source()-def validate_credentials(api_key: str, environment: str) -> bool:- # allow_redirects=False: a redirect would forward the access_token header off- # the validated Asaas host.- res = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(- f"{base_url(environment)}{API_PATH}/customers?limit=1",- headers={"access_token": api_key},- )- return res.status_code == 200+def key_environment(api_key: str) -> str | None:+ """The environment an Asaas API key belongs to, from its prefix. Older keys carry no prefix."""+ if api_key.startswith(PRODUCTION_KEY_PREFIX):+ return "production"+ if api_key.startswith(SANDBOX_KEY_PREFIX):+ return "sandbox"+ return None+++def _error_code(response: requests.Response) -> str | None:+ try:+ errors = response.json().get("errors")+ return errors[0].get("code") if errors else None+ except (ValueError, AttributeError, IndexError, TypeError):+ return None+++def validate_credentials(api_key: str, environment: str) -> tuple[bool, str | None]:+ key_env = key_environment(api_key)+ if key_env is not None and key_env != environment:+ return False, KEY_IN_PRODUCTION_ERROR if key_env == "production" else KEY_IN_SANDBOX_ERROR++ try:+ # allow_redirects=False: a redirect would forward the access_token header off+ # the validated Asaas host.+ res = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(+ f"{base_url(environment)}{API_PATH}/customers?limit=1",+ headers={"access_token": api_key},+ )+ except requests.RequestException as e:+ capture_exception(e)+ return False, UNAVAILABLE_ERROR++ if res.status_code == 200:+ return True, None+ if res.status_code == 401:+ code = _error_code(res)+ if code == "invalid_environment":+ return False, WRONG_ENVIRONMENT_ERROR+ if code == "invalid_access_token_format":+ return False, KEY_FORMAT_ERROR+ return False, INVALID_KEY_ERROR+ if res.status_code == 403:+ return False, FORBIDDEN_ERROR+ return False, UNAVAILABLE_ERRORdiff --git a/products/warehouse_sources/sources/asaas/source.py b/products/warehouse_sources/sources/asaas/source.pyindex f75a7e2ba327..77584cce2a4a 100644--- a/products/warehouse_sources/sources/asaas/source.py+++ b/products/warehouse_sources/sources/asaas/source.py@@ -2,6 +2,7 @@ from typing import Optional, castfrom products.warehouse_sources.sources.asaas._config import AsaasSourceConfigfrom products.warehouse_sources.sources.asaas.asaas import (+ INVALID_KEY_ERROR,AsaasResumeConfig,asaas_source,validate_credentials as validate_asaas_credentials,@@ -50,7 +51,7 @@ class AsaasSource(ResumableSource[AsaasSourceConfig, AsaasResumeConfig]):def get_non_retryable_errors(self) -> dict[str, str | None]:return {- "401 Client Error": "Your Asaas API key is invalid or expired. Please generate a new key and reconnect.",+ "401 Client Error": INVALID_KEY_ERROR,"403 Client Error": "Your Asaas API key doesn't have permission for this request. Check the key's account and try again.",}@@ -77,10 +78,7 @@ class AsaasSource(ResumableSource[AsaasSourceConfig, AsaasResumeConfig]):schema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- if validate_asaas_credentials(config.api_key, config.environment):- return True, None-- return False, "Invalid credentials"+ return validate_asaas_credentials(config.api_key, config.environment)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AsaasResumeConfig]:return ResumableSourceManager[AsaasResumeConfig](inputs, AsaasResumeConfig)diff --git a/products/warehouse_sources/sources/asaas/tests/test_asaas.py b/products/warehouse_sources/sources/asaas/tests/test_asaas.pyindex 9d9d71e89cac..bfd79f546ab1 100644--- a/products/warehouse_sources/sources/asaas/tests/test_asaas.py+++ b/products/warehouse_sources/sources/asaas/tests/test_asaas.py@@ -7,8 +7,15 @@ from parameterized import parameterizedfrom products.warehouse_sources.sources.asaas._config import AsaasSourceConfigfrom products.warehouse_sources.sources.asaas.asaas import (+ FORBIDDEN_ERROR,+ INVALID_KEY_ERROR,+ KEY_FORMAT_ERROR,+ KEY_IN_PRODUCTION_ERROR,+ KEY_IN_SANDBOX_ERROR,PRODUCTION_BASE_URL,SANDBOX_BASE_URL,+ UNAVAILABLE_ERROR,+ WRONG_ENVIRONMENT_ERROR,AsaasResumeConfig,base_url,format_date_param,@@ -145,20 +152,75 @@ class TestAsaasSourceResumeBehavior:assert result.requests[0].headers["access_token"] == "test-key"+def _asaas_error(code: str) -> dict[str, Any]:+ return {"errors": [{"code": code, "description": "error description"}]}++class TestValidateCredentials:@parameterized.expand([- (200, True),+ ("accepted", [ScriptedResponse(status=200)], (True, None)),+ (+ "wrong_environment",+ [ScriptedResponse(status=401, json=_asaas_error("invalid_environment"))],+ (False, WRONG_ENVIRONMENT_ERROR),+ ),+ (+ "malformed_key",+ [ScriptedResponse(status=401, json=_asaas_error("invalid_access_token_format"))],+ (False, KEY_FORMAT_ERROR),+ ),+ (+ "revoked_key",+ [ScriptedResponse(status=401, json=_asaas_error("invalid_access_token"))],+ (False, INVALID_KEY_ERROR),+ ),+ ("unauthorized_without_body", [ScriptedResponse(status=401)], (False, INVALID_KEY_ERROR)),+ ("unauthorized_non_json_body", [ScriptedResponse(status=401, body=b"<html>")], (False, INVALID_KEY_ERROR)),+ ("forbidden", [ScriptedResponse(status=403)], (False, FORBIDDEN_ERROR)),+ ("unexpected_status", [ScriptedResponse(status=404)], (False, UNAVAILABLE_ERROR)),+ ("transport_failure", [ConnectionResetError()] * 4, (False, UNAVAILABLE_ERROR)),])- def test_status_code_maps_to_validity(self, status_code: int, expected: bool) -> None:- with scripted_network([ScriptedResponse(status=status_code)]) as network:- assert validate_credentials("test-key", "production") is expected+ def test_response_maps_to_result(+ self, _name: str, script: list[ScriptedResponse | BaseException], expected: tuple[bool, str | None]+ ) -> None:+ with scripted_network(script) as network:+ assert validate_credentials("test-key", "production") == expectedassert network.requests_log[0].path == "/v3/customers"assert network.requests_log[0].param("limit") == "1"assert network.requests_log[0].headers["access_token"] == "test-key"+ @parameterized.expand(+ [+ ("sandbox_key_on_production", "$aact_hmlg_example", "production", KEY_IN_SANDBOX_ERROR),+ ("production_key_on_sandbox", "$aact_prod_example", "sandbox", KEY_IN_PRODUCTION_ERROR),+ ]+ )+ def test_key_for_other_environment_fails_without_a_request(+ self, _name: str, api_key: str, environment: str, expected_error: str+ ) -> None:+ with scripted_network([]) as network:+ assert validate_credentials(api_key, environment) == (False, expected_error)++ assert network.requests_log == []++ @parameterized.expand(+ [+ ("production_key", "$aact_prod_example", "production", PRODUCTION_BASE_URL),+ ("sandbox_key", "$aact_hmlg_example", "sandbox", SANDBOX_BASE_URL),+ ("key_without_environment_prefix", "$aact_example", "sandbox", SANDBOX_BASE_URL),+ ]+ )+ def test_key_matching_environment_is_checked_against_that_host(+ self, _name: str, api_key: str, environment: str, expected_base_url: str+ ) -> None:+ with scripted_network([ScriptedResponse(status=200)]) as network:+ assert validate_credentials(api_key, environment) == (True, None)++ assert network.requests_log[0].url.startswith(f"{expected_base_url}/v3/customers")+class TestAsaasSource:def setup_method(self) -> None:@@ -171,12 +233,11 @@ class TestAsaasSource:assert self.source.default_version == "v3"assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")- @parameterized.expand([(True, True, None), (False, False, "Invalid credentials")])- def test_validate_credentials(self, mock_return: bool, expected_valid: bool, expected_message) -> None:- with mock.patch(VALIDATE_PATCH, return_value=mock_return) as mock_validate:- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)+ @parameterized.expand([((True, None),), ((False, INVALID_KEY_ERROR),)])+ def test_validate_credentials(self, result: tuple[bool, str | None]) -> None:+ with mock.patch(VALIDATE_PATCH, return_value=result) as mock_validate:+ assert self.source.validate_credentials(self.config, self.team_id) == result- assert (is_valid, error_message) == (expected_valid, expected_message)mock_validate.assert_called_once_with("test-key", "production")@parameterized.expand(