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(aws-cost-explorer): translate AWS denials instead of echoing them (#97201)

Tom Owers7b650ab7b098
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
index e2d741dbd5ce..719afad77cc8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py
@@ -13,6 +13,8 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from urllib3.util.retry import Retry
+from posthog.exceptions_capture import capture_exception
+
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.settings import (
AWS_COST_EXPLORER_ENDPOINTS,
CE_CONTENT_TYPE,
@@ -54,7 +56,9 @@ _CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
class AwsCostExplorerError(Exception):
- pass
+ def __init__(self, message: str, code: str | None = None) -> None:
+ super().__init__(message)
+ self.code = code
class AwsCostExplorerThrottledError(AwsCostExplorerError):
@@ -261,8 +265,8 @@ def error_for_response(response: requests.Response) -> AwsCostExplorerError:
# 429/5xx are already retried by the tracked transport; only the app-level throttling codes
# (returned as HTTP 400) need a second, bounded retry here.
if code in THROTTLING_ERROR_CODES:
- return AwsCostExplorerThrottledError(text)
- return AwsCostExplorerError(text)
+ return AwsCostExplorerThrottledError(text, code)
+ return AwsCostExplorerError(text, code)
def make_session(secret_access_key: str, session_token: Optional[str]) -> requests.Session:
@@ -308,6 +312,29 @@ def send_operation(
return response.json()
+# AWS error code -> the message the setup wizard shows. AWS answers a denied `GetCostAndUsage`
+# with the calling identity's IAM ARN (and so its account id) in the response text, so the raw
+# error can never be surfaced. `AwsCostExplorerSource.get_non_retryable_errors` reuses these for
+# the sync path, keyed on the stringified error.
+VALIDATION_ERROR_MESSAGES: dict[str, str] = {
+ "UnrecognizedClientException": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",
+ "InvalidClientTokenId": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",
+ "SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",
+ "InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",
+ "ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",
+ "AccessDeniedException": "These AWS credentials are missing Cost Explorer permissions. Grant ce:GetCostAndUsage, ce:GetReservationUtilization and ce:GetSavingsPlansUtilization to the IAM user or role.",
+ "DataUnavailableException": "AWS has no Cost Explorer data for the requested dates. Cost Explorer has to be enabled on the account, and it can take up to 24 hours to prepare data.",
+ "BillExpirationException": "The requested dates are older than the data AWS keeps. Move the start date forward and try again.",
+}
+
+TRANSIENT_VALIDATION_ERROR = "AWS Cost Explorer is busy or temporarily unavailable. Wait a moment and try again."
+
+GENERIC_VALIDATION_ERROR = (
+ "AWS didn't accept the Cost Explorer request. Check the access key is active and can read Cost Explorer, "
+ "then try again."
+)
+
+
def validate_credentials(
aws_access_key_id: str,
aws_secret_access_key: str,
@@ -332,7 +359,14 @@ def validate_credentials(
payload,
)
except AwsCostExplorerError as error:
- return False, str(error)
+ code = error.code or ""
+ if code in VALIDATION_ERROR_MESSAGES:
+ return False, VALIDATION_ERROR_MESSAGES[code]
+ if code in THROTTLING_ERROR_CODES or code.startswith("HTTP 5"):
+ return False, TRANSIENT_VALIDATION_ERROR
+ # An AWS code we don't have copy for: keep the detail where we can still debug from it.
+ capture_exception(error)
+ return False, GENERIC_VALIDATION_ERROR
except Exception:
return False, "Could not reach the AWS Cost Explorer API"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py
index b3c868e9c0b8..5fd60057f3c6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py
@@ -10,6 +10,7 @@ from posthog.schema import (
)
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.aws_cost_explorer import (
+ VALIDATION_ERROR_MESSAGES,
AwsCostExplorerResumeConfig,
aws_cost_explorer_source,
validate_credentials as validate_aws_cost_explorer_credentials,
@@ -46,17 +47,13 @@ class AwsCostExplorerSource(ResumableSource[AwsCostExplorerSourceConfig, AwsCost
return ExternalDataSourceType.AWSCOSTEXPLORER
def get_non_retryable_errors(self) -> dict[str, str | None]:
- return {
- "AWS Cost Explorer request failed: UnrecognizedClientException": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",
- "AWS Cost Explorer request failed: InvalidClientTokenId": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",
- "AWS Cost Explorer request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",
- "AWS Cost Explorer request failed: InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",
- "AWS Cost Explorer request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",
- "AWS Cost Explorer request failed: AccessDeniedException": "These AWS credentials are missing Cost Explorer permissions. Grant ce:GetCostAndUsage, ce:GetReservationUtilization and ce:GetSavingsPlansUtilization to the IAM user or role.",
- "AWS Cost Explorer request failed: DataUnavailableException": "AWS has no Cost Explorer data for the requested dates. Cost Explorer has to be enabled on the account, and it can take up to 24 hours to prepare data.",
- "AWS Cost Explorer request failed: BillExpirationException": "The requested dates are older than the data AWS keeps. Move the start date forward and try again.",
- "AWS access key ID and secret access key are required": "Enter both an AWS access key ID and a secret access key.",
+ errors: dict[str, str | None] = {
+ f"AWS Cost Explorer request failed: {code}": message for code, message in VALIDATION_ERROR_MESSAGES.items()
}
+ errors["AWS access key ID and secret access key are required"] = (
+ "Enter both an AWS access key ID and a secret access key."
+ )
+ return errors
def get_canonical_descriptions(self) -> CanonicalDescriptions:
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.canonical_descriptions import (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
index 4dcac5654a2d..51eb1df8bf6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
@@ -12,6 +12,9 @@ from tenacity import wait_none
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer import aws_cost_explorer
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.aws_cost_explorer import (
+ GENERIC_VALIDATION_ERROR,
+ TRANSIENT_VALIDATION_ERROR,
+ VALIDATION_ERROR_MESSAGES,
AwsCostExplorerError,
AwsCostExplorerResumeConfig,
AwsCostExplorerThrottledError,
@@ -411,11 +414,24 @@ class TestValidateCredentials:
assert send.call_args[0][2] == "GetCostAndUsage"
- def test_an_api_error_is_surfaced_to_the_user(self) -> None:
- error = AwsCostExplorerError("AWS Cost Explorer request failed: AccessDeniedException - denied")
+ @pytest.mark.parametrize(
+ "code,expected",
+ [
+ ("AccessDeniedException", VALIDATION_ERROR_MESSAGES["AccessDeniedException"]),
+ ("ExpiredTokenException", VALIDATION_ERROR_MESSAGES["ExpiredTokenException"]),
+ ("ThrottlingException", TRANSIENT_VALIDATION_ERROR),
+ ("HTTP 503", TRANSIENT_VALIDATION_ERROR),
+ ("SomeUnmappedException", GENERIC_VALIDATION_ERROR),
+ ],
+ )
+ def test_an_api_error_is_translated_instead_of_echoing_the_aws_text(self, code: str, expected: str) -> None:
+ # A denial names the calling identity, so the AWS text can never reach the wizard.
+ raw = (
+ f"AWS Cost Explorer request failed: {code} - User: arn:aws:iam::000000000000:user/example is not authorized"
+ )
- with mock.patch.object(aws_cost_explorer, "send_operation", side_effect=error):
- assert validate_credentials("key", "secret", None) == (False, str(error))
+ with mock.patch.object(aws_cost_explorer, "send_operation", side_effect=AwsCostExplorerError(raw, code)):
+ assert validate_credentials("key", "secret", None) == (False, expected)
def test_a_transport_failure_does_not_leak_internals(self) -> None:
with mock.patch.object(aws_cost_explorer, "send_operation", side_effect=requests.ConnectionError("boom")):